repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
hametuha/wpametu | src/WPametu/UI/Field/Input.php | Input.build_input | protected function build_input($data, array $fields = [] ){
$fields = implode(' ', $fields);
return sprintf('<input id="%1$s" name="%1$s" type="%2$s" %3$s value="%4$s" />',
$this->name, $this->type, $fields, esc_attr($data));
} | php | protected function build_input($data, array $fields = [] ){
$fields = implode(' ', $fields);
return sprintf('<input id="%1$s" name="%1$s" type="%2$s" %3$s value="%4$s" />',
$this->name, $this->type, $fields, esc_attr($data));
} | [
"protected",
"function",
"build_input",
"(",
"$",
"data",
",",
"array",
"$",
"fields",
"=",
"[",
"]",
")",
"{",
"$",
"fields",
"=",
"implode",
"(",
"' '",
",",
"$",
"fields",
")",
";",
"return",
"sprintf",
"(",
"'<input id=\"%1$s\" name=\"%1$s\" type=\"%2$s\... | build input field
@param mixed $data
@param array $fields
@return string | [
"build",
"input",
"field"
] | train | https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/UI/Field/Input.php#L44-L49 |
hametuha/wpametu | src/WPametu/UI/Field/Input.php | Input.validate | protected function validate($value){
if( parent::validate($value) ){
if( $this->required && empty($value) ){
throw new ValidateException(sprintf($this->__('Field %s is required.'), $this->label));
}
return true;
}else{
return false;
}
} | php | protected function validate($value){
if( parent::validate($value) ){
if( $this->required && empty($value) ){
throw new ValidateException(sprintf($this->__('Field %s is required.'), $this->label));
}
return true;
}else{
return false;
}
} | [
"protected",
"function",
"validate",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"parent",
"::",
"validate",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"required",
"&&",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"throw",
"new",
... | Validate values
@param mixed $value
@return bool
@throws ValidateException | [
"Validate",
"values"
] | train | https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/UI/Field/Input.php#L79-L88 |
nabab/bbn | src/bbn/util/info.php | info.report | public static function report($st)
{
if ( !isset(self::$cli) )
{
global $argv;
self::$cli = isset($argv) ? 1 : false;
}
if ( self::$cli )
{
if ( \is_string($st) )
echo $st."\n";
else
var_dump($st)."\n";
}
else
{
if ( \is_string($st) )
array_push(self::$info,$st);
else
array_push(self::$info,print_r($st,true));
}
} | php | public static function report($st)
{
if ( !isset(self::$cli) )
{
global $argv;
self::$cli = isset($argv) ? 1 : false;
}
if ( self::$cli )
{
if ( \is_string($st) )
echo $st."\n";
else
var_dump($st)."\n";
}
else
{
if ( \is_string($st) )
array_push(self::$info,$st);
else
array_push(self::$info,print_r($st,true));
}
} | [
"public",
"static",
"function",
"report",
"(",
"$",
"st",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"cli",
")",
")",
"{",
"global",
"$",
"argv",
";",
"self",
"::",
"$",
"cli",
"=",
"isset",
"(",
"$",
"argv",
")",
"?",
"1",
":... | Add information to the $info array
@param string $st
@return null | [
"Add",
"information",
"to",
"the",
"$info",
"array"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/util/info.php#L27-L48 |
nabab/bbn | src/bbn/util/info.php | info.log | public static function log($st,$file='misc')
{
if ( \defined('BBN_DATA_PATH') ){
$log_file = BBN_DATA_PATH.'logs/'.$file.'.log';
$i = debug_backtrace()[0];
$r = "[".date('d/m/Y H:i:s')."]\t".$i['file']." - line ".$i['line']."\n";
if ( !\is_string($st) )
$r .= print_r($st,true);
else
$r .= $st;
$r .= "\n\n";
$s = ( file_exists($log_file) ) ? filesize($log_file) : 0;
if ( $s > 1048576 )
{
file_put_contents($log_file.'.old',file_get_contents($log_file),FILE_APPEND);
file_put_contents($log_file,$r);
}
else
file_put_contents($log_file,$r,FILE_APPEND);
}
} | php | public static function log($st,$file='misc')
{
if ( \defined('BBN_DATA_PATH') ){
$log_file = BBN_DATA_PATH.'logs/'.$file.'.log';
$i = debug_backtrace()[0];
$r = "[".date('d/m/Y H:i:s')."]\t".$i['file']." - line ".$i['line']."\n";
if ( !\is_string($st) )
$r .= print_r($st,true);
else
$r .= $st;
$r .= "\n\n";
$s = ( file_exists($log_file) ) ? filesize($log_file) : 0;
if ( $s > 1048576 )
{
file_put_contents($log_file.'.old',file_get_contents($log_file),FILE_APPEND);
file_put_contents($log_file,$r);
}
else
file_put_contents($log_file,$r,FILE_APPEND);
}
} | [
"public",
"static",
"function",
"log",
"(",
"$",
"st",
",",
"$",
"file",
"=",
"'misc'",
")",
"{",
"if",
"(",
"\\",
"defined",
"(",
"'BBN_DATA_PATH'",
")",
")",
"{",
"$",
"log_file",
"=",
"BBN_DATA_PATH",
".",
"'logs/'",
".",
"$",
"file",
".",
"'.log'... | Add information to the $info array
@param string $st
@param string $file
@return null | [
"Add",
"information",
"to",
"the",
"$info",
"array"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/util/info.php#L56-L76 |
mvccore/ext-router-module | src/MvcCore/Ext/Routers/Modules/Route/Instancing.php | Instancing.constructDataModuleNamespace | protected function constructDataModuleNamespace (& $data) {
if (isset($data->module))
$this->SetModule($data->module);
if (isset($data->namespace))
$this->SetNamespace($data->namespace);
} | php | protected function constructDataModuleNamespace (& $data) {
if (isset($data->module))
$this->SetModule($data->module);
if (isset($data->namespace))
$this->SetNamespace($data->namespace);
} | [
"protected",
"function",
"constructDataModuleNamespace",
"(",
"&",
"$",
"data",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"data",
"->",
"module",
")",
")",
"$",
"this",
"->",
"SetModule",
"(",
"$",
"data",
"->",
"module",
")",
";",
"if",
"(",
"isset",
... | If route is initialized by single array argument with all data,
initialize route application module name and optional target controllers
namespace - used only if routed controller is not defined absolutely.
Initialize both properties by setter methods.
@param \stdClass $data Object containing properties `module` and `namespace`.
@return void | [
"If",
"route",
"is",
"initialized",
"by",
"single",
"array",
"argument",
"with",
"all",
"data",
"initialize",
"route",
"application",
"module",
"name",
"and",
"optional",
"target",
"controllers",
"namespace",
"-",
"used",
"only",
"if",
"routed",
"controller",
"i... | train | https://github.com/mvccore/ext-router-module/blob/7695784a451db86cca6a43c98d076803cd0a50a7/src/MvcCore/Ext/Routers/Modules/Route/Instancing.php#L111-L116 |
GrupaZero/api | src/Gzero/Api/Transformer/RouteTransformer.php | RouteTransformer.transform | public function transform($route)
{
$route = $this->entityToArray(Route::class, $route);
return [
'id' => (int) $route['id'],
'createdAt' => $route['created_at'],
'updatedAt' => $route['updated_at']
];
} | php | public function transform($route)
{
$route = $this->entityToArray(Route::class, $route);
return [
'id' => (int) $route['id'],
'createdAt' => $route['created_at'],
'updatedAt' => $route['updated_at']
];
} | [
"public",
"function",
"transform",
"(",
"$",
"route",
")",
"{",
"$",
"route",
"=",
"$",
"this",
"->",
"entityToArray",
"(",
"Route",
"::",
"class",
",",
"$",
"route",
")",
";",
"return",
"[",
"'id'",
"=>",
"(",
"int",
")",
"$",
"route",
"[",
"'id'"... | Transforms route entity
@param Route|array $route route entity
@return array | [
"Transforms",
"route",
"entity"
] | train | https://github.com/GrupaZero/api/blob/fc544bb6057274e9d5e7b617346c3f854ea5effd/src/Gzero/Api/Transformer/RouteTransformer.php#L35-L43 |
Isset/pushnotification | src/PushNotification/Core/NotifierAbstract.php | NotifierAbstract.send | public function send(Message $message, string $connectionName = null): MessageEnvelope
{
if (!$this->handles($message)) {
throw new LogicException('Message of type ' . get_class($message) . " couldn't be handled by this notifier");
}
return $this->sendMessage($message, $connectionName);
} | php | public function send(Message $message, string $connectionName = null): MessageEnvelope
{
if (!$this->handles($message)) {
throw new LogicException('Message of type ' . get_class($message) . " couldn't be handled by this notifier");
}
return $this->sendMessage($message, $connectionName);
} | [
"public",
"function",
"send",
"(",
"Message",
"$",
"message",
",",
"string",
"$",
"connectionName",
"=",
"null",
")",
":",
"MessageEnvelope",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"handles",
"(",
"$",
"message",
")",
")",
"{",
"throw",
"new",
"LogicE... | @param Message $message
@param string $connectionName
@throws LogicException
@return MessageEnvelope | [
"@param",
"Message",
"$message",
"@param",
"string",
"$connectionName"
] | train | https://github.com/Isset/pushnotification/blob/5e7634dc6b1cf4f7c371d1890243a25252db0d85/src/PushNotification/Core/NotifierAbstract.php#L73-L80 |
Isset/pushnotification | src/PushNotification/Core/NotifierAbstract.php | NotifierAbstract.queue | public function queue(Message $message, string $connectionName = null): MessageEnvelope
{
if (!$this->handles($message)) {
throw new LogicException('Message of type ' . get_class($message) . " couldn't be handled by this notifier");
}
return $this->addToQueue($message, $connectionName);
} | php | public function queue(Message $message, string $connectionName = null): MessageEnvelope
{
if (!$this->handles($message)) {
throw new LogicException('Message of type ' . get_class($message) . " couldn't be handled by this notifier");
}
return $this->addToQueue($message, $connectionName);
} | [
"public",
"function",
"queue",
"(",
"Message",
"$",
"message",
",",
"string",
"$",
"connectionName",
"=",
"null",
")",
":",
"MessageEnvelope",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"handles",
"(",
"$",
"message",
")",
")",
"{",
"throw",
"new",
"Logic... | @param Message $message
@param string $connectionName
@throws ConnectionHandlerException
@throws LogicException
@return MessageEnvelope | [
"@param",
"Message",
"$message",
"@param",
"string",
"$connectionName"
] | train | https://github.com/Isset/pushnotification/blob/5e7634dc6b1cf4f7c371d1890243a25252db0d85/src/PushNotification/Core/NotifierAbstract.php#L91-L98 |
Isset/pushnotification | src/PushNotification/Core/NotifierAbstract.php | NotifierAbstract.flushQueue | public function flushQueue(string $connectionName = null)
{
if (empty($this->queues)) {
return;
}
if ($connectionName === null) {
foreach ($this->queues as $queueConnectionName => $queue) {
$this->flushQueueItem($queueConnectionName, $queue);
}
} elseif (array_key_exists($connectionName, $this->queues)) {
$this->flushQueueItem($connectionName, $this->queues[$connectionName]);
}
} | php | public function flushQueue(string $connectionName = null)
{
if (empty($this->queues)) {
return;
}
if ($connectionName === null) {
foreach ($this->queues as $queueConnectionName => $queue) {
$this->flushQueueItem($queueConnectionName, $queue);
}
} elseif (array_key_exists($connectionName, $this->queues)) {
$this->flushQueueItem($connectionName, $this->queues[$connectionName]);
}
} | [
"public",
"function",
"flushQueue",
"(",
"string",
"$",
"connectionName",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"queues",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"$",
"connectionName",
"===",
"null",
")",
"{",
"fore... | Flushes the queue to the notifier queues.
@param string $connectionName
@throws NotifyFailedException
@throws ConnectionException
@throws ConnectionHandlerException | [
"Flushes",
"the",
"queue",
"to",
"the",
"notifier",
"queues",
"."
] | train | https://github.com/Isset/pushnotification/blob/5e7634dc6b1cf4f7c371d1890243a25252db0d85/src/PushNotification/Core/NotifierAbstract.php#L109-L122 |
Isset/pushnotification | src/PushNotification/Core/NotifierAbstract.php | NotifierAbstract.addToQueue | protected function addToQueue(Message $message, string $connectionName = null): MessageEnvelope
{
$envelope = $this->createMessageEnvelope($message);
if ($connectionName === null) {
$connectionName = $this->connectionHandler->getDefaultConnection()->getType();
}
if (!array_key_exists($connectionName, $this->queues)) {
$this->queues[$connectionName] = new MessageEnvelopeQueueImpl();
}
$this->queues[$connectionName]->add($envelope);
return $envelope;
} | php | protected function addToQueue(Message $message, string $connectionName = null): MessageEnvelope
{
$envelope = $this->createMessageEnvelope($message);
if ($connectionName === null) {
$connectionName = $this->connectionHandler->getDefaultConnection()->getType();
}
if (!array_key_exists($connectionName, $this->queues)) {
$this->queues[$connectionName] = new MessageEnvelopeQueueImpl();
}
$this->queues[$connectionName]->add($envelope);
return $envelope;
} | [
"protected",
"function",
"addToQueue",
"(",
"Message",
"$",
"message",
",",
"string",
"$",
"connectionName",
"=",
"null",
")",
":",
"MessageEnvelope",
"{",
"$",
"envelope",
"=",
"$",
"this",
"->",
"createMessageEnvelope",
"(",
"$",
"message",
")",
";",
"if",... | @param Message $message
@param string|null $connectionName
@throws ConnectionHandlerException
@return MessageEnvelope | [
"@param",
"Message",
"$message",
"@param",
"string|null",
"$connectionName"
] | train | https://github.com/Isset/pushnotification/blob/5e7634dc6b1cf4f7c371d1890243a25252db0d85/src/PushNotification/Core/NotifierAbstract.php#L132-L144 |
antaresproject/notifications | resources/database/seeds/EmailSmsSentNoificationSeeder.php | EmailSmsSentNoificationSeeder.run | public function run()
{
DB::beginTransaction();
try {
$this->down();
$this->addNotification([
'category' => 'default',
'type' => 'admin',
'severity' => 'high',
'event' => 'sms.notification_not_sent',
'contents' => [
'en' => [
'title' => 'Sms notification send failed',
'content' => file_get_contents(__DIR__ . '/../../views/notification/sms_notification_not_sent.twig')
],
]
]);
$this->addNotification([
'category' => 'default',
'type' => 'admin',
'severity' => 'medium',
'event' => 'sms.notification_sent',
'contents' => [
'en' => [
'title' => 'Sms notification send success',
'content' => file_get_contents(__DIR__ . '/../../views/notification/sms_notification_sent.twig')
],
]
]);
$this->addNotification([
'category' => 'default',
'type' => 'admin',
'severity' => 'high',
'event' => 'email.notification_not_sent',
'contents' => [
'en' => [
'title' => 'Email notification send failed',
'content' => file_get_contents(__DIR__ . '/../../views/notification/email_notification_not_sent.twig')
],
]
]);
$this->addNotification([
'category' => 'default',
'type' => 'admin',
'severity' => 'medium',
'event' => 'email.notification_sent',
'contents' => [
'en' => [
'title' => 'Email notification send success',
'content' => file_get_contents(__DIR__ . '/../../views/notification/email_notification_sent.twig')
],
]
]);
} catch (Exception $ex) {
DB::rollback();
throw $ex;
}
DB::commit();
} | php | public function run()
{
DB::beginTransaction();
try {
$this->down();
$this->addNotification([
'category' => 'default',
'type' => 'admin',
'severity' => 'high',
'event' => 'sms.notification_not_sent',
'contents' => [
'en' => [
'title' => 'Sms notification send failed',
'content' => file_get_contents(__DIR__ . '/../../views/notification/sms_notification_not_sent.twig')
],
]
]);
$this->addNotification([
'category' => 'default',
'type' => 'admin',
'severity' => 'medium',
'event' => 'sms.notification_sent',
'contents' => [
'en' => [
'title' => 'Sms notification send success',
'content' => file_get_contents(__DIR__ . '/../../views/notification/sms_notification_sent.twig')
],
]
]);
$this->addNotification([
'category' => 'default',
'type' => 'admin',
'severity' => 'high',
'event' => 'email.notification_not_sent',
'contents' => [
'en' => [
'title' => 'Email notification send failed',
'content' => file_get_contents(__DIR__ . '/../../views/notification/email_notification_not_sent.twig')
],
]
]);
$this->addNotification([
'category' => 'default',
'type' => 'admin',
'severity' => 'medium',
'event' => 'email.notification_sent',
'contents' => [
'en' => [
'title' => 'Email notification send success',
'content' => file_get_contents(__DIR__ . '/../../views/notification/email_notification_sent.twig')
],
]
]);
} catch (Exception $ex) {
DB::rollback();
throw $ex;
}
DB::commit();
} | [
"public",
"function",
"run",
"(",
")",
"{",
"DB",
"::",
"beginTransaction",
"(",
")",
";",
"try",
"{",
"$",
"this",
"->",
"down",
"(",
")",
";",
"$",
"this",
"->",
"addNotification",
"(",
"[",
"'category'",
"=>",
"'default'",
",",
"'type'",
"=>",
"'a... | Dodaje dane do tabel
@return void | [
"Dodaje",
"dane",
"do",
"tabel"
] | train | https://github.com/antaresproject/notifications/blob/60de743477b7e9cbb51de66da5fd9461adc9dd8a/resources/database/seeds/EmailSmsSentNoificationSeeder.php#L31-L95 |
wenbinye/PhalconX | src/Di/ServiceProvider.php | ServiceProvider.provide | public function provide($name, $args)
{
$services = $this->getServices();
if (isset($services[$name])) {
return (new Service($name, $services[$name]))
->resolve($args, $this->getDi());
} else {
$method = self::METHOD_PREFIX . $name;
if (method_exists($this, $method)) {
if (empty($args)) {
return $this->$method();
} else {
return call_user_func_array([$this, $method], $args);
}
} else {
throw new Exception("Cannot load '{$name}' from " . get_class($this));
}
}
} | php | public function provide($name, $args)
{
$services = $this->getServices();
if (isset($services[$name])) {
return (new Service($name, $services[$name]))
->resolve($args, $this->getDi());
} else {
$method = self::METHOD_PREFIX . $name;
if (method_exists($this, $method)) {
if (empty($args)) {
return $this->$method();
} else {
return call_user_func_array([$this, $method], $args);
}
} else {
throw new Exception("Cannot load '{$name}' from " . get_class($this));
}
}
} | [
"public",
"function",
"provide",
"(",
"$",
"name",
",",
"$",
"args",
")",
"{",
"$",
"services",
"=",
"$",
"this",
"->",
"getServices",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"services",
"[",
"$",
"name",
"]",
")",
")",
"{",
"return",
"(",
... | Creates service instance
@param string $name service name
@param array $args arguments to create instance | [
"Creates",
"service",
"instance"
] | train | https://github.com/wenbinye/PhalconX/blob/0d2e1480e722dde56ccd23b2e8a5c8ac6ac2f8e1/src/Di/ServiceProvider.php#L26-L44 |
wenbinye/PhalconX | src/Di/ServiceProvider.php | ServiceProvider.getNames | public function getNames()
{
$names = array_keys($this->getServices());
$len = strlen(self::METHOD_PREFIX);
foreach (get_class_methods($this) as $method) {
if (Text::startsWith($method, self::METHOD_PREFIX)) {
$name = lcfirst(substr($method, $len));
if ($name) {
$names[] = $name;
}
}
}
return $names;
} | php | public function getNames()
{
$names = array_keys($this->getServices());
$len = strlen(self::METHOD_PREFIX);
foreach (get_class_methods($this) as $method) {
if (Text::startsWith($method, self::METHOD_PREFIX)) {
$name = lcfirst(substr($method, $len));
if ($name) {
$names[] = $name;
}
}
}
return $names;
} | [
"public",
"function",
"getNames",
"(",
")",
"{",
"$",
"names",
"=",
"array_keys",
"(",
"$",
"this",
"->",
"getServices",
"(",
")",
")",
";",
"$",
"len",
"=",
"strlen",
"(",
"self",
"::",
"METHOD_PREFIX",
")",
";",
"foreach",
"(",
"get_class_methods",
"... | Gets all service names | [
"Gets",
"all",
"service",
"names"
] | train | https://github.com/wenbinye/PhalconX/blob/0d2e1480e722dde56ccd23b2e8a5c8ac6ac2f8e1/src/Di/ServiceProvider.php#L49-L62 |
blast-project/BaseEntitiesBundle | src/Command/UpdateSearchCommand.php | UpdateSearchCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$name = strtr($input->getArgument('name'), '/', '\\');
if (false !== $pos = strpos($name, ':')) {
$name = $this->getContainer()->get('doctrine')->getAliasNamespace(substr($name, 0, $pos)) . '\\' . substr($name, $pos + 1);
}
if (class_exists($name)) {
$output->writeln(sprintf('Updating search index for entity "<info>%s</info>"', $name));
} else {
throw new \RuntimeException(sprintf('%s class doesn\'t exist.', $name));
}
// Check if the entity has the Searchable trait
$reflector = new \ReflectionClass($name);
$traits = $reflector->getTraitNames();
if (!in_array('Blast\BaseEntitiesBundle\Entity\Traits\Searchable', $traits)) {
throw new \RuntimeException(sprintf('%s class doesn\'t have the Searchable trait.', $reflector->getName()));
}
$em = $this->getContainer()->get('doctrine')->getEntityManager();
$metadata = $em->getClassMetadata($name);
$searchHandler = $this->getContainer()->get('blast_base_entities.search_handler');
$searchHandler->handleEntity($metadata);
$searchHandler->batchUpdate();
$output->writeln('DONE');
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$name = strtr($input->getArgument('name'), '/', '\\');
if (false !== $pos = strpos($name, ':')) {
$name = $this->getContainer()->get('doctrine')->getAliasNamespace(substr($name, 0, $pos)) . '\\' . substr($name, $pos + 1);
}
if (class_exists($name)) {
$output->writeln(sprintf('Updating search index for entity "<info>%s</info>"', $name));
} else {
throw new \RuntimeException(sprintf('%s class doesn\'t exist.', $name));
}
// Check if the entity has the Searchable trait
$reflector = new \ReflectionClass($name);
$traits = $reflector->getTraitNames();
if (!in_array('Blast\BaseEntitiesBundle\Entity\Traits\Searchable', $traits)) {
throw new \RuntimeException(sprintf('%s class doesn\'t have the Searchable trait.', $reflector->getName()));
}
$em = $this->getContainer()->get('doctrine')->getEntityManager();
$metadata = $em->getClassMetadata($name);
$searchHandler = $this->getContainer()->get('blast_base_entities.search_handler');
$searchHandler->handleEntity($metadata);
$searchHandler->batchUpdate();
$output->writeln('DONE');
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"name",
"=",
"strtr",
"(",
"$",
"input",
"->",
"getArgument",
"(",
"'name'",
")",
",",
"'/'",
",",
"'\\\\'",
")",
";",
"if",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/blast-project/BaseEntitiesBundle/blob/abd06891fc38922225ab7e4fcb437a286ba2c0c4/src/Command/UpdateSearchCommand.php#L54-L82 |
brick/di | src/Scope/Singleton.php | Singleton.get | public function get(Definition $definition, Container $container)
{
if (! $this->resolved) {
$this->result = $definition->resolve($container);
$this->resolved = true;
}
return $this->result;
} | php | public function get(Definition $definition, Container $container)
{
if (! $this->resolved) {
$this->result = $definition->resolve($container);
$this->resolved = true;
}
return $this->result;
} | [
"public",
"function",
"get",
"(",
"Definition",
"$",
"definition",
",",
"Container",
"$",
"container",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"resolved",
")",
"{",
"$",
"this",
"->",
"result",
"=",
"$",
"definition",
"->",
"resolve",
"(",
"$",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/brick/di/blob/6ced82ab3623b8f1470317d38cbd2de855e7aa3d/src/Scope/Singleton.php#L29-L37 |
brick/di | src/Definition/BindingDefinition.php | BindingDefinition.resolve | public function resolve(Container $container)
{
$parameters = $this->getParameters($container, $this->parameters);
if ($this->target instanceof \Closure) {
return $container->getInjector()->invoke($this->target, $parameters);
}
return $container->getInjector()->instantiate($this->target, $parameters);
} | php | public function resolve(Container $container)
{
$parameters = $this->getParameters($container, $this->parameters);
if ($this->target instanceof \Closure) {
return $container->getInjector()->invoke($this->target, $parameters);
}
return $container->getInjector()->instantiate($this->target, $parameters);
} | [
"public",
"function",
"resolve",
"(",
"Container",
"$",
"container",
")",
"{",
"$",
"parameters",
"=",
"$",
"this",
"->",
"getParameters",
"(",
"$",
"container",
",",
"$",
"this",
"->",
"parameters",
")",
";",
"if",
"(",
"$",
"this",
"->",
"target",
"i... | {@inheritdoc} | [
"{"
] | train | https://github.com/brick/di/blob/6ced82ab3623b8f1470317d38cbd2de855e7aa3d/src/Definition/BindingDefinition.php#L73-L82 |
brick/di | src/Definition/BindingDefinition.php | BindingDefinition.getParameters | private function getParameters(Container $container, array $parameters) : array
{
$result = [];
foreach ($parameters as $key => $value) {
if (is_array($value)) {
$result[$key] = $this->getParameters($container, $value);
} elseif ($value instanceof Ref) {
$result[$key] = $container->get($value->getKey());
} else {
$result[$key] = $value;
}
}
return $result;
} | php | private function getParameters(Container $container, array $parameters) : array
{
$result = [];
foreach ($parameters as $key => $value) {
if (is_array($value)) {
$result[$key] = $this->getParameters($container, $value);
} elseif ($value instanceof Ref) {
$result[$key] = $container->get($value->getKey());
} else {
$result[$key] = $value;
}
}
return $result;
} | [
"private",
"function",
"getParameters",
"(",
"Container",
"$",
"container",
",",
"array",
"$",
"parameters",
")",
":",
"array",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"parameters",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
... | @param Container $container
@param array $parameters
@return array | [
"@param",
"Container",
"$container",
"@param",
"array",
"$parameters"
] | train | https://github.com/brick/di/blob/6ced82ab3623b8f1470317d38cbd2de855e7aa3d/src/Definition/BindingDefinition.php#L90-L105 |
php-lug/lug | src/Component/Grid/DataSource/Doctrine/MongoDB/DataSourceBuilder.php | DataSourceBuilder.innerJoin | public function innerJoin($join, $alias)
{
$this->queryBuilder->field($join)->notEqual(null);
return $this;
} | php | public function innerJoin($join, $alias)
{
$this->queryBuilder->field($join)->notEqual(null);
return $this;
} | [
"public",
"function",
"innerJoin",
"(",
"$",
"join",
",",
"$",
"alias",
")",
"{",
"$",
"this",
"->",
"queryBuilder",
"->",
"field",
"(",
"$",
"join",
")",
"->",
"notEqual",
"(",
"null",
")",
";",
"return",
"$",
"this",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Component/Grid/DataSource/Doctrine/MongoDB/DataSourceBuilder.php#L76-L81 |
php-lug/lug | src/Component/Grid/DataSource/Doctrine/MongoDB/DataSourceBuilder.php | DataSourceBuilder.createDataSource | public function createDataSource(array $options = [])
{
$queryBuilder = clone $this->queryBuilder;
if (isset($options['all']) && $options['all']) {
return new ArrayDataSource($queryBuilder->getQuery()->getIterator()->toArray());
}
$dataSource = new PagerfantaDataSource(new DoctrineODMMongoDBAdapter($queryBuilder));
$dataSource->setMaxPerPage($this->limit);
$dataSource->setCurrentPage($this->page);
return $dataSource;
} | php | public function createDataSource(array $options = [])
{
$queryBuilder = clone $this->queryBuilder;
if (isset($options['all']) && $options['all']) {
return new ArrayDataSource($queryBuilder->getQuery()->getIterator()->toArray());
}
$dataSource = new PagerfantaDataSource(new DoctrineODMMongoDBAdapter($queryBuilder));
$dataSource->setMaxPerPage($this->limit);
$dataSource->setCurrentPage($this->page);
return $dataSource;
} | [
"public",
"function",
"createDataSource",
"(",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"queryBuilder",
"=",
"clone",
"$",
"this",
"->",
"queryBuilder",
";",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'all'",
"]",
")",
"&&",
"$",
"o... | {@inheritdoc} | [
"{"
] | train | https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Component/Grid/DataSource/Doctrine/MongoDB/DataSourceBuilder.php#L188-L201 |
ienaga/SimpleApiClient | src/api/Client.php | Client.append | public function append()
{
if (!$this->hasMultiHandle()) {
$this->setMultiHandle(curl_multi_init());
}
// init
$this
->initOption()
->buildBody();
$curl = curl_init();
curl_setopt_array($curl, $this->getOptions());
curl_multi_add_handle($this->getMultiHandle(), $curl);
$this->curls[] = $curl;
} | php | public function append()
{
if (!$this->hasMultiHandle()) {
$this->setMultiHandle(curl_multi_init());
}
// init
$this
->initOption()
->buildBody();
$curl = curl_init();
curl_setopt_array($curl, $this->getOptions());
curl_multi_add_handle($this->getMultiHandle(), $curl);
$this->curls[] = $curl;
} | [
"public",
"function",
"append",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"hasMultiHandle",
"(",
")",
")",
"{",
"$",
"this",
"->",
"setMultiHandle",
"(",
"curl_multi_init",
"(",
")",
")",
";",
"}",
"// init",
"$",
"this",
"->",
"initOption",
... | add multi handle | [
"add",
"multi",
"handle"
] | train | https://github.com/ienaga/SimpleApiClient/blob/834a5e5eb043ed901000bf769a4cf16b9dc28d15/src/api/Client.php#L640-L656 |
ienaga/SimpleApiClient | src/api/Client.php | Client.multi | public function multi()
{
$active = null;
do {
curl_multi_exec($this->getMultiHandle(), $active);
} while ($active);
// remove multi handle
foreach ($this->curls as $curl) {
curl_multi_remove_handle($this->getMultiHandle(), $curl);
curl_close($curl);
}
curl_multi_close($this->getMultiHandle());
$this->postMulti();
} | php | public function multi()
{
$active = null;
do {
curl_multi_exec($this->getMultiHandle(), $active);
} while ($active);
// remove multi handle
foreach ($this->curls as $curl) {
curl_multi_remove_handle($this->getMultiHandle(), $curl);
curl_close($curl);
}
curl_multi_close($this->getMultiHandle());
$this->postMulti();
} | [
"public",
"function",
"multi",
"(",
")",
"{",
"$",
"active",
"=",
"null",
";",
"do",
"{",
"curl_multi_exec",
"(",
"$",
"this",
"->",
"getMultiHandle",
"(",
")",
",",
"$",
"active",
")",
";",
"}",
"while",
"(",
"$",
"active",
")",
";",
"// remove mult... | execute multi | [
"execute",
"multi"
] | train | https://github.com/ienaga/SimpleApiClient/blob/834a5e5eb043ed901000bf769a4cf16b9dc28d15/src/api/Client.php#L670-L687 |
FrenzelGmbH/cm-address | models/Address.php | Address.getAddresses | public static function getAddresses($model, $class)
{
$models = self::find()->where([
'entity_id' => $model,
'entity' => $class
])->orderBy('{{%net_frenzel_address}}.created_at DESC')->active()->with(['author'])->all();
return $models;
} | php | public static function getAddresses($model, $class)
{
$models = self::find()->where([
'entity_id' => $model,
'entity' => $class
])->orderBy('{{%net_frenzel_address}}.created_at DESC')->active()->with(['author'])->all();
return $models;
} | [
"public",
"static",
"function",
"getAddresses",
"(",
"$",
"model",
",",
"$",
"class",
")",
"{",
"$",
"models",
"=",
"self",
"::",
"find",
"(",
")",
"->",
"where",
"(",
"[",
"'entity_id'",
"=>",
"$",
"model",
",",
"'entity'",
"=>",
"$",
"class",
"]",
... | [getCommunications description]
@param [type] $model [description]
@param [type] $class [description]
@return [type] [description] | [
"[",
"getCommunications",
"description",
"]"
] | train | https://github.com/FrenzelGmbH/cm-address/blob/4295671dc603beed4bea6c5a7f77dac9846127f3/models/Address.php#L191-L199 |
FrenzelGmbH/cm-address | models/Address.php | Address.validateModelId | public function validateModelId($attribute, $params)
{
/** @var ActiveRecord $class */
$class = Model::findIdentity($this->model_class);
if ($class === null) {
$this->addError($attribute, \Yii::t('net_frenzel_communication', 'ERROR_MSG_INVALID_MODEL_ID'));
} else {
$model = $class->name;
if ($model::find()->where(['id' => $this->entity_id]) === false) {
$this->addError($attribute, \Yii::t('net_frenzel_communication', 'ERROR_MSG_INVALID_MODEL_ID'));
}
}
} | php | public function validateModelId($attribute, $params)
{
/** @var ActiveRecord $class */
$class = Model::findIdentity($this->model_class);
if ($class === null) {
$this->addError($attribute, \Yii::t('net_frenzel_communication', 'ERROR_MSG_INVALID_MODEL_ID'));
} else {
$model = $class->name;
if ($model::find()->where(['id' => $this->entity_id]) === false) {
$this->addError($attribute, \Yii::t('net_frenzel_communication', 'ERROR_MSG_INVALID_MODEL_ID'));
}
}
} | [
"public",
"function",
"validateModelId",
"(",
"$",
"attribute",
",",
"$",
"params",
")",
"{",
"/** @var ActiveRecord $class */",
"$",
"class",
"=",
"Model",
"::",
"findIdentity",
"(",
"$",
"this",
"->",
"model_class",
")",
";",
"if",
"(",
"$",
"class",
"==="... | Model ID validation.
@param string $attribute Attribute name
@param array $params Attribute params
@return mixed | [
"Model",
"ID",
"validation",
"."
] | train | https://github.com/FrenzelGmbH/cm-address/blob/4295671dc603beed4bea6c5a7f77dac9846127f3/models/Address.php#L209-L221 |
FrenzelGmbH/cm-address | models/Address.php | Address.getIPLocation | public static function getIPLocation(){
//initialize the browser
$adapter = new GuzzleHttpAdapter();
//create geocoder
$geocoder = new \Geocoder\Provider\FreeGeoIp($adapter);
if (!isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$client_ip = $_SERVER['REMOTE_ADDR'];
}
else {
$client_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
return $geocoder->geocode($client_ip);
} | php | public static function getIPLocation(){
//initialize the browser
$adapter = new GuzzleHttpAdapter();
//create geocoder
$geocoder = new \Geocoder\Provider\FreeGeoIp($adapter);
if (!isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$client_ip = $_SERVER['REMOTE_ADDR'];
}
else {
$client_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
return $geocoder->geocode($client_ip);
} | [
"public",
"static",
"function",
"getIPLocation",
"(",
")",
"{",
"//initialize the browser",
"$",
"adapter",
"=",
"new",
"GuzzleHttpAdapter",
"(",
")",
";",
"//create geocoder",
"$",
"geocoder",
"=",
"new",
"\\",
"Geocoder",
"\\",
"Provider",
"\\",
"FreeGeoIp",
"... | find the use location based upon his current IP address
@return mixed [description] | [
"find",
"the",
"use",
"location",
"based",
"upon",
"his",
"current",
"IP",
"address"
] | train | https://github.com/FrenzelGmbH/cm-address/blob/4295671dc603beed4bea6c5a7f77dac9846127f3/models/Address.php#L251-L266 |
andrewrcollins/SimpleFinance | src/PennyNotes/SimpleFinance.php | SimpleFinance.fvif | public static function fvif($interestRate, $periods)
{
if (!is_float($interestRate)) {
throw new \InvalidArgumentException('$interestRate is not float');
}
if (!is_int($periods)) {
throw new \InvalidArgumentException('$periods is not int');
}
if ($periods === 0) {
return 1;
}
$interestFactor = $interestRate + 1;
if ($interestFactor == 0) {
return 0;
}
if ($periods === 1) {
return $interestFactor;
}
if ($periods < 0) {
$periods = -$periods;
$interestFactor = 1 / $interestFactor;
}
return pow($interestFactor, $periods);
} | php | public static function fvif($interestRate, $periods)
{
if (!is_float($interestRate)) {
throw new \InvalidArgumentException('$interestRate is not float');
}
if (!is_int($periods)) {
throw new \InvalidArgumentException('$periods is not int');
}
if ($periods === 0) {
return 1;
}
$interestFactor = $interestRate + 1;
if ($interestFactor == 0) {
return 0;
}
if ($periods === 1) {
return $interestFactor;
}
if ($periods < 0) {
$periods = -$periods;
$interestFactor = 1 / $interestFactor;
}
return pow($interestFactor, $periods);
} | [
"public",
"static",
"function",
"fvif",
"(",
"$",
"interestRate",
",",
"$",
"periods",
")",
"{",
"if",
"(",
"!",
"is_float",
"(",
"$",
"interestRate",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'$interestRate is not float'",
")",
... | Future Value Interest Factor (FVIF).
@param float $interestRate interest rate
@param int $periods periods
@throws \InvalidArgumentException if $interestRate is not float
@throws \InvalidArgumentException if $periods is not int
@return float future value interest factor | [
"Future",
"Value",
"Interest",
"Factor",
"(",
"FVIF",
")",
"."
] | train | https://github.com/andrewrcollins/SimpleFinance/blob/d43e57399d1282e8c6da279163364b34d544570e/src/PennyNotes/SimpleFinance.php#L37-L68 |
andrewrcollins/SimpleFinance | src/PennyNotes/SimpleFinance.php | SimpleFinance.pmt | public static function pmt($interestRate, $periods, $presentValue, $futureValue)
{
if (!is_float($interestRate)) {
throw new \InvalidArgumentException('$interestRate is not float');
}
if (!is_int($periods)) {
throw new \InvalidArgumentException('$periods is not int');
}
if ($interestRate === 0) {
$pmt = -1 * ($futureValue + $presentValue) / $periods;
} else {
$numerator = ($presentValue + $futureValue);
$denominator = self::fvif($interestRate, $periods) - 1;
$pmt = -1.0 * (($numerator / $denominator) + $presentValue) * $interestRate;
}
return $pmt;
} | php | public static function pmt($interestRate, $periods, $presentValue, $futureValue)
{
if (!is_float($interestRate)) {
throw new \InvalidArgumentException('$interestRate is not float');
}
if (!is_int($periods)) {
throw new \InvalidArgumentException('$periods is not int');
}
if ($interestRate === 0) {
$pmt = -1 * ($futureValue + $presentValue) / $periods;
} else {
$numerator = ($presentValue + $futureValue);
$denominator = self::fvif($interestRate, $periods) - 1;
$pmt = -1.0 * (($numerator / $denominator) + $presentValue) * $interestRate;
}
return $pmt;
} | [
"public",
"static",
"function",
"pmt",
"(",
"$",
"interestRate",
",",
"$",
"periods",
",",
"$",
"presentValue",
",",
"$",
"futureValue",
")",
"{",
"if",
"(",
"!",
"is_float",
"(",
"$",
"interestRate",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgument... | Regular Payment at Regular Interval (PMT).
@param float $interestRate interest rate
@param int $periods periods
@param float $presentValue present value
@param float $futureValue future value
@throws \InvalidArgumentException if $interestRate is not float
@throws \InvalidArgumentException if $periods is not int
@return float regular payment at regular interval | [
"Regular",
"Payment",
"at",
"Regular",
"Interval",
"(",
"PMT",
")",
"."
] | train | https://github.com/andrewrcollins/SimpleFinance/blob/d43e57399d1282e8c6da279163364b34d544570e/src/PennyNotes/SimpleFinance.php#L83-L104 |
andrewrcollins/SimpleFinance | src/PennyNotes/SimpleFinance.php | SimpleFinance.payment | public static function payment($annualInterest, $months)
{
// convert annual interest rate to monthly interest rate
$interestRate = $annualInterest / 12;
// present value = -1 * [principal] = -25.00
$presentValue = -25;
// future value = 0
$futureValue = 0;
// calculate regular payment at regular interval (PMT).
$pmt = self::pmt($interestRate, $months, $presentValue, $futureValue);
// return result
return $pmt;
} | php | public static function payment($annualInterest, $months)
{
// convert annual interest rate to monthly interest rate
$interestRate = $annualInterest / 12;
// present value = -1 * [principal] = -25.00
$presentValue = -25;
// future value = 0
$futureValue = 0;
// calculate regular payment at regular interval (PMT).
$pmt = self::pmt($interestRate, $months, $presentValue, $futureValue);
// return result
return $pmt;
} | [
"public",
"static",
"function",
"payment",
"(",
"$",
"annualInterest",
",",
"$",
"months",
")",
"{",
"// convert annual interest rate to monthly interest rate",
"$",
"interestRate",
"=",
"$",
"annualInterest",
"/",
"12",
";",
"// present value = -1 * [principal] = -25.00",
... | Calculate regular loan payment.
@param float $annualInterest annual interest rate
@param int $months months
@return float regular loan payment | [
"Calculate",
"regular",
"loan",
"payment",
"."
] | train | https://github.com/andrewrcollins/SimpleFinance/blob/d43e57399d1282e8c6da279163364b34d544570e/src/PennyNotes/SimpleFinance.php#L114-L130 |
andrewrcollins/SimpleFinance | src/PennyNotes/SimpleFinance.php | SimpleFinance.bcfvif | public static function bcfvif($interestRate, $periods)
{
if ($periods === 0) {
return 1;
}
$interestFactor = bcadd($interestRate, 1);
if (bccomp($interestFactor, 0) === 0) {
return 0;
}
if ($periods === 1) {
return $interestFactor;
}
if ($periods < 0) {
$periods = -$periods;
$interestFactor = bcdiv(1, $interestFactor);
}
return bcpow($interestFactor, $periods);
} | php | public static function bcfvif($interestRate, $periods)
{
if ($periods === 0) {
return 1;
}
$interestFactor = bcadd($interestRate, 1);
if (bccomp($interestFactor, 0) === 0) {
return 0;
}
if ($periods === 1) {
return $interestFactor;
}
if ($periods < 0) {
$periods = -$periods;
$interestFactor = bcdiv(1, $interestFactor);
}
return bcpow($interestFactor, $periods);
} | [
"public",
"static",
"function",
"bcfvif",
"(",
"$",
"interestRate",
",",
"$",
"periods",
")",
"{",
"if",
"(",
"$",
"periods",
"===",
"0",
")",
"{",
"return",
"1",
";",
"}",
"$",
"interestFactor",
"=",
"bcadd",
"(",
"$",
"interestRate",
",",
"1",
")",... | Calculate future value interest factor (FVIF).
@param string $interestRate interest rate
@param int $periods periods
@return string future value interest factor | [
"Calculate",
"future",
"value",
"interest",
"factor",
"(",
"FVIF",
")",
"."
] | train | https://github.com/andrewrcollins/SimpleFinance/blob/d43e57399d1282e8c6da279163364b34d544570e/src/PennyNotes/SimpleFinance.php#L140-L163 |
andrewrcollins/SimpleFinance | src/PennyNotes/SimpleFinance.php | SimpleFinance.bcpmt | public static function bcpmt($interestRate, $periods, $presentValue, $futureValue)
{
$pmt = 0;
if (bccomp($interestRate, 0) === 0) {
$pmt = bcadd($futureValue, $presentValue);
$pmt = bcdiv($pmt, $periods);
$pmt = bcmul(-1, $pmt);
} else {
$numerator = bcadd($presentValue, $futureValue);
$denominator = self::bcfvif($interestRate, $periods);
$denominator = bcsub($denominator, 1);
$pmt = bcdiv($numerator, $denominator);
$pmt = bcadd($pmt, $presentValue);
$pmt = bcmul($pmt, $interestRate);
$pmt = bcmul(-1, $pmt);
}
return $pmt;
} | php | public static function bcpmt($interestRate, $periods, $presentValue, $futureValue)
{
$pmt = 0;
if (bccomp($interestRate, 0) === 0) {
$pmt = bcadd($futureValue, $presentValue);
$pmt = bcdiv($pmt, $periods);
$pmt = bcmul(-1, $pmt);
} else {
$numerator = bcadd($presentValue, $futureValue);
$denominator = self::bcfvif($interestRate, $periods);
$denominator = bcsub($denominator, 1);
$pmt = bcdiv($numerator, $denominator);
$pmt = bcadd($pmt, $presentValue);
$pmt = bcmul($pmt, $interestRate);
$pmt = bcmul(-1, $pmt);
}
return $pmt;
} | [
"public",
"static",
"function",
"bcpmt",
"(",
"$",
"interestRate",
",",
"$",
"periods",
",",
"$",
"presentValue",
",",
"$",
"futureValue",
")",
"{",
"$",
"pmt",
"=",
"0",
";",
"if",
"(",
"bccomp",
"(",
"$",
"interestRate",
",",
"0",
")",
"===",
"0",
... | Calculate regular payment at regular interval (PMT).
@param string $interestRate interest rate
@param int $periods periods
@param string $presentValue present value
@param string $futureValue future value
@return string regular payment at regular interval | [
"Calculate",
"regular",
"payment",
"at",
"regular",
"interval",
"(",
"PMT",
")",
"."
] | train | https://github.com/andrewrcollins/SimpleFinance/blob/d43e57399d1282e8c6da279163364b34d544570e/src/PennyNotes/SimpleFinance.php#L175-L196 |
andrewrcollins/SimpleFinance | src/PennyNotes/SimpleFinance.php | SimpleFinance.bcpayment | public static function bcpayment($annualInterest, $months)
{
// convert annual interest rate to monthly interest rate
$interestRate = bcdiv($annualInterest, 12);
// present value = -1 * [principal] = -25.00
$presentValue = -25;
// future value = 0
$futureValue = 0;
// calculate regular payment at regular interval (PMT).
$pmt = self::bcpmt($interestRate, $months, $presentValue, $futureValue);
// return result
return $pmt;
} | php | public static function bcpayment($annualInterest, $months)
{
// convert annual interest rate to monthly interest rate
$interestRate = bcdiv($annualInterest, 12);
// present value = -1 * [principal] = -25.00
$presentValue = -25;
// future value = 0
$futureValue = 0;
// calculate regular payment at regular interval (PMT).
$pmt = self::bcpmt($interestRate, $months, $presentValue, $futureValue);
// return result
return $pmt;
} | [
"public",
"static",
"function",
"bcpayment",
"(",
"$",
"annualInterest",
",",
"$",
"months",
")",
"{",
"// convert annual interest rate to monthly interest rate",
"$",
"interestRate",
"=",
"bcdiv",
"(",
"$",
"annualInterest",
",",
"12",
")",
";",
"// present value = -... | Calculate regular loan payment.
@param string $annualInterest annual interest rate
@param int $months months
@return string regular loan payment | [
"Calculate",
"regular",
"loan",
"payment",
"."
] | train | https://github.com/andrewrcollins/SimpleFinance/blob/d43e57399d1282e8c6da279163364b34d544570e/src/PennyNotes/SimpleFinance.php#L206-L222 |
RhubarbPHP/Module.RestApi | src/UrlHandlers/RestHandler.php | RestHandler.handleInvalidMethod | protected function handleInvalidMethod($method)
{
$emptyResponse = new Response();
$emptyResponse->setHeader("HTTP/1.1 405 Method $method Not Allowed", false);
$emptyResponse->setHeader("Allow", implode(", ", $this->getSupportedHttpMethods()));
throw new ForceResponseException($emptyResponse);
} | php | protected function handleInvalidMethod($method)
{
$emptyResponse = new Response();
$emptyResponse->setHeader("HTTP/1.1 405 Method $method Not Allowed", false);
$emptyResponse->setHeader("Allow", implode(", ", $this->getSupportedHttpMethods()));
throw new ForceResponseException($emptyResponse);
} | [
"protected",
"function",
"handleInvalidMethod",
"(",
"$",
"method",
")",
"{",
"$",
"emptyResponse",
"=",
"new",
"Response",
"(",
")",
";",
"$",
"emptyResponse",
"->",
"setHeader",
"(",
"\"HTTP/1.1 405 Method $method Not Allowed\"",
",",
"false",
")",
";",
"$",
"... | Override to handle the case where an HTTP method is unsupported.
This should throw a ForceResponseException
@param $method
@throws \Rhubarb\Crown\Exceptions\ForceResponseException | [
"Override",
"to",
"handle",
"the",
"case",
"where",
"an",
"HTTP",
"method",
"is",
"unsupported",
"."
] | train | https://github.com/RhubarbPHP/Module.RestApi/blob/825d2b920caed13811971c5eb2784a94417787bd/src/UrlHandlers/RestHandler.php#L210-L217 |
magium/mcm-redis-factory | lib/Factory.php | Factory.factory | public function factory()
{
$redis = new \Redis();
$host = $this->getConfig()->getValue(self::CONFIG_HOST);
$port = $this->getConfig()->getValue(self::CONFIG_PORT);
$timeout = $this->getConfig()->getValue(self::CONFIG_TIMEOUT);
if ($this->getConfig()->getValueFlag(self::CONFIG_PERSISTENT)) {
$redis->pconnect($host, $port, $timeout);
} else {
$redis->connect($host, $port, $timeout);
}
if ($this->getConfig()->hasValue(self::CONFIG_DATABASE)) {
$redis->select($this->getConfig()->getValue(self::CONFIG_DATABASE));
}
return $redis;
} | php | public function factory()
{
$redis = new \Redis();
$host = $this->getConfig()->getValue(self::CONFIG_HOST);
$port = $this->getConfig()->getValue(self::CONFIG_PORT);
$timeout = $this->getConfig()->getValue(self::CONFIG_TIMEOUT);
if ($this->getConfig()->getValueFlag(self::CONFIG_PERSISTENT)) {
$redis->pconnect($host, $port, $timeout);
} else {
$redis->connect($host, $port, $timeout);
}
if ($this->getConfig()->hasValue(self::CONFIG_DATABASE)) {
$redis->select($this->getConfig()->getValue(self::CONFIG_DATABASE));
}
return $redis;
} | [
"public",
"function",
"factory",
"(",
")",
"{",
"$",
"redis",
"=",
"new",
"\\",
"Redis",
"(",
")",
";",
"$",
"host",
"=",
"$",
"this",
"->",
"getConfig",
"(",
")",
"->",
"getValue",
"(",
"self",
"::",
"CONFIG_HOST",
")",
";",
"$",
"port",
"=",
"$... | Creates a configured \Redis instance in the object context
@param ConfigInterface $config
@return \Redis | [
"Creates",
"a",
"configured",
"\\",
"Redis",
"instance",
"in",
"the",
"object",
"context"
] | train | https://github.com/magium/mcm-redis-factory/blob/d5881a7d4834cc13d1f569bb2c94c892b3b48e76/lib/Factory.php#L38-L56 |
Eresus/EresusCMS | src/core/framework/core/3rdparty/dwoo/Dwoo/Adapters/CakePHP/dwoo.php | DwooView.setTemplateDir | public function setTemplateDir($path = VIEW) {
$old = $this->_sv_template_dir;
$this->_sv_template_dir = $path;
return $old;
} | php | public function setTemplateDir($path = VIEW) {
$old = $this->_sv_template_dir;
$this->_sv_template_dir = $path;
return $old;
} | [
"public",
"function",
"setTemplateDir",
"(",
"$",
"path",
"=",
"VIEW",
")",
"{",
"$",
"old",
"=",
"$",
"this",
"->",
"_sv_template_dir",
";",
"$",
"this",
"->",
"_sv_template_dir",
"=",
"$",
"path",
";",
"return",
"$",
"old",
";",
"}"
] | changes the template directory | [
"changes",
"the",
"template",
"directory"
] | train | https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/dwoo/Dwoo/Adapters/CakePHP/dwoo.php#L75-L80 |
hanamura/wp-model | src/WPModel/Post.php | Post._initPost | protected function _initPost()
{
if (!isset($this->_post) && $this->_id) {
$this->_post = get_post($this->_id);
}
} | php | protected function _initPost()
{
if (!isset($this->_post) && $this->_id) {
$this->_post = get_post($this->_id);
}
} | [
"protected",
"function",
"_initPost",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"_post",
")",
"&&",
"$",
"this",
"->",
"_id",
")",
"{",
"$",
"this",
"->",
"_post",
"=",
"get_post",
"(",
"$",
"this",
"->",
"_id",
")",
";",
... | init post | [
"init",
"post"
] | train | https://github.com/hanamura/wp-model/blob/69925d1c2072e6e78a0b36b5e84d270839cc7419/src/WPModel/Post.php#L94-L99 |
hanamura/wp-model | src/WPModel/Post.php | Post._permalink | protected function _permalink()
{
if (!isset($this->_permalink)) {
$this->_permalink = get_permalink($this->id);
}
return $this->_permalink;
} | php | protected function _permalink()
{
if (!isset($this->_permalink)) {
$this->_permalink = get_permalink($this->id);
}
return $this->_permalink;
} | [
"protected",
"function",
"_permalink",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"_permalink",
")",
")",
"{",
"$",
"this",
"->",
"_permalink",
"=",
"get_permalink",
"(",
"$",
"this",
"->",
"id",
")",
";",
"}",
"return",
"$",
"... | method properties | [
"method",
"properties"
] | train | https://github.com/hanamura/wp-model/blob/69925d1c2072e6e78a0b36b5e84d270839cc7419/src/WPModel/Post.php#L104-L110 |
hanamura/wp-model | src/WPModel/Post.php | Post._meta | protected function _meta()
{
if (!isset($this->_meta)) {
$this->_meta = new PostMeta($this->id);
}
return $this->_meta;
} | php | protected function _meta()
{
if (!isset($this->_meta)) {
$this->_meta = new PostMeta($this->id);
}
return $this->_meta;
} | [
"protected",
"function",
"_meta",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"_meta",
")",
")",
"{",
"$",
"this",
"->",
"_meta",
"=",
"new",
"PostMeta",
"(",
"$",
"this",
"->",
"id",
")",
";",
"}",
"return",
"$",
"this",
"-... | meta | [
"meta"
] | train | https://github.com/hanamura/wp-model/blob/69925d1c2072e6e78a0b36b5e84d270839cc7419/src/WPModel/Post.php#L183-L189 |
hanamura/wp-model | src/WPModel/Post.php | Post._image | protected function _image($options = null)
{
$options = array_merge(array('size' => 'full'), $options ?: array());
if ($sources = $this->images) {
return isset($sources[$options['size']]) ? $sources[$options['size']] : $sources['full'];
} else {
return null;
}
} | php | protected function _image($options = null)
{
$options = array_merge(array('size' => 'full'), $options ?: array());
if ($sources = $this->images) {
return isset($sources[$options['size']]) ? $sources[$options['size']] : $sources['full'];
} else {
return null;
}
} | [
"protected",
"function",
"_image",
"(",
"$",
"options",
"=",
"null",
")",
"{",
"$",
"options",
"=",
"array_merge",
"(",
"array",
"(",
"'size'",
"=>",
"'full'",
")",
",",
"$",
"options",
"?",
":",
"array",
"(",
")",
")",
";",
"if",
"(",
"$",
"source... | image source | [
"image",
"source"
] | train | https://github.com/hanamura/wp-model/blob/69925d1c2072e6e78a0b36b5e84d270839cc7419/src/WPModel/Post.php#L192-L201 |
hanamura/wp-model | src/WPModel/Post.php | Post._neighbor | protected function _neighbor($options)
{
global $wpdb;
// options
// -------
$options = array_merge(array(
'post_type' => $this->post_type,
'direction' => null,
), $options);
// post types
$post_type = $options['post_type'];
$post_type = is_array($post_type) ? $post_type : array($post_type);
$post_type_string = array_map(function($post_type) use($wpdb) {
return $wpdb->prepare('%s', $post_type);
}, $post_type);
$post_type_string = implode(', ', $post_type_string);
// direction
$direction = $options['direction'];
if ($direction !== 'prev' && $direction !== 'next') {
throw new \Exception('direction must be `prev` or `next`');
}
// internal
$hook_string = ($direction === 'prev') ? 'previous' : 'next';
$operator = ($direction === 'prev') ? '<' : '>';
$order = ($direction === 'prev') ? 'DESC' : 'ASC';
$cache_key = "${direction}.${post_type_string}";
// get cache
// ---------
$post = wp_cache_get($cache_key, __CLASS__);
if ($post !== false) {
return $post;
}
// query
// -----
// join
$join = apply_filters("get_{$hook_string}_post_join", '', false, '');
// where
$where = apply_filters(
"get_{$hook_string}_post_where",
$wpdb->prepare(
"WHERE p.post_date {$operator} %s"
. " AND p.post_type IN ({$post_type_string})"
. " AND p.post_status = 'publish'"
, $this->post_date
),
false,
''
);
// sort
$sort = apply_filters(
"get_{$hook_string}_post_sort",
"ORDER BY p.post_date {$order} LIMIT 1"
);
// query
$query = "SELECT p.ID FROM {$wpdb->posts} AS p {$join} {$where} {$sort}";
// id
$id = $wpdb->get_row($query);
// set cache
// ---------
$post = $id ? get_post($id->ID) : null;
wp_cache_set($cache_key, $post, __CLASS__);
return $post;
} | php | protected function _neighbor($options)
{
global $wpdb;
// options
// -------
$options = array_merge(array(
'post_type' => $this->post_type,
'direction' => null,
), $options);
// post types
$post_type = $options['post_type'];
$post_type = is_array($post_type) ? $post_type : array($post_type);
$post_type_string = array_map(function($post_type) use($wpdb) {
return $wpdb->prepare('%s', $post_type);
}, $post_type);
$post_type_string = implode(', ', $post_type_string);
// direction
$direction = $options['direction'];
if ($direction !== 'prev' && $direction !== 'next') {
throw new \Exception('direction must be `prev` or `next`');
}
// internal
$hook_string = ($direction === 'prev') ? 'previous' : 'next';
$operator = ($direction === 'prev') ? '<' : '>';
$order = ($direction === 'prev') ? 'DESC' : 'ASC';
$cache_key = "${direction}.${post_type_string}";
// get cache
// ---------
$post = wp_cache_get($cache_key, __CLASS__);
if ($post !== false) {
return $post;
}
// query
// -----
// join
$join = apply_filters("get_{$hook_string}_post_join", '', false, '');
// where
$where = apply_filters(
"get_{$hook_string}_post_where",
$wpdb->prepare(
"WHERE p.post_date {$operator} %s"
. " AND p.post_type IN ({$post_type_string})"
. " AND p.post_status = 'publish'"
, $this->post_date
),
false,
''
);
// sort
$sort = apply_filters(
"get_{$hook_string}_post_sort",
"ORDER BY p.post_date {$order} LIMIT 1"
);
// query
$query = "SELECT p.ID FROM {$wpdb->posts} AS p {$join} {$where} {$sort}";
// id
$id = $wpdb->get_row($query);
// set cache
// ---------
$post = $id ? get_post($id->ID) : null;
wp_cache_set($cache_key, $post, __CLASS__);
return $post;
} | [
"protected",
"function",
"_neighbor",
"(",
"$",
"options",
")",
"{",
"global",
"$",
"wpdb",
";",
"// options",
"// -------",
"$",
"options",
"=",
"array_merge",
"(",
"array",
"(",
"'post_type'",
"=>",
"$",
"this",
"->",
"post_type",
",",
"'direction'",
"=>",... | neighbor | [
"neighbor"
] | train | https://github.com/hanamura/wp-model/blob/69925d1c2072e6e78a0b36b5e84d270839cc7419/src/WPModel/Post.php#L263-L351 |
stk2k/net-driver | src/Http/HttpResponse.php | HttpResponse.jsonDecode | public function jsonDecode()
{
$json = json_decode($this->body, true);
if ($json===null){
throw new JsonFormatException($this->body);
}
return $json;
} | php | public function jsonDecode()
{
$json = json_decode($this->body, true);
if ($json===null){
throw new JsonFormatException($this->body);
}
return $json;
} | [
"public",
"function",
"jsonDecode",
"(",
")",
"{",
"$",
"json",
"=",
"json_decode",
"(",
"$",
"this",
"->",
"body",
",",
"true",
")",
";",
"if",
"(",
"$",
"json",
"===",
"null",
")",
"{",
"throw",
"new",
"JsonFormatException",
"(",
"$",
"this",
"->",... | Decode as JSON
@return array|object
@throws JsonFormatException | [
"Decode",
"as",
"JSON"
] | train | https://github.com/stk2k/net-driver/blob/75e0bc1a95ba430dd9ed9e69f6a0a5dd8f2e7b1c/src/Http/HttpResponse.php#L82-L89 |
Eresus/EresusCMS | src/core/framework/core/3rdparty/ezcomponents/Database/src/sqlabstraction/implementations/query_select_mssql.php | ezcQuerySelectMssql.orderBy | public function orderBy( $column, $type = self::ASC )
{
if ( $this->invertedOrderString )
{
$this->invertedOrderString .= ', ';
}
else
{
$this->invertedOrderString = 'ORDER BY ';
}
$this->invertedOrderString .= $column . ' ' . ( $type == self::ASC ? self::DESC : self::ASC );
return parent::orderBy( $column, $type );
} | php | public function orderBy( $column, $type = self::ASC )
{
if ( $this->invertedOrderString )
{
$this->invertedOrderString .= ', ';
}
else
{
$this->invertedOrderString = 'ORDER BY ';
}
$this->invertedOrderString .= $column . ' ' . ( $type == self::ASC ? self::DESC : self::ASC );
return parent::orderBy( $column, $type );
} | [
"public",
"function",
"orderBy",
"(",
"$",
"column",
",",
"$",
"type",
"=",
"self",
"::",
"ASC",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"invertedOrderString",
")",
"{",
"$",
"this",
"->",
"invertedOrderString",
".=",
"', '",
";",
"}",
"else",
"{",
"... | Saves the ordered columns in an internal array so we can invert that order
if we need to in the limit() workaround
@param string $column a column name in the result set
@param string $type if the column should be sorted ascending or descending.
you can specify this using ezcQuerySelect::ASC or ezcQuerySelect::DESC
@return ezcQuery a pointer to $this | [
"Saves",
"the",
"ordered",
"columns",
"in",
"an",
"internal",
"array",
"so",
"we",
"can",
"invert",
"that",
"order",
"if",
"we",
"need",
"to",
"in",
"the",
"limit",
"()",
"workaround"
] | train | https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Database/src/sqlabstraction/implementations/query_select_mssql.php#L94-L106 |
Eresus/EresusCMS | src/core/framework/core/3rdparty/ezcomponents/Database/src/sqlabstraction/implementations/query_select_mssql.php | ezcQuerySelectMssql.getQuery | public function getQuery()
{
$query = parent::getQuery();
if ( $this->hasLimit )
{
if ( $this->offset)
{
if ( !$this->orderString )
{
// Uh ow. We need some columns to sort in the oposite order to make this work
throw new ezcQueryInvalidException( "LIMIT workaround for MS SQL", "orderBy() was not called before getQuery()." );
}
return 'SELECT * FROM ( SELECT TOP ' . $this->limit . ' * FROM ( ' . self::top( $this->offset + $this->limit, $query ) . ' ) AS ezcDummyTable1 ' . $this->invertedOrderString . ' ) AS ezcDummyTable2 ' . $this->orderString;
}
return self::top( $this->limit, $query );
}
return $query;
} | php | public function getQuery()
{
$query = parent::getQuery();
if ( $this->hasLimit )
{
if ( $this->offset)
{
if ( !$this->orderString )
{
// Uh ow. We need some columns to sort in the oposite order to make this work
throw new ezcQueryInvalidException( "LIMIT workaround for MS SQL", "orderBy() was not called before getQuery()." );
}
return 'SELECT * FROM ( SELECT TOP ' . $this->limit . ' * FROM ( ' . self::top( $this->offset + $this->limit, $query ) . ' ) AS ezcDummyTable1 ' . $this->invertedOrderString . ' ) AS ezcDummyTable2 ' . $this->orderString;
}
return self::top( $this->limit, $query );
}
return $query;
} | [
"public",
"function",
"getQuery",
"(",
")",
"{",
"$",
"query",
"=",
"parent",
"::",
"getQuery",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"hasLimit",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"offset",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"-... | Transforms the query from the parent to provide LIMIT functionality.
Note: doesn't work exactly like the MySQL equivalent; it will always return
$limit rows even if $offset + $limit exceeds the total number of rows.
@throws ezcQueryInvalidException if offset is used and orderBy is not.
@return string | [
"Transforms",
"the",
"query",
"from",
"the",
"parent",
"to",
"provide",
"LIMIT",
"functionality",
"."
] | train | https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Database/src/sqlabstraction/implementations/query_select_mssql.php#L129-L146 |
Visithor/visithor | src/Visithor/Compiler/Compiler.php | Compiler.addFile | protected function addFile(
Phar $phar,
SplFileInfo $file,
$strip = true
) {
$path = strtr(str_replace(dirname(dirname(dirname(__DIR__))) . DIRECTORY_SEPARATOR, '', $file->getRealPath()), '\\', '/');
$content = file_get_contents($file);
if ($strip) {
$content = $this->stripWhitespace($content);
} elseif ('LICENSE' === basename($file)) {
$content = "\n" . $content . "\n";
}
if ($path === 'src/Composer/Composer.php') {
$content = str_replace('@package_version@', $this->version, $content);
$content = str_replace('@release_date@', $this->versionDate, $content);
}
$phar->addFromString($path, $content);
return $this;
} | php | protected function addFile(
Phar $phar,
SplFileInfo $file,
$strip = true
) {
$path = strtr(str_replace(dirname(dirname(dirname(__DIR__))) . DIRECTORY_SEPARATOR, '', $file->getRealPath()), '\\', '/');
$content = file_get_contents($file);
if ($strip) {
$content = $this->stripWhitespace($content);
} elseif ('LICENSE' === basename($file)) {
$content = "\n" . $content . "\n";
}
if ($path === 'src/Composer/Composer.php') {
$content = str_replace('@package_version@', $this->version, $content);
$content = str_replace('@release_date@', $this->versionDate, $content);
}
$phar->addFromString($path, $content);
return $this;
} | [
"protected",
"function",
"addFile",
"(",
"Phar",
"$",
"phar",
",",
"SplFileInfo",
"$",
"file",
",",
"$",
"strip",
"=",
"true",
")",
"{",
"$",
"path",
"=",
"strtr",
"(",
"str_replace",
"(",
"dirname",
"(",
"dirname",
"(",
"dirname",
"(",
"__DIR__",
")",... | Add a file into the phar package
@param Phar $phar Phar object
@param SplFileInfo $file File to add
@param bool $strip strip
@return Compiler self Object | [
"Add",
"a",
"file",
"into",
"the",
"phar",
"package"
] | train | https://github.com/Visithor/visithor/blob/201ba2cfc536a0875983c79226947aa20b9f4dca/src/Visithor/Compiler/Compiler.php#L87-L108 |
Visithor/visithor | src/Visithor/Compiler/Compiler.php | Compiler.addBin | protected function addBin(Phar $phar)
{
$content = file_get_contents(__DIR__ . '/../../../bin/visithor');
$content = preg_replace('{^#!/usr/bin/env php\s*}', '', $content);
$phar->addFromString('bin/visithor', $content);
return $this;
} | php | protected function addBin(Phar $phar)
{
$content = file_get_contents(__DIR__ . '/../../../bin/visithor');
$content = preg_replace('{^#!/usr/bin/env php\s*}', '', $content);
$phar->addFromString('bin/visithor', $content);
return $this;
} | [
"protected",
"function",
"addBin",
"(",
"Phar",
"$",
"phar",
")",
"{",
"$",
"content",
"=",
"file_get_contents",
"(",
"__DIR__",
".",
"'/../../../bin/visithor'",
")",
";",
"$",
"content",
"=",
"preg_replace",
"(",
"'{^#!/usr/bin/env php\\s*}'",
",",
"''",
",",
... | Add bin into Phar
@param Phar $phar Phar
@return Compiler self Object | [
"Add",
"bin",
"into",
"Phar"
] | train | https://github.com/Visithor/visithor/blob/201ba2cfc536a0875983c79226947aa20b9f4dca/src/Visithor/Compiler/Compiler.php#L117-L124 |
Visithor/visithor | src/Visithor/Compiler/Compiler.php | Compiler.addLicense | private function addLicense(Phar $phar)
{
$this->addFile($phar, new \SplFileInfo(__DIR__ . '/../../../LICENSE'), false);
return $this;
} | php | private function addLicense(Phar $phar)
{
$this->addFile($phar, new \SplFileInfo(__DIR__ . '/../../../LICENSE'), false);
return $this;
} | [
"private",
"function",
"addLicense",
"(",
"Phar",
"$",
"phar",
")",
"{",
"$",
"this",
"->",
"addFile",
"(",
"$",
"phar",
",",
"new",
"\\",
"SplFileInfo",
"(",
"__DIR__",
".",
"'/../../../LICENSE'",
")",
",",
"false",
")",
";",
"return",
"$",
"this",
";... | Add license
@param Phar $phar Phar
@return Compiler self Object | [
"Add",
"license"
] | train | https://github.com/Visithor/visithor/blob/201ba2cfc536a0875983c79226947aa20b9f4dca/src/Visithor/Compiler/Compiler.php#L285-L290 |
Visithor/visithor | src/Visithor/Compiler/Compiler.php | Compiler.loadVersion | private function loadVersion()
{
$process = new Process('git log --pretty="%H" -n1 HEAD', __DIR__);
if ($process->run() !== 0) {
throw new \RuntimeException('Can\'t run git log. You must ensure to run compile from visithor git repository clone and that git binary is available.');
}
$this->version = trim($process->getOutput());
$process = new Process('git log -n1 --pretty=%ci HEAD', __DIR__);
if ($process->run() !== 0) {
throw new \RuntimeException('Can\'t run git log. You must ensure to run compile from visithor git repository clone and that git binary is available.');
}
$date = new \DateTime(trim($process->getOutput()));
$date->setTimezone(new \DateTimeZone('UTC'));
$this->versionDate = $date->format('Y-m-d H:i:s');
$process = new Process('git describe --tags HEAD');
if ($process->run() === 0) {
$this->version = trim($process->getOutput());
}
return $this;
} | php | private function loadVersion()
{
$process = new Process('git log --pretty="%H" -n1 HEAD', __DIR__);
if ($process->run() !== 0) {
throw new \RuntimeException('Can\'t run git log. You must ensure to run compile from visithor git repository clone and that git binary is available.');
}
$this->version = trim($process->getOutput());
$process = new Process('git log -n1 --pretty=%ci HEAD', __DIR__);
if ($process->run() !== 0) {
throw new \RuntimeException('Can\'t run git log. You must ensure to run compile from visithor git repository clone and that git binary is available.');
}
$date = new \DateTime(trim($process->getOutput()));
$date->setTimezone(new \DateTimeZone('UTC'));
$this->versionDate = $date->format('Y-m-d H:i:s');
$process = new Process('git describe --tags HEAD');
if ($process->run() === 0) {
$this->version = trim($process->getOutput());
}
return $this;
} | [
"private",
"function",
"loadVersion",
"(",
")",
"{",
"$",
"process",
"=",
"new",
"Process",
"(",
"'git log --pretty=\"%H\" -n1 HEAD'",
",",
"__DIR__",
")",
";",
"if",
"(",
"$",
"process",
"->",
"run",
"(",
")",
"!==",
"0",
")",
"{",
"throw",
"new",
"\\",... | Load versions | [
"Load",
"versions"
] | train | https://github.com/Visithor/visithor/blob/201ba2cfc536a0875983c79226947aa20b9f4dca/src/Visithor/Compiler/Compiler.php#L295-L317 |
Smile-SA/CronBundle | Cron/CronHandler.php | CronHandler.addCron | public function addCron(CronInterface $cron, $alias, $priority, $arguments)
{
if (!isset($this->crons[$priority])) {
$this->crons[$priority] = array();
}
$cron->setAlias($alias);
$cron->addArguments($arguments);
$cron->addPriority($priority);
$this->crons[$priority][$alias] = $cron;
} | php | public function addCron(CronInterface $cron, $alias, $priority, $arguments)
{
if (!isset($this->crons[$priority])) {
$this->crons[$priority] = array();
}
$cron->setAlias($alias);
$cron->addArguments($arguments);
$cron->addPriority($priority);
$this->crons[$priority][$alias] = $cron;
} | [
"public",
"function",
"addCron",
"(",
"CronInterface",
"$",
"cron",
",",
"$",
"alias",
",",
"$",
"priority",
",",
"$",
"arguments",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"crons",
"[",
"$",
"priority",
"]",
")",
")",
"{",
"$",
... | Add cron to crons list
@param CronInterface $cron cron
@param string $alias cron alias
@param integer $priority cron priority
@param string $arguments cron arguments | [
"Add",
"cron",
"to",
"crons",
"list"
] | train | https://github.com/Smile-SA/CronBundle/blob/3e6d29112915fa957cc04386ba9c6d1fc134d31f/Cron/CronHandler.php#L44-L53 |
WScore/Validation | src/Utils/Message.php | Message.find | public function find($type, $method, $parameter)
{
if (strpos($method, '::filter_') !== false) {
$method = substr($method, strpos($method, '::filter_') + 9);
}
if ($message = $this->findForMethod($method, $parameter)) {
return $message;
}
// 4. use message for a specific type.
if (isset($this->messages['_type_'][$type])) {
return $this->messages['_type_'][$type];
}
// 5. use general error message.
return (string) Helper::arrGet($this->messages, '0', '');
} | php | public function find($type, $method, $parameter)
{
if (strpos($method, '::filter_') !== false) {
$method = substr($method, strpos($method, '::filter_') + 9);
}
if ($message = $this->findForMethod($method, $parameter)) {
return $message;
}
// 4. use message for a specific type.
if (isset($this->messages['_type_'][$type])) {
return $this->messages['_type_'][$type];
}
// 5. use general error message.
return (string) Helper::arrGet($this->messages, '0', '');
} | [
"public",
"function",
"find",
"(",
"$",
"type",
",",
"$",
"method",
",",
"$",
"parameter",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"method",
",",
"'::filter_'",
")",
"!==",
"false",
")",
"{",
"$",
"method",
"=",
"substr",
"(",
"$",
"method",
",",
... | find messages based on error type.
2. use message for a method/parameter set.
3. use message for a specific method.
4. use message for a type.
5. use general error message.
@param $type
@param $method
@param $parameter
@return string | [
"find",
"messages",
"based",
"on",
"error",
"type",
".",
"2",
".",
"use",
"message",
"for",
"a",
"method",
"/",
"parameter",
"set",
".",
"3",
".",
"use",
"message",
"for",
"a",
"specific",
"method",
".",
"4",
".",
"use",
"message",
"for",
"a",
"type"... | train | https://github.com/WScore/Validation/blob/25c0dca37d624bb0bb22f8e79ba54db2f69e0950/src/Utils/Message.php#L50-L65 |
cartalyst/assetic-filters | src/LessphpFilter.php | LessphpFilter.filterLoad | public function filterLoad(AssetInterface $asset)
{
$max_nesting_level = ini_get('xdebug.max_nesting_level');
$memory_limit = ini_get('memory_limit');
if ($max_nesting_level && $max_nesting_level < 200) {
ini_set('xdebug.max_nesting_level', 200);
}
if ($memory_limit && $memory_limit < 256) {
ini_set('memory_limit', '256M');
}
$root = $asset->getSourceRoot();
$path = $asset->getSourcePath();
$dirs = array();
$lc = new \Less_Parser(array(
'compress' => true,
));
if ($root && $path) {
$dirs[] = dirname($root.'/'.$path);
}
foreach ($this->loadPaths as $loadPath) {
$dirs[] = $loadPath;
}
$lc->SetImportDirs($dirs);
$url = parse_url($this->getRequest()->getUriForPath(''));
// Strip the document root from the path.
if (strpos($root, app('path.public')) !== false) {
$absolutePath = str_replace(app('path.public'), '', $root);
} elseif (strpos($root, app('path.resources')) !== false) {
$absolutePath = str_replace(app('path.resources'), '', $root);
}
if (isset($url['path'])) {
$absolutePath = $url['path'] . $absolutePath;
}
$lc->parseFile($root.'/'.$path, $absolutePath);
$asset->setContent($lc->getCss());
} | php | public function filterLoad(AssetInterface $asset)
{
$max_nesting_level = ini_get('xdebug.max_nesting_level');
$memory_limit = ini_get('memory_limit');
if ($max_nesting_level && $max_nesting_level < 200) {
ini_set('xdebug.max_nesting_level', 200);
}
if ($memory_limit && $memory_limit < 256) {
ini_set('memory_limit', '256M');
}
$root = $asset->getSourceRoot();
$path = $asset->getSourcePath();
$dirs = array();
$lc = new \Less_Parser(array(
'compress' => true,
));
if ($root && $path) {
$dirs[] = dirname($root.'/'.$path);
}
foreach ($this->loadPaths as $loadPath) {
$dirs[] = $loadPath;
}
$lc->SetImportDirs($dirs);
$url = parse_url($this->getRequest()->getUriForPath(''));
// Strip the document root from the path.
if (strpos($root, app('path.public')) !== false) {
$absolutePath = str_replace(app('path.public'), '', $root);
} elseif (strpos($root, app('path.resources')) !== false) {
$absolutePath = str_replace(app('path.resources'), '', $root);
}
if (isset($url['path'])) {
$absolutePath = $url['path'] . $absolutePath;
}
$lc->parseFile($root.'/'.$path, $absolutePath);
$asset->setContent($lc->getCss());
} | [
"public",
"function",
"filterLoad",
"(",
"AssetInterface",
"$",
"asset",
")",
"{",
"$",
"max_nesting_level",
"=",
"ini_get",
"(",
"'xdebug.max_nesting_level'",
")",
";",
"$",
"memory_limit",
"=",
"ini_get",
"(",
"'memory_limit'",
")",
";",
"if",
"(",
"$",
"max... | Filters an asset after it has been loaded.
@param \Assetic\Asset\AssetInterface $asset
@return void | [
"Filters",
"an",
"asset",
"after",
"it",
"has",
"been",
"loaded",
"."
] | train | https://github.com/cartalyst/assetic-filters/blob/5e26328f7e46937bf1daa0bee2f744ab3493f471/src/LessphpFilter.php#L42-L91 |
42mate/towel | src/Towel/Controller/AssetsController.php | AssetsController.index | public function index($request) {
$application = $request->get('application');
$path = $request->get('path');
if (empty($application) || empty($path)) {
return new Response(
"Not a valid asset",
404
);
}
if (strpos('..', $path) === 0) {
return new Response(
"Only assets will be served",
404
);
}
if ($application !== 'Towel') {
$asset_path = APP_ROOT_DIR . '/Application/' . $application . '/Views/assets/' . $path;
} else {
$asset_path = APP_FW_DIR. '/Views/assets/' . $path;
}
if (!file_exists($asset_path)) {
return new Response(
"Asset does not exists",
404
);
}
$asset_type = mime_content_type($asset_path);
$asset_content = file_get_contents($asset_path);
$asset_info = pathinfo($asset_path);
if (!empty($asset_info['extension']) && in_array($asset_info['extension'], self::$validExtensions)) {
$response = new Response(
$asset_content,
200,
['Content-Type' => self::$extensionTypeMapping[$asset_info['extension']]]
);
//To cache in the client side.
$maxAge = 0;
if (!empty($this->appConfig['assets']['max-age'])) {
$maxAge = $this->appConfig['assets']['max-age'];
}
$response->headers->addCacheControlDirective('max-age', $maxAge);
if (!empty($this->appConfig['assets']['public']) && $this->appConfig['assets']['public'] == true) {
$response->headers->addCacheControlDirective('public', true);
}
return $response;
}
return new Response(
"Not a valid extension",
404
);
} | php | public function index($request) {
$application = $request->get('application');
$path = $request->get('path');
if (empty($application) || empty($path)) {
return new Response(
"Not a valid asset",
404
);
}
if (strpos('..', $path) === 0) {
return new Response(
"Only assets will be served",
404
);
}
if ($application !== 'Towel') {
$asset_path = APP_ROOT_DIR . '/Application/' . $application . '/Views/assets/' . $path;
} else {
$asset_path = APP_FW_DIR. '/Views/assets/' . $path;
}
if (!file_exists($asset_path)) {
return new Response(
"Asset does not exists",
404
);
}
$asset_type = mime_content_type($asset_path);
$asset_content = file_get_contents($asset_path);
$asset_info = pathinfo($asset_path);
if (!empty($asset_info['extension']) && in_array($asset_info['extension'], self::$validExtensions)) {
$response = new Response(
$asset_content,
200,
['Content-Type' => self::$extensionTypeMapping[$asset_info['extension']]]
);
//To cache in the client side.
$maxAge = 0;
if (!empty($this->appConfig['assets']['max-age'])) {
$maxAge = $this->appConfig['assets']['max-age'];
}
$response->headers->addCacheControlDirective('max-age', $maxAge);
if (!empty($this->appConfig['assets']['public']) && $this->appConfig['assets']['public'] == true) {
$response->headers->addCacheControlDirective('public', true);
}
return $response;
}
return new Response(
"Not a valid extension",
404
);
} | [
"public",
"function",
"index",
"(",
"$",
"request",
")",
"{",
"$",
"application",
"=",
"$",
"request",
"->",
"get",
"(",
"'application'",
")",
";",
"$",
"path",
"=",
"$",
"request",
"->",
"get",
"(",
"'path'",
")",
";",
"if",
"(",
"empty",
"(",
"$"... | Serves assets from the Application directory.
To use this controller in your template use the function asset_url to get a valid url
for this controller.
@param $request
@return string|Response | [
"Serves",
"assets",
"from",
"the",
"Application",
"directory",
"."
] | train | https://github.com/42mate/towel/blob/5316c3075fc844e8a5cbae113712b26556227dff/src/Towel/Controller/AssetsController.php#L33-L93 |
philiplb/Valdi | src/Valdi/Validator/AbstractFilter.php | AbstractFilter.isValid | public function isValid($value, array $parameters) {
return in_array($value, ['', null], true) ||
filter_var($value, $this->getFilter(), $this->getFlags()) !== false;
} | php | public function isValid($value, array $parameters) {
return in_array($value, ['', null], true) ||
filter_var($value, $this->getFilter(), $this->getFlags()) !== false;
} | [
"public",
"function",
"isValid",
"(",
"$",
"value",
",",
"array",
"$",
"parameters",
")",
"{",
"return",
"in_array",
"(",
"$",
"value",
",",
"[",
"''",
",",
"null",
"]",
",",
"true",
")",
"||",
"filter_var",
"(",
"$",
"value",
",",
"$",
"this",
"->... | {@inheritdoc} | [
"{"
] | train | https://github.com/philiplb/Valdi/blob/9927ec34a2cb00cec705e952d3c2374e2dc3c972/src/Valdi/Validator/AbstractFilter.php#L42-L45 |
GrupaZero/social | src/Gzero/Repository/SocialRepository.php | SocialRepository.createNewUser | public function createNewUser($serviceName, AbstractUser $response)
{
$data = $this->parseServiceResponse($response);
$existingUser = $this->userRepo->getByEmail($data['email']);
// duplicated user verification
if ($existingUser === null) {
$data['password'] = str_random(40);
$user = $this->userRepo->create($data);
// create relation for new user and social integration
$this->addSocialRelation($user, $serviceName, $response);
return $user;
} else {
session()->put('url.intended', route('register'));
throw new SocialException(
trans('gzero-social::common.email_already_in_use_message', ['service_name' => title_case($serviceName)])
);
}
} | php | public function createNewUser($serviceName, AbstractUser $response)
{
$data = $this->parseServiceResponse($response);
$existingUser = $this->userRepo->getByEmail($data['email']);
// duplicated user verification
if ($existingUser === null) {
$data['password'] = str_random(40);
$user = $this->userRepo->create($data);
// create relation for new user and social integration
$this->addSocialRelation($user, $serviceName, $response);
return $user;
} else {
session()->put('url.intended', route('register'));
throw new SocialException(
trans('gzero-social::common.email_already_in_use_message', ['service_name' => title_case($serviceName)])
);
}
} | [
"public",
"function",
"createNewUser",
"(",
"$",
"serviceName",
",",
"AbstractUser",
"$",
"response",
")",
"{",
"$",
"data",
"=",
"$",
"this",
"->",
"parseServiceResponse",
"(",
"$",
"response",
")",
";",
"$",
"existingUser",
"=",
"$",
"this",
"->",
"userR... | Function creates new user based on social service response and create relation with social integration in database.
@param $serviceName string name of social service
@param $response AbstractUser response data
@return User
@throws SocialException | [
"Function",
"creates",
"new",
"user",
"based",
"on",
"social",
"service",
"response",
"and",
"create",
"relation",
"with",
"social",
"integration",
"in",
"database",
"."
] | train | https://github.com/GrupaZero/social/blob/f7cbf50765bd228010a2c61d950f915828306cf7/src/Gzero/Repository/SocialRepository.php#L92-L109 |
GrupaZero/social | src/Gzero/Repository/SocialRepository.php | SocialRepository.addUserSocialAccount | public function addUserSocialAccount(User $user, $serviceName, AbstractUser $response)
{
$user->has_social_integrations = true;
$user->save();
// create relation for new user and social integration
$this->addSocialRelation($user, $serviceName, $response);
return $user;
} | php | public function addUserSocialAccount(User $user, $serviceName, AbstractUser $response)
{
$user->has_social_integrations = true;
$user->save();
// create relation for new user and social integration
$this->addSocialRelation($user, $serviceName, $response);
return $user;
} | [
"public",
"function",
"addUserSocialAccount",
"(",
"User",
"$",
"user",
",",
"$",
"serviceName",
",",
"AbstractUser",
"$",
"response",
")",
"{",
"$",
"user",
"->",
"has_social_integrations",
"=",
"true",
";",
"$",
"user",
"->",
"save",
"(",
")",
";",
"// c... | Function adds new social account for existing user.
@param $user User user entity
@param $serviceName string name of social service
@param $response AbstractUser response data
@return User | [
"Function",
"adds",
"new",
"social",
"account",
"for",
"existing",
"user",
"."
] | train | https://github.com/GrupaZero/social/blob/f7cbf50765bd228010a2c61d950f915828306cf7/src/Gzero/Repository/SocialRepository.php#L120-L127 |
GrupaZero/social | src/Gzero/Repository/SocialRepository.php | SocialRepository.addSocialRelation | public function addSocialRelation(User $user, $serviceName, AbstractUser $response)
{
// create relation for new user and social integration
return $this->newQB()->insert(
[
'user_id' => $user->id,
'social_id' => $serviceName . '_' . $response->id,
'created_at' => \DB::raw('NOW()')
]
);
} | php | public function addSocialRelation(User $user, $serviceName, AbstractUser $response)
{
// create relation for new user and social integration
return $this->newQB()->insert(
[
'user_id' => $user->id,
'social_id' => $serviceName . '_' . $response->id,
'created_at' => \DB::raw('NOW()')
]
);
} | [
"public",
"function",
"addSocialRelation",
"(",
"User",
"$",
"user",
",",
"$",
"serviceName",
",",
"AbstractUser",
"$",
"response",
")",
"{",
"// create relation for new user and social integration",
"return",
"$",
"this",
"->",
"newQB",
"(",
")",
"->",
"insert",
... | Function creates relation for given user and social integration.
@param $user User user entity
@param $serviceName string name of social service
@param $response AbstractUser response data
@return mixed | [
"Function",
"creates",
"relation",
"for",
"given",
"user",
"and",
"social",
"integration",
"."
] | train | https://github.com/GrupaZero/social/blob/f7cbf50765bd228010a2c61d950f915828306cf7/src/Gzero/Repository/SocialRepository.php#L138-L148 |
GrupaZero/social | src/Gzero/Repository/SocialRepository.php | SocialRepository.parseServiceResponse | private function parseServiceResponse(AbstractUser $response)
{
$userData = [
'has_social_integrations' => true,
'nick' => $response->getNickname()
];
// set user email if exists (twitter returns as null)
if ($response->getEmail()) {
$userData['email'] = $response->getEmail();
} else {
$userData['email'] = uniqid('social_', true); // set unique email placeholder
}
// set user first and last name
$name = explode(" ", $response->getName());
if (count($name) >= 2) {
$userData['first_name'] = $name[0];
$userData['last_name'] = $name[1];
}
return $userData;
} | php | private function parseServiceResponse(AbstractUser $response)
{
$userData = [
'has_social_integrations' => true,
'nick' => $response->getNickname()
];
// set user email if exists (twitter returns as null)
if ($response->getEmail()) {
$userData['email'] = $response->getEmail();
} else {
$userData['email'] = uniqid('social_', true); // set unique email placeholder
}
// set user first and last name
$name = explode(" ", $response->getName());
if (count($name) >= 2) {
$userData['first_name'] = $name[0];
$userData['last_name'] = $name[1];
}
return $userData;
} | [
"private",
"function",
"parseServiceResponse",
"(",
"AbstractUser",
"$",
"response",
")",
"{",
"$",
"userData",
"=",
"[",
"'has_social_integrations'",
"=>",
"true",
",",
"'nick'",
"=>",
"$",
"response",
"->",
"getNickname",
"(",
")",
"]",
";",
"// set user email... | Function parses social service response and prepares user data to insert to database.
@param $response AbstractUser response data
@return array parsed user data for database insertion | [
"Function",
"parses",
"social",
"service",
"response",
"and",
"prepares",
"user",
"data",
"to",
"insert",
"to",
"database",
"."
] | train | https://github.com/GrupaZero/social/blob/f7cbf50765bd228010a2c61d950f915828306cf7/src/Gzero/Repository/SocialRepository.php#L167-L187 |
heidelpay/PhpDoc | src/phpDocumentor/Plugin/Core/Transformer/Writer/FileIo.php | FileIo.executeQueryCopy | public function executeQueryCopy(Transformation $transformation)
{
$path = $transformation->getSourceAsPath();
if (!is_readable($path)) {
throw new Exception('Unable to read the source file: ' . $path);
}
if (!is_writable($transformation->getTransformer()->getTarget())) {
throw new Exception('Unable to write to: ' . dirname($transformation->getArtifact()));
}
$filesystem = new Filesystem();
if (is_file($path)) {
$filesystem->copy($path, $transformation->getArtifact(), true);
} else {
$filesystem->mirror($path, $transformation->getArtifact(), null, array('override' => true));
}
} | php | public function executeQueryCopy(Transformation $transformation)
{
$path = $transformation->getSourceAsPath();
if (!is_readable($path)) {
throw new Exception('Unable to read the source file: ' . $path);
}
if (!is_writable($transformation->getTransformer()->getTarget())) {
throw new Exception('Unable to write to: ' . dirname($transformation->getArtifact()));
}
$filesystem = new Filesystem();
if (is_file($path)) {
$filesystem->copy($path, $transformation->getArtifact(), true);
} else {
$filesystem->mirror($path, $transformation->getArtifact(), null, array('override' => true));
}
} | [
"public",
"function",
"executeQueryCopy",
"(",
"Transformation",
"$",
"transformation",
")",
"{",
"$",
"path",
"=",
"$",
"transformation",
"->",
"getSourceAsPath",
"(",
")",
";",
"if",
"(",
"!",
"is_readable",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new... | Copies files or folders to the Artifact location.
@param Transformation $transformation Transformation to use as data source.
@throws Exception
@return void | [
"Copies",
"files",
"or",
"folders",
"to",
"the",
"Artifact",
"location",
"."
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Core/Transformer/Writer/FileIo.php#L68-L85 |
trunda/SmfMenu | src/Smf/Menu/Config/Extension.php | Extension.loadConfiguration | public function loadConfiguration()
{
$builder = $this->getContainerBuilder();
$config = $this->getConfig($this->defaults);
// Create instance of extension
$menuFactory = $builder->addDefinition($this->prefix('extension'))
->setClass('Smf\Menu\MenuExtension');
// Create instance of menufactory
$menuFactory = $builder->addDefinition($this->prefix('factory'))
->addSetup('addExtension', array($this->prefix('@extension')))
->setClass('Knp\Menu\MenuFactory');
// Create renderers manager
$rendererManager = $builder->addDefinition($this->prefix('rendererManager'))
->setClass('Smf\Menu\Renderer\Manager')
->addSetup(get_called_class() . '::setupRenderers', array('@self', '@container'))
->addSetup('setDefaultRenderer', array($config['defaultRenderer']));;
// Create a factory for control
$builder->addDefinition($this->prefix('controlFactory'))
->setClass('Smf\Menu\Control\Factory', array($menuFactory, $rendererManager));
// Matcher
$matcher = $builder->addDefinition($this->prefix('matcher'))
->addSetup(get_called_class() . '::setupVoters', array('@self', '@container'))
->setClass('Smf\Menu\Matcher\Matcher');
// Create a default renderers
$renderers = array(
'Smf\Menu\Renderer\ListRenderer',
'Smf\Menu\Renderer\BootstrapNavRenderer',
);
foreach ($renderers as $renderer) {
$name = explode('\\', $renderer);
$name = lcfirst(preg_replace('#Renderer$#', '', end($name)));
$builder->addDefinition($this->prefix('renderer_' . $name))
->setClass($renderer, array($matcher))
->addTag(self::RENDERER_TAG_NAME, $name);
}
// Create default voter
$builder->addDefinition($this->prefix('presenterVoter'))
->setClass('Smf\Menu\Matcher\Voter\PresenterVoter')
->addTag(self::VOTER_TAG_NAME);
} | php | public function loadConfiguration()
{
$builder = $this->getContainerBuilder();
$config = $this->getConfig($this->defaults);
// Create instance of extension
$menuFactory = $builder->addDefinition($this->prefix('extension'))
->setClass('Smf\Menu\MenuExtension');
// Create instance of menufactory
$menuFactory = $builder->addDefinition($this->prefix('factory'))
->addSetup('addExtension', array($this->prefix('@extension')))
->setClass('Knp\Menu\MenuFactory');
// Create renderers manager
$rendererManager = $builder->addDefinition($this->prefix('rendererManager'))
->setClass('Smf\Menu\Renderer\Manager')
->addSetup(get_called_class() . '::setupRenderers', array('@self', '@container'))
->addSetup('setDefaultRenderer', array($config['defaultRenderer']));;
// Create a factory for control
$builder->addDefinition($this->prefix('controlFactory'))
->setClass('Smf\Menu\Control\Factory', array($menuFactory, $rendererManager));
// Matcher
$matcher = $builder->addDefinition($this->prefix('matcher'))
->addSetup(get_called_class() . '::setupVoters', array('@self', '@container'))
->setClass('Smf\Menu\Matcher\Matcher');
// Create a default renderers
$renderers = array(
'Smf\Menu\Renderer\ListRenderer',
'Smf\Menu\Renderer\BootstrapNavRenderer',
);
foreach ($renderers as $renderer) {
$name = explode('\\', $renderer);
$name = lcfirst(preg_replace('#Renderer$#', '', end($name)));
$builder->addDefinition($this->prefix('renderer_' . $name))
->setClass($renderer, array($matcher))
->addTag(self::RENDERER_TAG_NAME, $name);
}
// Create default voter
$builder->addDefinition($this->prefix('presenterVoter'))
->setClass('Smf\Menu\Matcher\Voter\PresenterVoter')
->addTag(self::VOTER_TAG_NAME);
} | [
"public",
"function",
"loadConfiguration",
"(",
")",
"{",
"$",
"builder",
"=",
"$",
"this",
"->",
"getContainerBuilder",
"(",
")",
";",
"$",
"config",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"$",
"this",
"->",
"defaults",
")",
";",
"// Create instance of... | Configuration - container building | [
"Configuration",
"-",
"container",
"building"
] | train | https://github.com/trunda/SmfMenu/blob/739e74fb664c1f018b4a74142bd28d20c004bac6/src/Smf/Menu/Config/Extension.php#L37-L83 |
trunda/SmfMenu | src/Smf/Menu/Config/Extension.php | Extension.register | public static function register(Nette\Configurator $configurator, $name = self::DEFAULT_EXTENSION_NAME)
{
$class = get_called_class();
$configurator->onCompile[] = function (Nette\Configurator $configurator, Nette\DI\Compiler $compiler) use ($class, $name) {
$compiler->addExtension($name, new $class);
};
} | php | public static function register(Nette\Configurator $configurator, $name = self::DEFAULT_EXTENSION_NAME)
{
$class = get_called_class();
$configurator->onCompile[] = function (Nette\Configurator $configurator, Nette\DI\Compiler $compiler) use ($class, $name) {
$compiler->addExtension($name, new $class);
};
} | [
"public",
"static",
"function",
"register",
"(",
"Nette",
"\\",
"Configurator",
"$",
"configurator",
",",
"$",
"name",
"=",
"self",
"::",
"DEFAULT_EXTENSION_NAME",
")",
"{",
"$",
"class",
"=",
"get_called_class",
"(",
")",
";",
"$",
"configurator",
"->",
"on... | Register extension to compiler.
@param Configurator $configurator
@param string $name | [
"Register",
"extension",
"to",
"compiler",
"."
] | train | https://github.com/trunda/SmfMenu/blob/739e74fb664c1f018b4a74142bd28d20c004bac6/src/Smf/Menu/Config/Extension.php#L113-L119 |
oroinc/OroLayoutComponent | BlockOptionsManipulator.php | BlockOptionsManipulator.setOption | public function setOption($id, $optionName, $optionValue)
{
$options = $this->rawLayout->getProperty($id, RawLayout::OPTIONS);
$this->propertyAccessor->setValue($options, $this->getPropertyPath($optionName), $optionValue);
$this->rawLayout->setProperty($id, RawLayout::OPTIONS, $options);
} | php | public function setOption($id, $optionName, $optionValue)
{
$options = $this->rawLayout->getProperty($id, RawLayout::OPTIONS);
$this->propertyAccessor->setValue($options, $this->getPropertyPath($optionName), $optionValue);
$this->rawLayout->setProperty($id, RawLayout::OPTIONS, $options);
} | [
"public",
"function",
"setOption",
"(",
"$",
"id",
",",
"$",
"optionName",
",",
"$",
"optionValue",
")",
"{",
"$",
"options",
"=",
"$",
"this",
"->",
"rawLayout",
"->",
"getProperty",
"(",
"$",
"id",
",",
"RawLayout",
"::",
"OPTIONS",
")",
";",
"$",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/BlockOptionsManipulator.php#L33-L38 |
oroinc/OroLayoutComponent | BlockOptionsManipulator.php | BlockOptionsManipulator.appendOption | public function appendOption($id, $optionName, $optionValue)
{
$options = $this->rawLayout->getProperty($id, RawLayout::OPTIONS);
$path = $this->getPropertyPath($optionName);
try {
$value = $this->propertyAccessor->getValue($options, $path);
if (!$value instanceof OptionValueBag) {
$value = $this->createOptionValueBag($value);
}
$value->add($optionValue);
} catch (NoSuchPropertyException $ex) {
$value = $optionValue;
}
$this->propertyAccessor->setValue($options, $path, $value);
$this->rawLayout->setProperty($id, RawLayout::OPTIONS, $options);
} | php | public function appendOption($id, $optionName, $optionValue)
{
$options = $this->rawLayout->getProperty($id, RawLayout::OPTIONS);
$path = $this->getPropertyPath($optionName);
try {
$value = $this->propertyAccessor->getValue($options, $path);
if (!$value instanceof OptionValueBag) {
$value = $this->createOptionValueBag($value);
}
$value->add($optionValue);
} catch (NoSuchPropertyException $ex) {
$value = $optionValue;
}
$this->propertyAccessor->setValue($options, $path, $value);
$this->rawLayout->setProperty($id, RawLayout::OPTIONS, $options);
} | [
"public",
"function",
"appendOption",
"(",
"$",
"id",
",",
"$",
"optionName",
",",
"$",
"optionValue",
")",
"{",
"$",
"options",
"=",
"$",
"this",
"->",
"rawLayout",
"->",
"getProperty",
"(",
"$",
"id",
",",
"RawLayout",
"::",
"OPTIONS",
")",
";",
"$",... | {@inheritdoc} | [
"{"
] | train | https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/BlockOptionsManipulator.php#L43-L58 |
oroinc/OroLayoutComponent | BlockOptionsManipulator.php | BlockOptionsManipulator.replaceOption | public function replaceOption($id, $optionName, $oldOptionValue, $newOptionValue)
{
$options = $this->rawLayout->getProperty($id, RawLayout::OPTIONS);
$path = $this->getPropertyPath($optionName);
try {
$value = $this->propertyAccessor->getValue($options, $path);
} catch (NoSuchPropertyException $ex) {
$value = null;
}
if (!$value instanceof OptionValueBag) {
$value = $this->createOptionValueBag($value);
}
$value->replace($oldOptionValue, $newOptionValue);
$this->propertyAccessor->setValue($options, $path, $value);
$this->rawLayout->setProperty($id, RawLayout::OPTIONS, $options);
} | php | public function replaceOption($id, $optionName, $oldOptionValue, $newOptionValue)
{
$options = $this->rawLayout->getProperty($id, RawLayout::OPTIONS);
$path = $this->getPropertyPath($optionName);
try {
$value = $this->propertyAccessor->getValue($options, $path);
} catch (NoSuchPropertyException $ex) {
$value = null;
}
if (!$value instanceof OptionValueBag) {
$value = $this->createOptionValueBag($value);
}
$value->replace($oldOptionValue, $newOptionValue);
$this->propertyAccessor->setValue($options, $path, $value);
$this->rawLayout->setProperty($id, RawLayout::OPTIONS, $options);
} | [
"public",
"function",
"replaceOption",
"(",
"$",
"id",
",",
"$",
"optionName",
",",
"$",
"oldOptionValue",
",",
"$",
"newOptionValue",
")",
"{",
"$",
"options",
"=",
"$",
"this",
"->",
"rawLayout",
"->",
"getProperty",
"(",
"$",
"id",
",",
"RawLayout",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/BlockOptionsManipulator.php#L83-L98 |
oroinc/OroLayoutComponent | BlockOptionsManipulator.php | BlockOptionsManipulator.removeOption | public function removeOption($id, $optionName)
{
$options = $this->rawLayout->getProperty($id, RawLayout::OPTIONS);
$this->propertyAccessor->remove($options, $this->getPropertyPath($optionName));
$this->rawLayout->setProperty($id, RawLayout::OPTIONS, $options);
} | php | public function removeOption($id, $optionName)
{
$options = $this->rawLayout->getProperty($id, RawLayout::OPTIONS);
$this->propertyAccessor->remove($options, $this->getPropertyPath($optionName));
$this->rawLayout->setProperty($id, RawLayout::OPTIONS, $options);
} | [
"public",
"function",
"removeOption",
"(",
"$",
"id",
",",
"$",
"optionName",
")",
"{",
"$",
"options",
"=",
"$",
"this",
"->",
"rawLayout",
"->",
"getProperty",
"(",
"$",
"id",
",",
"RawLayout",
"::",
"OPTIONS",
")",
";",
"$",
"this",
"->",
"propertyA... | {@inheritdoc} | [
"{"
] | train | https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/BlockOptionsManipulator.php#L103-L108 |
oroinc/OroLayoutComponent | BlockOptionsManipulator.php | BlockOptionsManipulator.createOptionValueBag | protected function createOptionValueBag($initialValue)
{
$result = new OptionValueBag();
if (null !== $initialValue) {
$result->add($initialValue);
}
return $result;
} | php | protected function createOptionValueBag($initialValue)
{
$result = new OptionValueBag();
if (null !== $initialValue) {
$result->add($initialValue);
}
return $result;
} | [
"protected",
"function",
"createOptionValueBag",
"(",
"$",
"initialValue",
")",
"{",
"$",
"result",
"=",
"new",
"OptionValueBag",
"(",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"initialValue",
")",
"{",
"$",
"result",
"->",
"add",
"(",
"$",
"initialValue",
... | @param mixed $initialValue
@return OptionValueBag | [
"@param",
"mixed",
"$initialValue"
] | train | https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/BlockOptionsManipulator.php#L125-L133 |
mothership-ec/composer | src/Composer/Repository/PearRepository.php | PearRepository.buildComposerPackages | private function buildComposerPackages(ChannelInfo $channelInfo, VersionParser $versionParser)
{
$result = array();
foreach ($channelInfo->getPackages() as $packageDefinition) {
foreach ($packageDefinition->getReleases() as $version => $releaseInfo) {
try {
$normalizedVersion = $versionParser->normalize($version);
} catch (\UnexpectedValueException $e) {
if ($this->io->isVerbose()) {
$this->io->writeError('Could not load '.$packageDefinition->getPackageName().' '.$version.': '.$e->getMessage());
}
continue;
}
$composerPackageName = $this->buildComposerPackageName($packageDefinition->getChannelName(), $packageDefinition->getPackageName());
// distribution url must be read from /r/{packageName}/{version}.xml::/r/g:text()
// but this location is 'de-facto' standard
$urlBits = parse_url($this->url);
$scheme = (isset($urlBits['scheme']) && 'https' === $urlBits['scheme'] && extension_loaded('openssl')) ? 'https' : 'http';
$distUrl = "{$scheme}://{$packageDefinition->getChannelName()}/get/{$packageDefinition->getPackageName()}-{$version}.tgz";
$requires = array();
$suggests = array();
$conflicts = array();
$replaces = array();
// alias package only when its channel matches repository channel,
// cause we've know only repository channel alias
if ($channelInfo->getName() == $packageDefinition->getChannelName()) {
$composerPackageAlias = $this->buildComposerPackageName($channelInfo->getAlias(), $packageDefinition->getPackageName());
$aliasConstraint = new VersionConstraint('==', $normalizedVersion);
$replaces[] = new Link($composerPackageName, $composerPackageAlias, $aliasConstraint, 'replaces', (string) $aliasConstraint);
}
// alias package with user-specified prefix. it makes private pear channels looks like composer's.
if (!empty($this->vendorAlias)
&& ($this->vendorAlias != 'pear-'.$channelInfo->getAlias() || $channelInfo->getName() != $packageDefinition->getChannelName())
) {
$composerPackageAlias = "{$this->vendorAlias}/{$packageDefinition->getPackageName()}";
$aliasConstraint = new VersionConstraint('==', $normalizedVersion);
$replaces[] = new Link($composerPackageName, $composerPackageAlias, $aliasConstraint, 'replaces', (string) $aliasConstraint);
}
foreach ($releaseInfo->getDependencyInfo()->getRequires() as $dependencyConstraint) {
$dependencyPackageName = $this->buildComposerPackageName($dependencyConstraint->getChannelName(), $dependencyConstraint->getPackageName());
$constraint = $versionParser->parseConstraints($dependencyConstraint->getConstraint());
$link = new Link($composerPackageName, $dependencyPackageName, $constraint, $dependencyConstraint->getType(), $dependencyConstraint->getConstraint());
switch ($dependencyConstraint->getType()) {
case 'required':
$requires[] = $link;
break;
case 'conflicts':
$conflicts[] = $link;
break;
case 'replaces':
$replaces[] = $link;
break;
}
}
foreach ($releaseInfo->getDependencyInfo()->getOptionals() as $group => $dependencyConstraints) {
foreach ($dependencyConstraints as $dependencyConstraint) {
$dependencyPackageName = $this->buildComposerPackageName($dependencyConstraint->getChannelName(), $dependencyConstraint->getPackageName());
$suggests[$group.'-'.$dependencyPackageName] = $dependencyConstraint->getConstraint();
}
}
$package = new CompletePackage($composerPackageName, $normalizedVersion, $version);
$package->setType('pear-library');
$package->setDescription($packageDefinition->getDescription());
$package->setLicense(array($packageDefinition->getLicense()));
$package->setDistType('file');
$package->setDistUrl($distUrl);
$package->setAutoload(array('classmap' => array('')));
$package->setIncludePaths(array('/'));
$package->setRequires($requires);
$package->setConflicts($conflicts);
$package->setSuggests($suggests);
$package->setReplaces($replaces);
$result[] = $package;
}
}
return $result;
} | php | private function buildComposerPackages(ChannelInfo $channelInfo, VersionParser $versionParser)
{
$result = array();
foreach ($channelInfo->getPackages() as $packageDefinition) {
foreach ($packageDefinition->getReleases() as $version => $releaseInfo) {
try {
$normalizedVersion = $versionParser->normalize($version);
} catch (\UnexpectedValueException $e) {
if ($this->io->isVerbose()) {
$this->io->writeError('Could not load '.$packageDefinition->getPackageName().' '.$version.': '.$e->getMessage());
}
continue;
}
$composerPackageName = $this->buildComposerPackageName($packageDefinition->getChannelName(), $packageDefinition->getPackageName());
// distribution url must be read from /r/{packageName}/{version}.xml::/r/g:text()
// but this location is 'de-facto' standard
$urlBits = parse_url($this->url);
$scheme = (isset($urlBits['scheme']) && 'https' === $urlBits['scheme'] && extension_loaded('openssl')) ? 'https' : 'http';
$distUrl = "{$scheme}://{$packageDefinition->getChannelName()}/get/{$packageDefinition->getPackageName()}-{$version}.tgz";
$requires = array();
$suggests = array();
$conflicts = array();
$replaces = array();
// alias package only when its channel matches repository channel,
// cause we've know only repository channel alias
if ($channelInfo->getName() == $packageDefinition->getChannelName()) {
$composerPackageAlias = $this->buildComposerPackageName($channelInfo->getAlias(), $packageDefinition->getPackageName());
$aliasConstraint = new VersionConstraint('==', $normalizedVersion);
$replaces[] = new Link($composerPackageName, $composerPackageAlias, $aliasConstraint, 'replaces', (string) $aliasConstraint);
}
// alias package with user-specified prefix. it makes private pear channels looks like composer's.
if (!empty($this->vendorAlias)
&& ($this->vendorAlias != 'pear-'.$channelInfo->getAlias() || $channelInfo->getName() != $packageDefinition->getChannelName())
) {
$composerPackageAlias = "{$this->vendorAlias}/{$packageDefinition->getPackageName()}";
$aliasConstraint = new VersionConstraint('==', $normalizedVersion);
$replaces[] = new Link($composerPackageName, $composerPackageAlias, $aliasConstraint, 'replaces', (string) $aliasConstraint);
}
foreach ($releaseInfo->getDependencyInfo()->getRequires() as $dependencyConstraint) {
$dependencyPackageName = $this->buildComposerPackageName($dependencyConstraint->getChannelName(), $dependencyConstraint->getPackageName());
$constraint = $versionParser->parseConstraints($dependencyConstraint->getConstraint());
$link = new Link($composerPackageName, $dependencyPackageName, $constraint, $dependencyConstraint->getType(), $dependencyConstraint->getConstraint());
switch ($dependencyConstraint->getType()) {
case 'required':
$requires[] = $link;
break;
case 'conflicts':
$conflicts[] = $link;
break;
case 'replaces':
$replaces[] = $link;
break;
}
}
foreach ($releaseInfo->getDependencyInfo()->getOptionals() as $group => $dependencyConstraints) {
foreach ($dependencyConstraints as $dependencyConstraint) {
$dependencyPackageName = $this->buildComposerPackageName($dependencyConstraint->getChannelName(), $dependencyConstraint->getPackageName());
$suggests[$group.'-'.$dependencyPackageName] = $dependencyConstraint->getConstraint();
}
}
$package = new CompletePackage($composerPackageName, $normalizedVersion, $version);
$package->setType('pear-library');
$package->setDescription($packageDefinition->getDescription());
$package->setLicense(array($packageDefinition->getLicense()));
$package->setDistType('file');
$package->setDistUrl($distUrl);
$package->setAutoload(array('classmap' => array('')));
$package->setIncludePaths(array('/'));
$package->setRequires($requires);
$package->setConflicts($conflicts);
$package->setSuggests($suggests);
$package->setReplaces($replaces);
$result[] = $package;
}
}
return $result;
} | [
"private",
"function",
"buildComposerPackages",
"(",
"ChannelInfo",
"$",
"channelInfo",
",",
"VersionParser",
"$",
"versionParser",
")",
"{",
"$",
"result",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"channelInfo",
"->",
"getPackages",
"(",
")",
"as",
... | Builds CompletePackages from PEAR package definition data.
@param ChannelInfo $channelInfo
@param VersionParser $versionParser
@return CompletePackage | [
"Builds",
"CompletePackages",
"from",
"PEAR",
"package",
"definition",
"data",
"."
] | train | https://github.com/mothership-ec/composer/blob/fa6ad031a939d8d33b211e428fdbdd28cfce238c/src/Composer/Repository/PearRepository.php#L92-L177 |
weew/http | src/Weew/Http/Cookie.php | Cookie.createFromString | public static function createFromString($string, ICookieParser $parser = null) {
if ( ! $parser instanceof ICookieParser) {
$parser = new CookieParser();
}
return $parser->parse($string);
} | php | public static function createFromString($string, ICookieParser $parser = null) {
if ( ! $parser instanceof ICookieParser) {
$parser = new CookieParser();
}
return $parser->parse($string);
} | [
"public",
"static",
"function",
"createFromString",
"(",
"$",
"string",
",",
"ICookieParser",
"$",
"parser",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"parser",
"instanceof",
"ICookieParser",
")",
"{",
"$",
"parser",
"=",
"new",
"CookieParser",
"(",
")",... | @param $string
@param ICookieParser $parser
@return ICookie | [
"@param",
"$string",
"@param",
"ICookieParser",
"$parser"
] | train | https://github.com/weew/http/blob/fd34d3d5643ca01c8e0946e888224a8e8dcc3c0d/src/Weew/Http/Cookie.php#L47-L53 |
weew/http | src/Weew/Http/Cookie.php | Cookie.send | public function send() {
if ( ! headers_sent()) {
setcookie(
$this->getName(),
$this->getValue(),
$this->getExpires(),
$this->getPath(),
$this->getDomain(),
$this->getSecure(),
$this->getHttpOnly()
);
}
} | php | public function send() {
if ( ! headers_sent()) {
setcookie(
$this->getName(),
$this->getValue(),
$this->getExpires(),
$this->getPath(),
$this->getDomain(),
$this->getSecure(),
$this->getHttpOnly()
);
}
} | [
"public",
"function",
"send",
"(",
")",
"{",
"if",
"(",
"!",
"headers_sent",
"(",
")",
")",
"{",
"setcookie",
"(",
"$",
"this",
"->",
"getName",
"(",
")",
",",
"$",
"this",
"->",
"getValue",
"(",
")",
",",
"$",
"this",
"->",
"getExpires",
"(",
")... | Send response. | [
"Send",
"response",
"."
] | train | https://github.com/weew/http/blob/fd34d3d5643ca01c8e0946e888224a8e8dcc3c0d/src/Weew/Http/Cookie.php#L243-L255 |
dstuecken/notify | src/Handler/SyslogHandler.php | SyslogHandler.handle | public function handle(NotificationInterface $notification, $level)
{
syslog($this->levelMapping[$level], $notification->message());
return true;
} | php | public function handle(NotificationInterface $notification, $level)
{
syslog($this->levelMapping[$level], $notification->message());
return true;
} | [
"public",
"function",
"handle",
"(",
"NotificationInterface",
"$",
"notification",
",",
"$",
"level",
")",
"{",
"syslog",
"(",
"$",
"this",
"->",
"levelMapping",
"[",
"$",
"level",
"]",
",",
"$",
"notification",
"->",
"message",
"(",
")",
")",
";",
"retu... | Handle a notification
@return bool | [
"Handle",
"a",
"notification"
] | train | https://github.com/dstuecken/notify/blob/abccf0a6a272caf66baea74323f18e2212c6e11e/src/Handler/SyslogHandler.php#L41-L46 |
php-lug/lug | src/Bundle/LocaleBundle/Behat/Context/LocaleWebContext.php | LocaleWebContext.assertGridCells | public function assertGridCells($column, $cells)
{
$this->gridContext->assertColumnCells(
$column,
array_map('trim', !empty($cells) ? explode(';', $cells) : [])
);
} | php | public function assertGridCells($column, $cells)
{
$this->gridContext->assertColumnCells(
$column,
array_map('trim', !empty($cells) ? explode(';', $cells) : [])
);
} | [
"public",
"function",
"assertGridCells",
"(",
"$",
"column",
",",
"$",
"cells",
")",
"{",
"$",
"this",
"->",
"gridContext",
"->",
"assertColumnCells",
"(",
"$",
"column",
",",
"array_map",
"(",
"'trim'",
",",
"!",
"empty",
"(",
"$",
"cells",
")",
"?",
... | @param string $column
@param string $cells
@Given the locale grid for the column ":column" should be ":cells" | [
"@param",
"string",
"$column",
"@param",
"string",
"$cells"
] | train | https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/LocaleBundle/Behat/Context/LocaleWebContext.php#L193-L199 |
rhosocial/yii2-user | models/invitation/registration/UserInvitationRegistrationTrait.php | UserInvitationRegistrationTrait.hasEnabledInvitationRegistration | public function hasEnabledInvitationRegistration()
{
if ($this->invitationRegistrationClass === false || !is_string($this->invitationRegistrationClass) || !class_exists($this->invitationRegistrationClass)) {
return false;
}
return true;
} | php | public function hasEnabledInvitationRegistration()
{
if ($this->invitationRegistrationClass === false || !is_string($this->invitationRegistrationClass) || !class_exists($this->invitationRegistrationClass)) {
return false;
}
return true;
} | [
"public",
"function",
"hasEnabledInvitationRegistration",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"invitationRegistrationClass",
"===",
"false",
"||",
"!",
"is_string",
"(",
"$",
"this",
"->",
"invitationRegistrationClass",
")",
"||",
"!",
"class_exists",
"("... | Check whether this user enables the invitation from registration feature or not.
@return boolean | [
"Check",
"whether",
"this",
"user",
"enables",
"the",
"invitation",
"from",
"registration",
"feature",
"or",
"not",
"."
] | train | https://github.com/rhosocial/yii2-user/blob/96737a9d8ca7e9c42cd2b7736d6c0a90ede6e5bc/models/invitation/registration/UserInvitationRegistrationTrait.php#L86-L92 |
glynnforrest/active-doctrine | src/ActiveDoctrine/Entity/EntityCollection.php | EntityCollection.setColumn | public function setColumn($name, $value)
{
foreach ($this->entities as $entity) {
$entity->set($name, $value);
}
return $this;
} | php | public function setColumn($name, $value)
{
foreach ($this->entities as $entity) {
$entity->set($name, $value);
}
return $this;
} | [
"public",
"function",
"setColumn",
"(",
"$",
"name",
",",
"$",
"value",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"entities",
"as",
"$",
"entity",
")",
"{",
"$",
"entity",
"->",
"set",
"(",
"$",
"name",
",",
"$",
"value",
")",
";",
"}",
"retur... | Set the value of a column for all entities in this
collection. Setter methods will be called.
@param string $name The name of the column
@param mixed $value The value
@return EntityCollection This collection | [
"Set",
"the",
"value",
"of",
"a",
"column",
"for",
"all",
"entities",
"in",
"this",
"collection",
".",
"Setter",
"methods",
"will",
"be",
"called",
"."
] | train | https://github.com/glynnforrest/active-doctrine/blob/fcf8c434c7df4704966107bf9a95c005a0b37168/src/ActiveDoctrine/Entity/EntityCollection.php#L68-L75 |
glynnforrest/active-doctrine | src/ActiveDoctrine/Entity/EntityCollection.php | EntityCollection.setColumnRaw | public function setColumnRaw($name, $value)
{
foreach ($this->entities as $entity) {
$entity->setRaw($name, $value);
}
return $this;
} | php | public function setColumnRaw($name, $value)
{
foreach ($this->entities as $entity) {
$entity->setRaw($name, $value);
}
return $this;
} | [
"public",
"function",
"setColumnRaw",
"(",
"$",
"name",
",",
"$",
"value",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"entities",
"as",
"$",
"entity",
")",
"{",
"$",
"entity",
"->",
"setRaw",
"(",
"$",
"name",
",",
"$",
"value",
")",
";",
"}",
... | Set the value of a column for all entities in this
collection. Setter methods will not be called.
@param string $name The name of the column
@param mixed $value The value
@return EntityCollection This collection | [
"Set",
"the",
"value",
"of",
"a",
"column",
"for",
"all",
"entities",
"in",
"this",
"collection",
".",
"Setter",
"methods",
"will",
"not",
"be",
"called",
"."
] | train | https://github.com/glynnforrest/active-doctrine/blob/fcf8c434c7df4704966107bf9a95c005a0b37168/src/ActiveDoctrine/Entity/EntityCollection.php#L85-L92 |
glynnforrest/active-doctrine | src/ActiveDoctrine/Entity/EntityCollection.php | EntityCollection.getColumn | public function getColumn($name)
{
$results = [];
foreach ($this->entities as $entity) {
$results[] = $entity->get($name);
}
return $results;
} | php | public function getColumn($name)
{
$results = [];
foreach ($this->entities as $entity) {
$results[] = $entity->get($name);
}
return $results;
} | [
"public",
"function",
"getColumn",
"(",
"$",
"name",
")",
"{",
"$",
"results",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"entities",
"as",
"$",
"entity",
")",
"{",
"$",
"results",
"[",
"]",
"=",
"$",
"entity",
"->",
"get",
"(",
"$",
... | Get the values of a single column from all entities in this
collection. Getter methods will be called.
@param string $name The name of the column
@return array A list of values | [
"Get",
"the",
"values",
"of",
"a",
"single",
"column",
"from",
"all",
"entities",
"in",
"this",
"collection",
".",
"Getter",
"methods",
"will",
"be",
"called",
"."
] | train | https://github.com/glynnforrest/active-doctrine/blob/fcf8c434c7df4704966107bf9a95c005a0b37168/src/ActiveDoctrine/Entity/EntityCollection.php#L101-L109 |
glynnforrest/active-doctrine | src/ActiveDoctrine/Entity/EntityCollection.php | EntityCollection.getColumnRaw | public function getColumnRaw($name)
{
$results = [];
foreach ($this->entities as $entity) {
$results[] = $entity->getRaw($name);
}
return $results;
} | php | public function getColumnRaw($name)
{
$results = [];
foreach ($this->entities as $entity) {
$results[] = $entity->getRaw($name);
}
return $results;
} | [
"public",
"function",
"getColumnRaw",
"(",
"$",
"name",
")",
"{",
"$",
"results",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"entities",
"as",
"$",
"entity",
")",
"{",
"$",
"results",
"[",
"]",
"=",
"$",
"entity",
"->",
"getRaw",
"(",
... | Get the values of a single column from all entities in this
collection. Getter methods will not be called.
@param string $name The name of the column
@return array A list of values | [
"Get",
"the",
"values",
"of",
"a",
"single",
"column",
"from",
"all",
"entities",
"in",
"this",
"collection",
".",
"Getter",
"methods",
"will",
"not",
"be",
"called",
"."
] | train | https://github.com/glynnforrest/active-doctrine/blob/fcf8c434c7df4704966107bf9a95c005a0b37168/src/ActiveDoctrine/Entity/EntityCollection.php#L118-L126 |
glynnforrest/active-doctrine | src/ActiveDoctrine/Entity/EntityCollection.php | EntityCollection.getOne | public function getOne($column, $value, $strict = true)
{
if ($strict) {
foreach ($this->entities as $entity) {
if ($entity->get($column) === $value) {
return $entity;
}
}
} else {
foreach ($this->entities as $entity) {
if ($entity->get($column) == $value) {
return $entity;
}
}
}
return;
} | php | public function getOne($column, $value, $strict = true)
{
if ($strict) {
foreach ($this->entities as $entity) {
if ($entity->get($column) === $value) {
return $entity;
}
}
} else {
foreach ($this->entities as $entity) {
if ($entity->get($column) == $value) {
return $entity;
}
}
}
return;
} | [
"public",
"function",
"getOne",
"(",
"$",
"column",
",",
"$",
"value",
",",
"$",
"strict",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"strict",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"entities",
"as",
"$",
"entity",
")",
"{",
"if",
"(",
"$",
... | Get a single Entity from this collection where column =
value. If more than one Entity is matched, the first will be
returned. If no Entity is matched, null will be returned.
@param string $column
@param string $value
@param bool $strict use strict comparison when comparing values
@return mixed Entity or NULL | [
"Get",
"a",
"single",
"Entity",
"from",
"this",
"collection",
"where",
"column",
"=",
"value",
".",
"If",
"more",
"than",
"one",
"Entity",
"is",
"matched",
"the",
"first",
"will",
"be",
"returned",
".",
"If",
"no",
"Entity",
"is",
"matched",
"null",
"wil... | train | https://github.com/glynnforrest/active-doctrine/blob/fcf8c434c7df4704966107bf9a95c005a0b37168/src/ActiveDoctrine/Entity/EntityCollection.php#L138-L155 |
glynnforrest/active-doctrine | src/ActiveDoctrine/Entity/EntityCollection.php | EntityCollection.getRandom | public function getRandom()
{
return empty($this->entities) ? null : $this->entities[array_rand($this->entities)];
} | php | public function getRandom()
{
return empty($this->entities) ? null : $this->entities[array_rand($this->entities)];
} | [
"public",
"function",
"getRandom",
"(",
")",
"{",
"return",
"empty",
"(",
"$",
"this",
"->",
"entities",
")",
"?",
"null",
":",
"$",
"this",
"->",
"entities",
"[",
"array_rand",
"(",
"$",
"this",
"->",
"entities",
")",
"]",
";",
"}"
] | Get a random Entity from this collection, or null if the
collection is empty.
@return Entity|null | [
"Get",
"a",
"random",
"Entity",
"from",
"this",
"collection",
"or",
"null",
"if",
"the",
"collection",
"is",
"empty",
"."
] | train | https://github.com/glynnforrest/active-doctrine/blob/fcf8c434c7df4704966107bf9a95c005a0b37168/src/ActiveDoctrine/Entity/EntityCollection.php#L163-L166 |
glynnforrest/active-doctrine | src/ActiveDoctrine/Entity/EntityCollection.php | EntityCollection.remove | public function remove($column, $value)
{
foreach ($this->entities as $index => $entity) {
if ($entity->get($column) === $value) {
//remove the entity and reset the keys
unset($this->entities[$index]);
$this->entities = array_values($this->entities);
return $entity;
}
}
return;
} | php | public function remove($column, $value)
{
foreach ($this->entities as $index => $entity) {
if ($entity->get($column) === $value) {
//remove the entity and reset the keys
unset($this->entities[$index]);
$this->entities = array_values($this->entities);
return $entity;
}
}
return;
} | [
"public",
"function",
"remove",
"(",
"$",
"column",
",",
"$",
"value",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"entities",
"as",
"$",
"index",
"=>",
"$",
"entity",
")",
"{",
"if",
"(",
"$",
"entity",
"->",
"get",
"(",
"$",
"column",
")",
"==... | Remove a single Entity from this collection where column =
value. If more than one Entity is matched, the first will be
removed and returned. If no Entity is matched, null will be
returned.
@param string $column
@param string $value
@return mixed The removed Entity or NULL | [
"Remove",
"a",
"single",
"Entity",
"from",
"this",
"collection",
"where",
"column",
"=",
"value",
".",
"If",
"more",
"than",
"one",
"Entity",
"is",
"matched",
"the",
"first",
"will",
"be",
"removed",
"and",
"returned",
".",
"If",
"no",
"Entity",
"is",
"m... | train | https://github.com/glynnforrest/active-doctrine/blob/fcf8c434c7df4704966107bf9a95c005a0b37168/src/ActiveDoctrine/Entity/EntityCollection.php#L178-L191 |
glynnforrest/active-doctrine | src/ActiveDoctrine/Entity/EntityCollection.php | EntityCollection.removeRandom | public function removeRandom()
{
$index = array_rand($this->entities);
$entity = $this->entities[$index];
unset($this->entities[$index]);
return $entity;
} | php | public function removeRandom()
{
$index = array_rand($this->entities);
$entity = $this->entities[$index];
unset($this->entities[$index]);
return $entity;
} | [
"public",
"function",
"removeRandom",
"(",
")",
"{",
"$",
"index",
"=",
"array_rand",
"(",
"$",
"this",
"->",
"entities",
")",
";",
"$",
"entity",
"=",
"$",
"this",
"->",
"entities",
"[",
"$",
"index",
"]",
";",
"unset",
"(",
"$",
"this",
"->",
"en... | Remove a random Entity from this collection, or null if the
collection is empty.
@return Entity|null | [
"Remove",
"a",
"random",
"Entity",
"from",
"this",
"collection",
"or",
"null",
"if",
"the",
"collection",
"is",
"empty",
"."
] | train | https://github.com/glynnforrest/active-doctrine/blob/fcf8c434c7df4704966107bf9a95c005a0b37168/src/ActiveDoctrine/Entity/EntityCollection.php#L199-L206 |
comodojo/daemon | src/Comodojo/Daemon/Utils/ProcessTools.php | ProcessTools.term | public static function term($pid, $lagger_timeout = 0, $signal = SIGTERM) {
$kill_time = time() + $lagger_timeout;
// $term = posix_kill($pid, $signal);
$term = self::signal($pid, $signal);
while ( time() < $kill_time ) {
if ( !self::isRunning($pid) ) return $term;
usleep(20000);
}
return self::kill($pid);
} | php | public static function term($pid, $lagger_timeout = 0, $signal = SIGTERM) {
$kill_time = time() + $lagger_timeout;
// $term = posix_kill($pid, $signal);
$term = self::signal($pid, $signal);
while ( time() < $kill_time ) {
if ( !self::isRunning($pid) ) return $term;
usleep(20000);
}
return self::kill($pid);
} | [
"public",
"static",
"function",
"term",
"(",
"$",
"pid",
",",
"$",
"lagger_timeout",
"=",
"0",
",",
"$",
"signal",
"=",
"SIGTERM",
")",
"{",
"$",
"kill_time",
"=",
"time",
"(",
")",
"+",
"$",
"lagger_timeout",
";",
"// $term = posix_kill($pid, $signal);",
... | Terminate a process, asking PID to terminate or killing it directly.
@param int $pid
@param int $lagger_timeout Timeout to wait before killing process if it refuses to terminate
@param int $signal Signal to send (default to SIGTERM)
@return bool | [
"Terminate",
"a",
"process",
"asking",
"PID",
"to",
"terminate",
"or",
"killing",
"it",
"directly",
"."
] | train | https://github.com/comodojo/daemon/blob/361b0a3a91dc7720dd3bec448bb4ca47d0ef0292/src/Comodojo/Daemon/Utils/ProcessTools.php#L32-L48 |
comodojo/daemon | src/Comodojo/Daemon/Utils/ProcessTools.php | ProcessTools.setNiceness | public static function setNiceness($niceness, $pid = null) {
return is_null($pid) ? @proc_nice($niceness) : @pcntl_setpriority($pid, $niceness);
} | php | public static function setNiceness($niceness, $pid = null) {
return is_null($pid) ? @proc_nice($niceness) : @pcntl_setpriority($pid, $niceness);
} | [
"public",
"static",
"function",
"setNiceness",
"(",
"$",
"niceness",
",",
"$",
"pid",
"=",
"null",
")",
"{",
"return",
"is_null",
"(",
"$",
"pid",
")",
"?",
"@",
"proc_nice",
"(",
"$",
"niceness",
")",
":",
"@",
"pcntl_setpriority",
"(",
"$",
"pid",
... | Set niceness of a running process
@param int|null $pid The pid to query, or current process if null
@return bool | [
"Set",
"niceness",
"of",
"a",
"running",
"process"
] | train | https://github.com/comodojo/daemon/blob/361b0a3a91dc7720dd3bec448bb4ca47d0ef0292/src/Comodojo/Daemon/Utils/ProcessTools.php#L99-L103 |
titledk/silverstripe-uploaddirrules | code/rules/UploadDirRules.php | UploadDirRules.calc_base_directory_for_object | public static function calc_base_directory_for_object(DataObject $do)
{
//the 2 base options - dataobjects / pages
$str = 'dataobjects';
$ancestry = $do->getClassAncestry();
foreach ($ancestry as $c) {
if ($c == 'SiteTree') {
$str = 'pages';
}
}
//other options
switch ($do->ClassName) {
//case 'Subsite':
// $str = 'subsites';
// break;
case 'SiteConfig':
$str = 'site';
break;
default:
}
return $str;
} | php | public static function calc_base_directory_for_object(DataObject $do)
{
//the 2 base options - dataobjects / pages
$str = 'dataobjects';
$ancestry = $do->getClassAncestry();
foreach ($ancestry as $c) {
if ($c == 'SiteTree') {
$str = 'pages';
}
}
//other options
switch ($do->ClassName) {
//case 'Subsite':
// $str = 'subsites';
// break;
case 'SiteConfig':
$str = 'site';
break;
default:
}
return $str;
} | [
"public",
"static",
"function",
"calc_base_directory_for_object",
"(",
"DataObject",
"$",
"do",
")",
"{",
"//the 2 base options - dataobjects / pages",
"$",
"str",
"=",
"'dataobjects'",
";",
"$",
"ancestry",
"=",
"$",
"do",
"->",
"getClassAncestry",
"(",
")",
";",
... | Base rules.
@param DataObject $do
@return string | [
"Base",
"rules",
"."
] | train | https://github.com/titledk/silverstripe-uploaddirrules/blob/ed8ece7b6a4ca86dcb5dc16ee10ff339f629de3c/code/rules/UploadDirRules.php#L32-L59 |
nabab/bbn | src/bbn/db/languages/sqlite.php | sqlite.col_full_name | public function col_full_name(string $col, $table = null, $escaped = false): ?string
{
if ( $col = trim($col) ){
$bits = explode('.', str_replace($this->qte, '', $col));
$ok = null;
$col = array_pop($bits);
if ( $table && ($table = $this->table_simple_name($table)) ){
$ok = 1;
}
else if ( \count($bits) ){
$table = array_pop($bits);
$ok = 1;
}
if ( (null !== $ok) && bbn\str::check_name($table, $col) ){
return $escaped ? '"'.$table.'"."'.$col.'"' : $table.'.'.$col;
}
}
return null;
} | php | public function col_full_name(string $col, $table = null, $escaped = false): ?string
{
if ( $col = trim($col) ){
$bits = explode('.', str_replace($this->qte, '', $col));
$ok = null;
$col = array_pop($bits);
if ( $table && ($table = $this->table_simple_name($table)) ){
$ok = 1;
}
else if ( \count($bits) ){
$table = array_pop($bits);
$ok = 1;
}
if ( (null !== $ok) && bbn\str::check_name($table, $col) ){
return $escaped ? '"'.$table.'"."'.$col.'"' : $table.'.'.$col;
}
}
return null;
} | [
"public",
"function",
"col_full_name",
"(",
"string",
"$",
"col",
",",
"$",
"table",
"=",
"null",
",",
"$",
"escaped",
"=",
"false",
")",
":",
"?",
"string",
"{",
"if",
"(",
"$",
"col",
"=",
"trim",
"(",
"$",
"col",
")",
")",
"{",
"$",
"bits",
... | Returns a column's full name i.e. table.column
@param string $col The column's name (escaped or not)
@param null|string $table The table's name (escaped or not)
@param bool $escaped If set to true the returned string will be escaped
@return null|string | [
"Returns",
"a",
"column",
"s",
"full",
"name",
"i",
".",
"e",
".",
"table",
".",
"column"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db/languages/sqlite.php#L202-L220 |
nabab/bbn | src/bbn/db/languages/sqlite.php | sqlite.get_conditions | public function get_conditions(array $conditions, array $cfg = [], bool $is_having = false): string
{
$res = '';
if ( isset($conditions['conditions'], $conditions['logic']) ){
$logic = isset($conditions['logic']) && ($conditions['logic'] === 'OR') ? 'OR' : 'AND';
foreach ( $conditions['conditions'] as $key => $f ){
if ( \is_array($f) && isset($f['logic']) && !empty($f['conditions']) ){
if ( $tmp = $this->get_conditions($f, $cfg, $is_having) ){
$res .= (empty($res) ? '(' : PHP_EOL."$logic ").$tmp;
}
}
else if ( isset($f['operator'], $f['field']) ){
$field = $f['field'];
if ( !array_key_exists('value', $f) ){
$f['value'] = false;
}
$is_number = false;
$is_null = true;
$is_uid = false;
$is_date = false;
$model = null;
if ( isset($cfg['available_fields'][$field]) ){
$table = $cfg['available_fields'][$field];
$column = $this->col_simple_name($cfg['fields'][$field] ?? $field);
if ( isset($cfg['models'][$table]['fields'][$column]) ){
$model = $cfg['models'][$table]['fields'][$column];
$res .= (empty($res) ?
'(' :
" $logic ").(
!empty($cfg['available_fields'][$field]) ?
$this->col_full_name($cfg['fields'][$field] ?? $field, $cfg['available_fields'][$field], true).' ' :
$this->col_simple_name($column, true)
);
}
else{
$res .= (empty($res) ? '(' : PHP_EOL."$logic ").$field.' ';
}
if ( !empty($model) ){
$is_null = (bool)$model['null'];
if ( $model['type'] === 'binary' ){
$is_number = true;
if ( ($model['maxlength'] === 16) && $model['key'] ){
$is_uid = true;
}
}
else if ( \in_array($model['type'], self::$numeric_types, true) ){
$is_number = true;
}
else if ( \in_array($model['type'], self::$date_types, true) ){
$is_date = true;
}
}
else if ( $f['value'] && \bbn\str::is_uid($f['value']) ){
$is_uid = true;
}
}
else{
$res .= (empty($res) ? '(' : " $logic ").$field.' ';
}
switch ( strtolower($f['operator']) ){
case 'like':
$res .= 'LIKE ?';
break;
case 'not like':
$res .= 'NOT LIKE ?';
break;
case 'eq':
case '=':
case 'is':
if ( isset($f['exp']) ){
$res .= '= '.$f['exp'];
}
else if ( $is_uid || $is_number ){
$res .= '= ?';
}
else{
$res .= 'LIKE ?';
}
break;
case 'neq':
case '!=':
case 'isnot':
if ( isset($f['exp']) ){
$res .= '!= '.$f['exp'];
}
else if ( $is_uid || $is_number ){
$res .= '!= ?';
}
else{
$res .= 'NOT LIKE ?';
}
break;
case 'doesnotcontains':
$res .= 'NOT LIKE '.($f['exp'] ?? '?');
break;
case 'endswith':
case 'startswith':
case 'contains':
$res .= 'LIKE '.($f['exp'] ?? '?');
break;
case 'gte':
case '>=':
if ( isset($f['exp']) ){
$res .= '>= '.$f['exp'];
}
else{
$res .= '>= ?';
}
break;
case 'gt':
case '>':
if ( isset($f['exp']) ){
$res .= '> '.$f['exp'];
}
else{
$res .= '> ?';
}
break;
case 'lte':
case '<=':
if ( isset($f['exp']) ){
$res .= '<= '.$f['exp'];
}
else{
$res .= '<= ?';
}
break;
case 'lt':
case '<':
if ( isset($f['exp']) ){
$res .= '< '.$f['exp'];
}
else{
$res .= '< ?';
}
break;
/** @todo Check if it is working with an array */
case 'isnull':
$res .= $is_null ? 'IS NULL' : " = ''";
break;
case 'isnotnull':
$res .= $is_null ? 'IS NOT NULL' : " != ''";
break;
case 'isempty':
$res .= $is_number ? '= 0' : "LIKE ''";
break;
case 'isnotempty':
$res .= $is_number ? '!= 0' : "NOT LIKE ''";
break;
case 'doesnotcontain':
$res .= $is_number ? '!= ?' : 'NOT LIKE ?';
break;
case 'contains':
default:
$res .= $is_number ? '= ?' : 'LIKE ?';
break;
}
}
}
if ( !empty($res) ){
$res .= ')'.PHP_EOL;
}
}
return $res;
} | php | public function get_conditions(array $conditions, array $cfg = [], bool $is_having = false): string
{
$res = '';
if ( isset($conditions['conditions'], $conditions['logic']) ){
$logic = isset($conditions['logic']) && ($conditions['logic'] === 'OR') ? 'OR' : 'AND';
foreach ( $conditions['conditions'] as $key => $f ){
if ( \is_array($f) && isset($f['logic']) && !empty($f['conditions']) ){
if ( $tmp = $this->get_conditions($f, $cfg, $is_having) ){
$res .= (empty($res) ? '(' : PHP_EOL."$logic ").$tmp;
}
}
else if ( isset($f['operator'], $f['field']) ){
$field = $f['field'];
if ( !array_key_exists('value', $f) ){
$f['value'] = false;
}
$is_number = false;
$is_null = true;
$is_uid = false;
$is_date = false;
$model = null;
if ( isset($cfg['available_fields'][$field]) ){
$table = $cfg['available_fields'][$field];
$column = $this->col_simple_name($cfg['fields'][$field] ?? $field);
if ( isset($cfg['models'][$table]['fields'][$column]) ){
$model = $cfg['models'][$table]['fields'][$column];
$res .= (empty($res) ?
'(' :
" $logic ").(
!empty($cfg['available_fields'][$field]) ?
$this->col_full_name($cfg['fields'][$field] ?? $field, $cfg['available_fields'][$field], true).' ' :
$this->col_simple_name($column, true)
);
}
else{
$res .= (empty($res) ? '(' : PHP_EOL."$logic ").$field.' ';
}
if ( !empty($model) ){
$is_null = (bool)$model['null'];
if ( $model['type'] === 'binary' ){
$is_number = true;
if ( ($model['maxlength'] === 16) && $model['key'] ){
$is_uid = true;
}
}
else if ( \in_array($model['type'], self::$numeric_types, true) ){
$is_number = true;
}
else if ( \in_array($model['type'], self::$date_types, true) ){
$is_date = true;
}
}
else if ( $f['value'] && \bbn\str::is_uid($f['value']) ){
$is_uid = true;
}
}
else{
$res .= (empty($res) ? '(' : " $logic ").$field.' ';
}
switch ( strtolower($f['operator']) ){
case 'like':
$res .= 'LIKE ?';
break;
case 'not like':
$res .= 'NOT LIKE ?';
break;
case 'eq':
case '=':
case 'is':
if ( isset($f['exp']) ){
$res .= '= '.$f['exp'];
}
else if ( $is_uid || $is_number ){
$res .= '= ?';
}
else{
$res .= 'LIKE ?';
}
break;
case 'neq':
case '!=':
case 'isnot':
if ( isset($f['exp']) ){
$res .= '!= '.$f['exp'];
}
else if ( $is_uid || $is_number ){
$res .= '!= ?';
}
else{
$res .= 'NOT LIKE ?';
}
break;
case 'doesnotcontains':
$res .= 'NOT LIKE '.($f['exp'] ?? '?');
break;
case 'endswith':
case 'startswith':
case 'contains':
$res .= 'LIKE '.($f['exp'] ?? '?');
break;
case 'gte':
case '>=':
if ( isset($f['exp']) ){
$res .= '>= '.$f['exp'];
}
else{
$res .= '>= ?';
}
break;
case 'gt':
case '>':
if ( isset($f['exp']) ){
$res .= '> '.$f['exp'];
}
else{
$res .= '> ?';
}
break;
case 'lte':
case '<=':
if ( isset($f['exp']) ){
$res .= '<= '.$f['exp'];
}
else{
$res .= '<= ?';
}
break;
case 'lt':
case '<':
if ( isset($f['exp']) ){
$res .= '< '.$f['exp'];
}
else{
$res .= '< ?';
}
break;
/** @todo Check if it is working with an array */
case 'isnull':
$res .= $is_null ? 'IS NULL' : " = ''";
break;
case 'isnotnull':
$res .= $is_null ? 'IS NOT NULL' : " != ''";
break;
case 'isempty':
$res .= $is_number ? '= 0' : "LIKE ''";
break;
case 'isnotempty':
$res .= $is_number ? '!= 0' : "NOT LIKE ''";
break;
case 'doesnotcontain':
$res .= $is_number ? '!= ?' : 'NOT LIKE ?';
break;
case 'contains':
default:
$res .= $is_number ? '= ?' : 'LIKE ?';
break;
}
}
}
if ( !empty($res) ){
$res .= ')'.PHP_EOL;
}
}
return $res;
} | [
"public",
"function",
"get_conditions",
"(",
"array",
"$",
"conditions",
",",
"array",
"$",
"cfg",
"=",
"[",
"]",
",",
"bool",
"$",
"is_having",
"=",
"false",
")",
":",
"string",
"{",
"$",
"res",
"=",
"''",
";",
"if",
"(",
"isset",
"(",
"$",
"condi... | Returns a string with the conditions for the ON, WHERE, or HAVING part of the query if there is, empty otherwise
@param array $conditions
@param array $cfg
@param bool $is_having
@return string | [
"Returns",
"a",
"string",
"with",
"the",
"conditions",
"for",
"the",
"ON",
"WHERE",
"or",
"HAVING",
"part",
"of",
"the",
"query",
"if",
"there",
"is",
"empty",
"otherwise"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db/languages/sqlite.php#L436-L612 |
nabab/bbn | src/bbn/db/languages/sqlite.php | sqlite.get_select | public function get_select(array $cfg): string
{
$res = '';
if ( \is_array($cfg['tables']) && !empty($cfg['tables']) ){
$res = 'SELECT ';
if ( !empty($cfg['fields']) ){
$fields_to_put = [];
// Checking the selected fields
foreach ( $cfg['fields'] as $alias => $f ){
$is_distinct = false;
$f = trim($f);
$bits = explode(' ', $f);
if ( (count($bits) > 1) && (strtolower($bits[0]) === 'distinct') ){
$is_distinct = true;
array_shift($bits);
$f = implode(' ', $bits);
}
// Adding the alias in $fields
if ( strpos($f, '(') ){
$fields_to_put[] = ($is_distinct ? 'DISTINCT ' : '').$f.(\is_string($alias) ? ' AS '.$this->escape($alias) : '');
}
else if ( !empty($cfg['available_fields'][$f]) ){
$idx = $cfg['available_fields'][$f];
$csn = $this->col_simple_name($f);
$is_uid = false;
//die(var_dump($idx, $f, $tables[$idx]));
if ( ($idx !== false) && isset($cfg['models'][$idx]['fields'][$csn]) ){
$column = $cfg['models'][$idx]['fields'][$csn];
if ( ($column['type'] === 'binary') && ($column['maxlength'] === 16) ){
$is_uid = true;
if ( !\is_string($alias) ){
$alias = $csn;
}
}
}
//$res['fields'][$alias] = $this->cfn($f, $fields[$f]);
if ( $is_uid ){
$st = 'LOWER(HEX('.$this->col_full_name($csn, $cfg['available_fields'][$f], true).'))';
}
// For JSON fields
else if ( $cfg['available_fields'][$f] === false ){
$st = $f;
}
else{
$st = $this->col_full_name($csn, $cfg['available_fields'][$f], true);
}
if ( \is_string($alias) ){
$st .= ' AS '.$this->escape($alias);
}
$fields_to_put[] = ($is_distinct ? 'DISTINCT ' : '').$st;
}
else if ( isset($cfg['available_fields'][$f]) && ($cfg['available_fields'][$f] === false) ){
$this->db->error("Error! The column '$f' exists on several tables in '".implode(', ', $cfg['tables']));
}
else{
$this->db->error("Error! The column '$f' doesn't exist in '".implode(', ', $cfg['tables']).' ('.implode(' - ', array_keys($cfg['available_fields'])).')');
}
}
$res .= implode(', ', $fields_to_put);
}
$res .= PHP_EOL;
$tables_to_put = [];
foreach ( $cfg['tables'] as $alias => $tfn ){
$st = $this->table_full_name($tfn, true);
if ( $alias !== $tfn ){
$st .= ' AS '.$this->escape($alias);
}
$tables_to_put[] = $st;
}
$res .= 'FROM '.implode(', ', $tables_to_put).PHP_EOL;
return $res;
}
return $res;
} | php | public function get_select(array $cfg): string
{
$res = '';
if ( \is_array($cfg['tables']) && !empty($cfg['tables']) ){
$res = 'SELECT ';
if ( !empty($cfg['fields']) ){
$fields_to_put = [];
// Checking the selected fields
foreach ( $cfg['fields'] as $alias => $f ){
$is_distinct = false;
$f = trim($f);
$bits = explode(' ', $f);
if ( (count($bits) > 1) && (strtolower($bits[0]) === 'distinct') ){
$is_distinct = true;
array_shift($bits);
$f = implode(' ', $bits);
}
// Adding the alias in $fields
if ( strpos($f, '(') ){
$fields_to_put[] = ($is_distinct ? 'DISTINCT ' : '').$f.(\is_string($alias) ? ' AS '.$this->escape($alias) : '');
}
else if ( !empty($cfg['available_fields'][$f]) ){
$idx = $cfg['available_fields'][$f];
$csn = $this->col_simple_name($f);
$is_uid = false;
//die(var_dump($idx, $f, $tables[$idx]));
if ( ($idx !== false) && isset($cfg['models'][$idx]['fields'][$csn]) ){
$column = $cfg['models'][$idx]['fields'][$csn];
if ( ($column['type'] === 'binary') && ($column['maxlength'] === 16) ){
$is_uid = true;
if ( !\is_string($alias) ){
$alias = $csn;
}
}
}
//$res['fields'][$alias] = $this->cfn($f, $fields[$f]);
if ( $is_uid ){
$st = 'LOWER(HEX('.$this->col_full_name($csn, $cfg['available_fields'][$f], true).'))';
}
// For JSON fields
else if ( $cfg['available_fields'][$f] === false ){
$st = $f;
}
else{
$st = $this->col_full_name($csn, $cfg['available_fields'][$f], true);
}
if ( \is_string($alias) ){
$st .= ' AS '.$this->escape($alias);
}
$fields_to_put[] = ($is_distinct ? 'DISTINCT ' : '').$st;
}
else if ( isset($cfg['available_fields'][$f]) && ($cfg['available_fields'][$f] === false) ){
$this->db->error("Error! The column '$f' exists on several tables in '".implode(', ', $cfg['tables']));
}
else{
$this->db->error("Error! The column '$f' doesn't exist in '".implode(', ', $cfg['tables']).' ('.implode(' - ', array_keys($cfg['available_fields'])).')');
}
}
$res .= implode(', ', $fields_to_put);
}
$res .= PHP_EOL;
$tables_to_put = [];
foreach ( $cfg['tables'] as $alias => $tfn ){
$st = $this->table_full_name($tfn, true);
if ( $alias !== $tfn ){
$st .= ' AS '.$this->escape($alias);
}
$tables_to_put[] = $st;
}
$res .= 'FROM '.implode(', ', $tables_to_put).PHP_EOL;
return $res;
}
return $res;
} | [
"public",
"function",
"get_select",
"(",
"array",
"$",
"cfg",
")",
":",
"string",
"{",
"$",
"res",
"=",
"''",
";",
"if",
"(",
"\\",
"is_array",
"(",
"$",
"cfg",
"[",
"'tables'",
"]",
")",
"&&",
"!",
"empty",
"(",
"$",
"cfg",
"[",
"'tables'",
"]",... | Generates a string starting with SELECT ... FROM with corresponding parameters
@param array $cfg The configuration array
@return string | [
"Generates",
"a",
"string",
"starting",
"with",
"SELECT",
"...",
"FROM",
"with",
"corresponding",
"parameters"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db/languages/sqlite.php#L620-L693 |
nabab/bbn | src/bbn/db/languages/sqlite.php | sqlite.delete_index | public function delete_index(string $table, string $key): bool
{
if ( ( $table = $this->table_full_name($table, 1) ) && bbn\str::check_name($key) ){
return (bool)$this->db->query("ALTER TABLE $table DROP INDEX `$key`");
}
return false;
} | php | public function delete_index(string $table, string $key): bool
{
if ( ( $table = $this->table_full_name($table, 1) ) && bbn\str::check_name($key) ){
return (bool)$this->db->query("ALTER TABLE $table DROP INDEX `$key`");
}
return false;
} | [
"public",
"function",
"delete_index",
"(",
"string",
"$",
"table",
",",
"string",
"$",
"key",
")",
":",
"bool",
"{",
"if",
"(",
"(",
"$",
"table",
"=",
"$",
"this",
"->",
"table_full_name",
"(",
"$",
"table",
",",
"1",
")",
")",
"&&",
"bbn",
"\\",
... | Deletes an index
@param null|string $table
@param string $key
@return bool | [
"Deletes",
"an",
"index"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db/languages/sqlite.php#L979-L985 |
nabab/bbn | src/bbn/db/languages/sqlite.php | sqlite.create_user | public function create_user(string $user, string $pass, string $db = null): bool
{
return true;
} | php | public function create_user(string $user, string $pass, string $db = null): bool
{
return true;
} | [
"public",
"function",
"create_user",
"(",
"string",
"$",
"user",
",",
"string",
"$",
"pass",
",",
"string",
"$",
"db",
"=",
"null",
")",
":",
"bool",
"{",
"return",
"true",
";",
"}"
] | Creates a database user
@param string $user
@param string $pass
@param string $db
@return bool | [
"Creates",
"a",
"database",
"user"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/db/languages/sqlite.php#L995-L998 |
alevilar/ristorantino-vendor | Stats/Model/Query.php | Query.listarCategorias | function listarCategorias($filtro = '*'){
$conditions[] = array('categoria <>'=>"");
if($filtro != '*'){
$conditions[] = array("categoria LIKE" => "%".$filtro."%");
}
$this->recursive = -1;
$categorias = $this->find('all', array(
'group' => 'categoria',
'conditions'=> $conditions,
'fields' => array('categoria')
));
return $categorias;
} | php | function listarCategorias($filtro = '*'){
$conditions[] = array('categoria <>'=>"");
if($filtro != '*'){
$conditions[] = array("categoria LIKE" => "%".$filtro."%");
}
$this->recursive = -1;
$categorias = $this->find('all', array(
'group' => 'categoria',
'conditions'=> $conditions,
'fields' => array('categoria')
));
return $categorias;
} | [
"function",
"listarCategorias",
"(",
"$",
"filtro",
"=",
"'*'",
")",
"{",
"$",
"conditions",
"[",
"]",
"=",
"array",
"(",
"'categoria <>'",
"=>",
"\"\"",
")",
";",
"if",
"(",
"$",
"filtro",
"!=",
"'*'",
")",
"{",
"$",
"conditions",
"[",
"]",
"=",
"... | Me lista todas las categorias que existen en la Queries
si se le pasa como parametro un "*" me trae todas
@param string $filtro
@return array $categorias find(all) | [
"Me",
"lista",
"todas",
"las",
"categorias",
"que",
"existen",
"en",
"la",
"Queries",
"si",
"se",
"le",
"pasa",
"como",
"parametro",
"un",
"*",
"me",
"trae",
"todas"
] | train | https://github.com/alevilar/ristorantino-vendor/blob/6b91a1e20cc0ba09a1968d77e3de6512cfa2d966/Stats/Model/Query.php#L17-L33 |
neat-php/database | classes/Result.php | Result.values | public function values($column = 0)
{
if (is_int($column)) {
return $this->statement->fetchAll(PDO::FETCH_COLUMN, $column);
}
return array_map(function ($row) use ($column) {
return $row[$column];
}, $this->rows());
} | php | public function values($column = 0)
{
if (is_int($column)) {
return $this->statement->fetchAll(PDO::FETCH_COLUMN, $column);
}
return array_map(function ($row) use ($column) {
return $row[$column];
}, $this->rows());
} | [
"public",
"function",
"values",
"(",
"$",
"column",
"=",
"0",
")",
"{",
"if",
"(",
"is_int",
"(",
"$",
"column",
")",
")",
"{",
"return",
"$",
"this",
"->",
"statement",
"->",
"fetchAll",
"(",
"PDO",
"::",
"FETCH_COLUMN",
",",
"$",
"column",
")",
"... | Get all values from one column
Moves the cursor to the end of the result
@param int|string $column
@return array | [
"Get",
"all",
"values",
"from",
"one",
"column"
] | train | https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/Result.php#L72-L81 |
neat-php/database | classes/Result.php | Result.value | public function value($column = 0)
{
if (is_int($column)) {
return $this->statement->fetchColumn($column);
}
return $this->row()[$column];
} | php | public function value($column = 0)
{
if (is_int($column)) {
return $this->statement->fetchColumn($column);
}
return $this->row()[$column];
} | [
"public",
"function",
"value",
"(",
"$",
"column",
"=",
"0",
")",
"{",
"if",
"(",
"is_int",
"(",
"$",
"column",
")",
")",
"{",
"return",
"$",
"this",
"->",
"statement",
"->",
"fetchColumn",
"(",
"$",
"column",
")",
";",
"}",
"return",
"$",
"this",
... | Get a single value from one column
Moves the cursor to the next row
@param int|string $column
@return mixed|false Value or false when not found | [
"Get",
"a",
"single",
"value",
"from",
"one",
"column"
] | train | https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/Result.php#L91-L98 |
nguyenanhung/security | src/Encryption.php | Encryption.createKey | public function createKey($length = 16)
{
if (function_exists('random_bytes')) {
try {
return random_bytes((int) $length);
}
catch (\Exception $e) {
return FALSE;
}
} elseif (defined('MCRYPT_DEV_URANDOM')) {
return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
}
$isSecure = NULL;
$key = openssl_random_pseudo_bytes($length, $isSecure);
return ($isSecure === TRUE) ? $key : FALSE;
} | php | public function createKey($length = 16)
{
if (function_exists('random_bytes')) {
try {
return random_bytes((int) $length);
}
catch (\Exception $e) {
return FALSE;
}
} elseif (defined('MCRYPT_DEV_URANDOM')) {
return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
}
$isSecure = NULL;
$key = openssl_random_pseudo_bytes($length, $isSecure);
return ($isSecure === TRUE) ? $key : FALSE;
} | [
"public",
"function",
"createKey",
"(",
"$",
"length",
"=",
"16",
")",
"{",
"if",
"(",
"function_exists",
"(",
"'random_bytes'",
")",
")",
"{",
"try",
"{",
"return",
"random_bytes",
"(",
"(",
"int",
")",
"$",
"length",
")",
";",
"}",
"catch",
"(",
"\... | Function createKey
@author: 713uk13m <dev@nguyenanhung.com>
@time : 2018-12-03 16:20
@param int $length
@return bool|string | [
"Function",
"createKey"
] | train | https://github.com/nguyenanhung/security/blob/a2c9bac66d3c2dad6d668ba6c2bd82ed04bffbd6/src/Encryption.php#L52-L68 |
qlake/framework | src/Qlake/Database/Connection/ConnectionFactory.php | ConnectionFactory.createConnector | public function createConnector()
{
$connectionName = $this->config['default'];
$config = $this->config['connections'][$connectionName];
switch ($config['driver'])
{
case 'mysql':
return new MysqlConnector($config);
case 'pgsql':
return new \Qlake\Database\Connector\PostgresConnector($config);
case 'sqlite':
return new \Qlake\Database\Connector\SQLiteConnector($config);
case 'sqlsrv':
return new \Qlake\Database\Connector\SqlServerConnector($config);
}
} | php | public function createConnector()
{
$connectionName = $this->config['default'];
$config = $this->config['connections'][$connectionName];
switch ($config['driver'])
{
case 'mysql':
return new MysqlConnector($config);
case 'pgsql':
return new \Qlake\Database\Connector\PostgresConnector($config);
case 'sqlite':
return new \Qlake\Database\Connector\SQLiteConnector($config);
case 'sqlsrv':
return new \Qlake\Database\Connector\SqlServerConnector($config);
}
} | [
"public",
"function",
"createConnector",
"(",
")",
"{",
"$",
"connectionName",
"=",
"$",
"this",
"->",
"config",
"[",
"'default'",
"]",
";",
"$",
"config",
"=",
"$",
"this",
"->",
"config",
"[",
"'connections'",
"]",
"[",
"$",
"connectionName",
"]",
";",... | /*public function loadDSN()
{
$connections = $this->config['connections'];
$defaultConnection = $this->config['default'];
switch ($defaultConnection['driver'])
{
case 'mysql':
return new MySqlConnection($connection, $database, $prefix, $config);
case 'pgsql':
return new PostgresConnection($connection, $database, $prefix, $config);
case 'sqlite':
return new SQLiteConnection($connection, $database, $prefix, $config);
case 'sqlsrv':
return new SqlServerConnection($connection, $database, $prefix, $config);
}
} | [
"/",
"*",
"public",
"function",
"loadDSN",
"()",
"{",
"$connections",
"=",
"$this",
"-",
">",
"config",
"[",
"connections",
"]",
";"
] | train | https://github.com/qlake/framework/blob/0b7bad459ae0721bc5cdd141344f9dfc1acee28a/src/Qlake/Database/Connection/ConnectionFactory.php#L62-L82 |
qlake/framework | src/Qlake/Routing/Collection.php | Collection.addRoute | public function addRoute(Route $route)
{
foreach ($route->getMethods() as $method)
{
$this->routes[$method][/*$route->uri*/] = $route;
}
$this->allRoutes[] = $route;
return $this;
} | php | public function addRoute(Route $route)
{
foreach ($route->getMethods() as $method)
{
$this->routes[$method][/*$route->uri*/] = $route;
}
$this->allRoutes[] = $route;
return $this;
} | [
"public",
"function",
"addRoute",
"(",
"Route",
"$",
"route",
")",
"{",
"foreach",
"(",
"$",
"route",
"->",
"getMethods",
"(",
")",
"as",
"$",
"method",
")",
"{",
"$",
"this",
"->",
"routes",
"[",
"$",
"method",
"]",
"[",
"/*$route->uri*/",
"]",
"=",... | Add a Route instans to application routes.
@param Qlake\Routing\Route
@return Qlake\Routing\Route | [
"Add",
"a",
"Route",
"instans",
"to",
"application",
"routes",
"."
] | train | https://github.com/qlake/framework/blob/0b7bad459ae0721bc5cdd141344f9dfc1acee28a/src/Qlake/Routing/Collection.php#L33-L43 |
mridang/magazine | src/Magazine/Magazine.php | Magazine.rglob | protected function rglob($pattern, $excludes = array()) {
$files = array();
foreach (glob($pattern, 0) as $item) {
if (!empty($excludes) && in_array(ltrim($item, '\.\/'), $excludes)) {
$this->trace("Skipping excluded item ./%s", ltrim($item, '\.\/'));
continue;
}
if (is_dir($item)) {
$this->debug("Globbing files in directory %s", $item);
$files = array_merge($files, $this->rglob($item.'/*', $excludes));
} else {
array_push($files, ltrim($item, '\.\/'));
}
}
return $files;
} | php | protected function rglob($pattern, $excludes = array()) {
$files = array();
foreach (glob($pattern, 0) as $item) {
if (!empty($excludes) && in_array(ltrim($item, '\.\/'), $excludes)) {
$this->trace("Skipping excluded item ./%s", ltrim($item, '\.\/'));
continue;
}
if (is_dir($item)) {
$this->debug("Globbing files in directory %s", $item);
$files = array_merge($files, $this->rglob($item.'/*', $excludes));
} else {
array_push($files, ltrim($item, '\.\/'));
}
}
return $files;
} | [
"protected",
"function",
"rglob",
"(",
"$",
"pattern",
",",
"$",
"excludes",
"=",
"array",
"(",
")",
")",
"{",
"$",
"files",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"glob",
"(",
"$",
"pattern",
",",
"0",
")",
"as",
"$",
"item",
")",
"{",
"... | Recursively globs all the files and directories using the given pattern.
If any file or directory exists in the list of excluded items, it is
skipped
@param $pattern string the glob pattern for selecting files and directories
@param array $excludes the array of files and directories to exclude
@return array the array of files and directories matching the glob pattern | [
"Recursively",
"globs",
"all",
"the",
"files",
"and",
"directories",
"using",
"the",
"given",
"pattern",
".",
"If",
"any",
"file",
"or",
"directory",
"exists",
"in",
"the",
"list",
"of",
"excluded",
"items",
"it",
"is",
"skipped"
] | train | https://github.com/mridang/magazine/blob/5b3cfecc472c61fde6af63efe62690a30a267a04/src/Magazine/Magazine.php#L173-L188 |
mridang/magazine | src/Magazine/Magazine.php | Magazine.trace | protected function trace($message, $args = array()) {
if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) {
/** @noinspection HtmlUnknownTag */
$this->output->writeln("<fg=cyan>".sprintf($message, $args));
}
} | php | protected function trace($message, $args = array()) {
if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) {
/** @noinspection HtmlUnknownTag */
$this->output->writeln("<fg=cyan>".sprintf($message, $args));
}
} | [
"protected",
"function",
"trace",
"(",
"$",
"message",
",",
"$",
"args",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"output",
"->",
"getVerbosity",
"(",
")",
">=",
"OutputInterface",
"::",
"VERBOSITY_VERY_VERBOSE",
")",
"{",
"/** @no... | Prints a debug log message to the console with the trace message colour
@param $message string the log message
@param array $args the array of format parameters | [
"Prints",
"a",
"debug",
"log",
"message",
"to",
"the",
"console",
"with",
"the",
"trace",
"message",
"colour"
] | train | https://github.com/mridang/magazine/blob/5b3cfecc472c61fde6af63efe62690a30a267a04/src/Magazine/Magazine.php#L196-L201 |
mridang/magazine | src/Magazine/Magazine.php | Magazine.debug | protected function debug($message, $args = array()) {
if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
/** @noinspection HtmlUnknownTag */
$this->output->writeln('<fg=green>'.sprintf($message, $args));
}
} | php | protected function debug($message, $args = array()) {
if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
/** @noinspection HtmlUnknownTag */
$this->output->writeln('<fg=green>'.sprintf($message, $args));
}
} | [
"protected",
"function",
"debug",
"(",
"$",
"message",
",",
"$",
"args",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"output",
"->",
"getVerbosity",
"(",
")",
">=",
"OutputInterface",
"::",
"VERBOSITY_VERBOSE",
")",
"{",
"/** @noinspe... | Prints a debug log message to the console with the debug message colour
@param $message string the log message
@param array $args the array of format parameters | [
"Prints",
"a",
"debug",
"log",
"message",
"to",
"the",
"console",
"with",
"the",
"debug",
"message",
"colour"
] | train | https://github.com/mridang/magazine/blob/5b3cfecc472c61fde6af63efe62690a30a267a04/src/Magazine/Magazine.php#L209-L214 |
mridang/magazine | src/Magazine/Magazine.php | Magazine.amendDynamicAttributesToJson | private function amendDynamicAttributesToJson(array &$json) {
if (!is_null($this->package_version)) {
$json['version'] = array();
$json['version']['release'] = $this->package_version;
}
if (!is_null($this->package_name)) {
$json['name'] = $this->package_name;
}
} | php | private function amendDynamicAttributesToJson(array &$json) {
if (!is_null($this->package_version)) {
$json['version'] = array();
$json['version']['release'] = $this->package_version;
}
if (!is_null($this->package_name)) {
$json['name'] = $this->package_name;
}
} | [
"private",
"function",
"amendDynamicAttributesToJson",
"(",
"array",
"&",
"$",
"json",
")",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"this",
"->",
"package_version",
")",
")",
"{",
"$",
"json",
"[",
"'version'",
"]",
"=",
"array",
"(",
")",
";",
"$",
... | Adds attributes given from command line to the json
@param array $json array of the json in magazine.json | [
"Adds",
"attributes",
"given",
"from",
"command",
"line",
"to",
"the",
"json"
] | train | https://github.com/mridang/magazine/blob/5b3cfecc472c61fde6af63efe62690a30a267a04/src/Magazine/Magazine.php#L233-L241 |
blast-project/BaseEntitiesBundle | src/DependencyInjection/BlastBaseEntitiesExtension.php | BlastBaseEntitiesExtension.loadListeners | public function loadListeners(ContainerBuilder $container, array $config)
{
$availableListeners = [
'naming',
'guidable',
'timestampable',
'addressable',
'treeable',
'nested_treeable',
'nameable',
'labelable',
'emailable',
'descriptible',
'searchable',
'loggable',
'sortable',
'normalize',
'syliusGuidable',
];
$useLoggable = false;
foreach ($availableListeners as $listenerName) {
$serviceId = 'blast_base_entities.listener.' . $listenerName;
// enable doctrine ORM event subscribers
foreach ($config['orm'] as $connection => $listeners) {
if (!empty($listeners[$listenerName]) && $container->hasDefinition($serviceId)) {
$definition = $container->getDefinition($serviceId);
$definition->addTag('doctrine.event_subscriber', ['connection' => $connection]);
if ($listenerName == 'loggable') {
$useLoggable = true;
}
}
$this->entityManagers[$connection] = $listeners;
}
// enable doctrine ODM event subscribers
// TODO : not tested
foreach ($config['odm'] as $connection => $listeners) {
if (!empty($listeners['$listenerName']) && $container->hasDefinition($serviceId)) {
$definition = $container->getDefinition($serviceId);
$definition->addTag('doctrine_mongodb.odm.event_subscriber', ['connection' => $connection]);
if ($listenerName == 'loggable') {
$useLoggable = true;
}
}
$this->documentManagers[$connection] = $listeners;
}
}
if ($useLoggable) {
$container->getDefinition('blast_base_entities.listener.logger')
->setPublic(true)
->addTag('kernel.event_subscriber');
}
if (array_key_exists('entity_search_indexes', $config)) {
$mergedConfig = $config['entity_search_indexes'];
if ($container->hasParameter('blast_base_entities.entity_search_indexes')) {
$mergedConfig = array_merge($container->getParameter('blast_base_entities.entity_search_indexes') ?: [], $mergedConfig);
}
$container->setParameter('blast_base_entities.entity_search_indexes', $mergedConfig);
}
return $this;
} | php | public function loadListeners(ContainerBuilder $container, array $config)
{
$availableListeners = [
'naming',
'guidable',
'timestampable',
'addressable',
'treeable',
'nested_treeable',
'nameable',
'labelable',
'emailable',
'descriptible',
'searchable',
'loggable',
'sortable',
'normalize',
'syliusGuidable',
];
$useLoggable = false;
foreach ($availableListeners as $listenerName) {
$serviceId = 'blast_base_entities.listener.' . $listenerName;
// enable doctrine ORM event subscribers
foreach ($config['orm'] as $connection => $listeners) {
if (!empty($listeners[$listenerName]) && $container->hasDefinition($serviceId)) {
$definition = $container->getDefinition($serviceId);
$definition->addTag('doctrine.event_subscriber', ['connection' => $connection]);
if ($listenerName == 'loggable') {
$useLoggable = true;
}
}
$this->entityManagers[$connection] = $listeners;
}
// enable doctrine ODM event subscribers
// TODO : not tested
foreach ($config['odm'] as $connection => $listeners) {
if (!empty($listeners['$listenerName']) && $container->hasDefinition($serviceId)) {
$definition = $container->getDefinition($serviceId);
$definition->addTag('doctrine_mongodb.odm.event_subscriber', ['connection' => $connection]);
if ($listenerName == 'loggable') {
$useLoggable = true;
}
}
$this->documentManagers[$connection] = $listeners;
}
}
if ($useLoggable) {
$container->getDefinition('blast_base_entities.listener.logger')
->setPublic(true)
->addTag('kernel.event_subscriber');
}
if (array_key_exists('entity_search_indexes', $config)) {
$mergedConfig = $config['entity_search_indexes'];
if ($container->hasParameter('blast_base_entities.entity_search_indexes')) {
$mergedConfig = array_merge($container->getParameter('blast_base_entities.entity_search_indexes') ?: [], $mergedConfig);
}
$container->setParameter('blast_base_entities.entity_search_indexes', $mergedConfig);
}
return $this;
} | [
"public",
"function",
"loadListeners",
"(",
"ContainerBuilder",
"$",
"container",
",",
"array",
"$",
"config",
")",
"{",
"$",
"availableListeners",
"=",
"[",
"'naming'",
",",
"'guidable'",
",",
"'timestampable'",
",",
"'addressable'",
",",
"'treeable'",
",",
"'n... | {@inheritdoc} | [
"{"
] | train | https://github.com/blast-project/BaseEntitiesBundle/blob/abd06891fc38922225ab7e4fcb437a286ba2c0c4/src/DependencyInjection/BlastBaseEntitiesExtension.php#L26-L93 |
antaresproject/notifications | src/Console/NotificationSeveritiesCommand.php | NotificationSeveritiesCommand.fire | public function fire()
{
$severities = NotificationSeverity::orderBy('id', 'asc')->get();
$flatten = [];
foreach ($severities as $severity) {
$flatten[] = ['<info>' . $severity->id . '</info>', '<fg=red>' . $severity->name . '</fg=red>'];
}
if (count($flatten) > 0) {
$this->table(['Id', 'Name'], $flatten);
} else {
$this->error('No severities found');
}
} | php | public function fire()
{
$severities = NotificationSeverity::orderBy('id', 'asc')->get();
$flatten = [];
foreach ($severities as $severity) {
$flatten[] = ['<info>' . $severity->id . '</info>', '<fg=red>' . $severity->name . '</fg=red>'];
}
if (count($flatten) > 0) {
$this->table(['Id', 'Name'], $flatten);
} else {
$this->error('No severities found');
}
} | [
"public",
"function",
"fire",
"(",
")",
"{",
"$",
"severities",
"=",
"NotificationSeverity",
"::",
"orderBy",
"(",
"'id'",
",",
"'asc'",
")",
"->",
"get",
"(",
")",
";",
"$",
"flatten",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"severities",
"as",
"$"... | Execute the console command.
@return void | [
"Execute",
"the",
"console",
"command",
"."
] | train | https://github.com/antaresproject/notifications/blob/60de743477b7e9cbb51de66da5fd9461adc9dd8a/src/Console/NotificationSeveritiesCommand.php#L49-L62 |
expectation-php/expect | src/configurator/DefaultConfigurator.php | DefaultConfigurator.configure | public function configure()
{
$registry = new DefaultMatcherRegistry();
$packageRegistrar = new DefaultPackageRegistrar();
$packageRegistrar->registerTo($registry);
$dictionary = $registry->toDictionary();
$matcherFactory = new DefaultMatcherFactory($dictionary);
return new DefaultContextFactory($matcherFactory, new ExceptionReporter());
} | php | public function configure()
{
$registry = new DefaultMatcherRegistry();
$packageRegistrar = new DefaultPackageRegistrar();
$packageRegistrar->registerTo($registry);
$dictionary = $registry->toDictionary();
$matcherFactory = new DefaultMatcherFactory($dictionary);
return new DefaultContextFactory($matcherFactory, new ExceptionReporter());
} | [
"public",
"function",
"configure",
"(",
")",
"{",
"$",
"registry",
"=",
"new",
"DefaultMatcherRegistry",
"(",
")",
";",
"$",
"packageRegistrar",
"=",
"new",
"DefaultPackageRegistrar",
"(",
")",
";",
"$",
"packageRegistrar",
"->",
"registerTo",
"(",
"$",
"regis... | {@inheritdoc} | [
"{"
] | train | https://github.com/expectation-php/expect/blob/1a32c5af37f3dc8dabe4e8eedeeb21aea16ce139/src/configurator/DefaultConfigurator.php#L33-L44 |
Eresus/EresusCMS | src/core/framework/core/WWW/HTTP/HTTP.php | HTTP.buildURL | public static function buildURL($url, $parts = array(), $flags = self::URL_REPLACE,
&$new_url = false)
{
$keys = array('user','pass','port','path','query','fragment');
/* HTTP::URL_STRIP_ALL becomes all the HTTP::URL_STRIP_Xs */
if ($flags & self::URL_STRIP_ALL)
{
$flags |= self::URL_STRIP_USER;
$flags |= self::URL_STRIP_PASS;
$flags |= self::URL_STRIP_PORT;
$flags |= self::URL_STRIP_PATH;
$flags |= self::URL_STRIP_QUERY;
$flags |= self::URL_STRIP_FRAGMENT;
}
/* HTTP::URL_STRIP_AUTH becomes HTTP::URL_STRIP_USER and HTTP::URL_STRIP_PASS */
else if ($flags & self::URL_STRIP_AUTH)
{
$flags |= self::URL_STRIP_USER;
$flags |= self::URL_STRIP_PASS;
}
// Parse the original URL
$parse_url = parse_url($url);
// Scheme and Host are always replaced
if (isset($parts['scheme']))
$parse_url['scheme'] = $parts['scheme'];
if (isset($parts['host']))
$parse_url['host'] = $parts['host'];
// (If applicable) Replace the original URL with it's new parts
if ($flags & self::URL_REPLACE)
{
foreach ($keys as $key)
{
if (isset($parts[$key]))
$parse_url[$key] = $parts[$key];
}
}
else
{
// Join the original URL path with the new path
if (isset($parts['path']) && ($flags & self::URL_JOIN_PATH))
{
if (isset($parse_url['path']))
$parse_url['path'] = rtrim(str_replace(basename($parse_url['path']), '',
$parse_url['path']), '/') . '/' . ltrim($parts['path'], '/');
else
$parse_url['path'] = $parts['path'];
}
// Join the original query string with the new query string
if (isset($parts['query']) && ($flags & self::URL_JOIN_QUERY))
{
if (isset($parse_url['query']))
$parse_url['query'] .= '&' . $parts['query'];
else
$parse_url['query'] = $parts['query'];
}
}
// Strips all the applicable sections of the URL
// Note: Scheme and Host are never stripped
foreach ($keys as $key)
{
if ($flags & (int)constant('HTTP::URL_STRIP_' . strtoupper($key)))
unset($parse_url[$key]);
}
$new_url = $parse_url;
return
((isset($parse_url['scheme'])) ? $parse_url['scheme'] . '://' : '')
.((isset($parse_url['user'])) ? $parse_url['user'] . ((isset($parse_url['pass'])) ? ':' .
$parse_url['pass'] : '') .'@' : '')
.((isset($parse_url['host'])) ? $parse_url['host'] : '')
.((isset($parse_url['port'])) ? ':' . $parse_url['port'] : '')
.((isset($parse_url['path'])) ? $parse_url['path'] : '')
.((isset($parse_url['query'])) ? '?' . $parse_url['query'] : '')
.((isset($parse_url['fragment'])) ? '#' . $parse_url['fragment'] : '')
;
} | php | public static function buildURL($url, $parts = array(), $flags = self::URL_REPLACE,
&$new_url = false)
{
$keys = array('user','pass','port','path','query','fragment');
/* HTTP::URL_STRIP_ALL becomes all the HTTP::URL_STRIP_Xs */
if ($flags & self::URL_STRIP_ALL)
{
$flags |= self::URL_STRIP_USER;
$flags |= self::URL_STRIP_PASS;
$flags |= self::URL_STRIP_PORT;
$flags |= self::URL_STRIP_PATH;
$flags |= self::URL_STRIP_QUERY;
$flags |= self::URL_STRIP_FRAGMENT;
}
/* HTTP::URL_STRIP_AUTH becomes HTTP::URL_STRIP_USER and HTTP::URL_STRIP_PASS */
else if ($flags & self::URL_STRIP_AUTH)
{
$flags |= self::URL_STRIP_USER;
$flags |= self::URL_STRIP_PASS;
}
// Parse the original URL
$parse_url = parse_url($url);
// Scheme and Host are always replaced
if (isset($parts['scheme']))
$parse_url['scheme'] = $parts['scheme'];
if (isset($parts['host']))
$parse_url['host'] = $parts['host'];
// (If applicable) Replace the original URL with it's new parts
if ($flags & self::URL_REPLACE)
{
foreach ($keys as $key)
{
if (isset($parts[$key]))
$parse_url[$key] = $parts[$key];
}
}
else
{
// Join the original URL path with the new path
if (isset($parts['path']) && ($flags & self::URL_JOIN_PATH))
{
if (isset($parse_url['path']))
$parse_url['path'] = rtrim(str_replace(basename($parse_url['path']), '',
$parse_url['path']), '/') . '/' . ltrim($parts['path'], '/');
else
$parse_url['path'] = $parts['path'];
}
// Join the original query string with the new query string
if (isset($parts['query']) && ($flags & self::URL_JOIN_QUERY))
{
if (isset($parse_url['query']))
$parse_url['query'] .= '&' . $parts['query'];
else
$parse_url['query'] = $parts['query'];
}
}
// Strips all the applicable sections of the URL
// Note: Scheme and Host are never stripped
foreach ($keys as $key)
{
if ($flags & (int)constant('HTTP::URL_STRIP_' . strtoupper($key)))
unset($parse_url[$key]);
}
$new_url = $parse_url;
return
((isset($parse_url['scheme'])) ? $parse_url['scheme'] . '://' : '')
.((isset($parse_url['user'])) ? $parse_url['user'] . ((isset($parse_url['pass'])) ? ':' .
$parse_url['pass'] : '') .'@' : '')
.((isset($parse_url['host'])) ? $parse_url['host'] : '')
.((isset($parse_url['port'])) ? ':' . $parse_url['port'] : '')
.((isset($parse_url['path'])) ? $parse_url['path'] : '')
.((isset($parse_url['query'])) ? '?' . $parse_url['query'] : '')
.((isset($parse_url['fragment'])) ? '#' . $parse_url['fragment'] : '')
;
} | [
"public",
"static",
"function",
"buildURL",
"(",
"$",
"url",
",",
"$",
"parts",
"=",
"array",
"(",
")",
",",
"$",
"flags",
"=",
"self",
"::",
"URL_REPLACE",
",",
"&",
"$",
"new_url",
"=",
"false",
")",
"{",
"$",
"keys",
"=",
"array",
"(",
"'user'",... | Build an URL
The parts of the second URL will be merged into the first according to the flags argument.
@param mixed $url (Part(s) of) an URL in form of a string or associative array like
parse_url() returns
@param mixed $parts Same as the first argument
@param int $flags A bitmask of binary or'ed HTTP_URL constants (Optional)HTTP_URL_REPLACE
is the default
@param array $new_url If set, it will be filled with the parts of the composed url like
parse_url() would return
@author tycoonmaster(at)gmail(dot)com
@author Mikhail Krasilnikov <mk@procreat.ru>
@todo Wiki docs | [
"Build",
"an",
"URL"
] | train | https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/WWW/HTTP/HTTP.php#L150-L233 |
Eresus/EresusCMS | src/core/framework/core/WWW/HTTP/HTTP.php | HTTP.redirect | public static function redirect($uri, $permanent = false)
{
Eresus_Kernel::log(__METHOD__, LOG_DEBUG, $uri);
$header = 'Location: '.$uri;
if ($permanent)
{
header($header, true, 301);
}
else
{
header($header);
}
exit;
} | php | public static function redirect($uri, $permanent = false)
{
Eresus_Kernel::log(__METHOD__, LOG_DEBUG, $uri);
$header = 'Location: '.$uri;
if ($permanent)
{
header($header, true, 301);
}
else
{
header($header);
}
exit;
} | [
"public",
"static",
"function",
"redirect",
"(",
"$",
"uri",
",",
"$",
"permanent",
"=",
"false",
")",
"{",
"Eresus_Kernel",
"::",
"log",
"(",
"__METHOD__",
",",
"LOG_DEBUG",
",",
"$",
"uri",
")",
";",
"$",
"header",
"=",
"'Location: '",
".",
"$",
"uri... | Направляет браузер на новый адрес и прекращает выполнение программы
@param string $uri новый адрес
@param bool $permanent отправлять заголовок '301 Moved permanently' | [
"Направляет",
"браузер",
"на",
"новый",
"адрес",
"и",
"прекращает",
"выполнение",
"программы"
] | train | https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/WWW/HTTP/HTTP.php#L257-L273 |
ekuiter/feature-php | FeaturePhp/Model/Configuration.php | Configuration.getValue | public function getValue($feature) {
// side effect: checks for instanceof ValueFeature
$defaultValue = $feature->getDefaultValue();
$values = $this->xmlConfiguration->getValues();
if (array_key_exists($feature->getName(), $values))
return $values[$feature->getName()];
else
return $defaultValue;
} | php | public function getValue($feature) {
// side effect: checks for instanceof ValueFeature
$defaultValue = $feature->getDefaultValue();
$values = $this->xmlConfiguration->getValues();
if (array_key_exists($feature->getName(), $values))
return $values[$feature->getName()];
else
return $defaultValue;
} | [
"public",
"function",
"getValue",
"(",
"$",
"feature",
")",
"{",
"// side effect: checks for instanceof ValueFeature",
"$",
"defaultValue",
"=",
"$",
"feature",
"->",
"getDefaultValue",
"(",
")",
";",
"$",
"values",
"=",
"$",
"this",
"->",
"xmlConfiguration",
"->"... | Returns the configuration's value for a value feature.
@param ValueFeature $feature
@return string | [
"Returns",
"the",
"configuration",
"s",
"value",
"for",
"a",
"value",
"feature",
"."
] | train | https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Model/Configuration.php#L96-L104 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.