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 |
|---|---|---|---|---|---|---|---|---|---|---|
philiplb/Valdi | src/Valdi/Validator/OrCombine.php | OrCombine.isValid | public function isValid($value, array $parameters) {
$this->checkParameters($parameters);
$validator = array_shift($parameters);
$this->invalidDetails = [];
$valid = false;
foreach ($parameters as $rules) {
$failedValidations = $validator->isValidValue([$rules], $value);
foreach ($failedValidations as $failedValidation) {
$this->invalidDetails[] = $failedValidation;
}
$valid = $valid || empty($failedValidations);
}
return $valid;
} | php | public function isValid($value, array $parameters) {
$this->checkParameters($parameters);
$validator = array_shift($parameters);
$this->invalidDetails = [];
$valid = false;
foreach ($parameters as $rules) {
$failedValidations = $validator->isValidValue([$rules], $value);
foreach ($failedValidations as $failedValidation) {
$this->invalidDetails[] = $failedValidation;
}
$valid = $valid || empty($failedValidations);
}
return $valid;
} | [
"public",
"function",
"isValid",
"(",
"$",
"value",
",",
"array",
"$",
"parameters",
")",
"{",
"$",
"this",
"->",
"checkParameters",
"(",
"$",
"parameters",
")",
";",
"$",
"validator",
"=",
"array_shift",
"(",
"$",
"parameters",
")",
";",
"$",
"this",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/philiplb/Valdi/blob/9927ec34a2cb00cec705e952d3c2374e2dc3c972/src/Valdi/Validator/OrCombine.php#L50-L66 |
netvlies/NetvliesFormBundle | EventListener/SuccessListener.php | SuccessListener.onFormSuccess | public function onFormSuccess(FormEvent $event)
{
$form = $event->getForm();
$result = $this->createResult($form);
if ($form->getStoreResults()) {
$this->storeResult($form, $result);
}
if ($form->getSendMail()) {
$this->sendMail($form, $result);
}
$successUrl = $form->getSuccessUrl();
if ($successUrl != null) {
$redirectResponse = new RedirectResponse($successUrl);
$redirectResponse->send();
}
} | php | public function onFormSuccess(FormEvent $event)
{
$form = $event->getForm();
$result = $this->createResult($form);
if ($form->getStoreResults()) {
$this->storeResult($form, $result);
}
if ($form->getSendMail()) {
$this->sendMail($form, $result);
}
$successUrl = $form->getSuccessUrl();
if ($successUrl != null) {
$redirectResponse = new RedirectResponse($successUrl);
$redirectResponse->send();
}
} | [
"public",
"function",
"onFormSuccess",
"(",
"FormEvent",
"$",
"event",
")",
"{",
"$",
"form",
"=",
"$",
"event",
"->",
"getForm",
"(",
")",
";",
"$",
"result",
"=",
"$",
"this",
"->",
"createResult",
"(",
"$",
"form",
")",
";",
"if",
"(",
"$",
"for... | Default handling for the form success event. This includes storage of
the result, sending a confirmation mail and redirecting to the success
URL, while respecting the form settings.
@param FormEvent $event | [
"Default",
"handling",
"for",
"the",
"form",
"success",
"event",
".",
"This",
"includes",
"storage",
"of",
"the",
"result",
"sending",
"a",
"confirmation",
"mail",
"and",
"redirecting",
"to",
"the",
"success",
"URL",
"while",
"respecting",
"the",
"form",
"sett... | train | https://github.com/netvlies/NetvliesFormBundle/blob/93f9a3321d9925040111374e7c1014a6400a2d08/EventListener/SuccessListener.php#L30-L50 |
netvlies/NetvliesFormBundle | EventListener/SuccessListener.php | SuccessListener.createResult | public function createResult(Form $form)
{
$result = new Result();
$result->setDatetimeAdded(new \DateTime());
$viewData = $form->getSf2Form()->getViewData();
foreach ($form->getFields() as $field) {
$entry = new Entry();
$entry->setField($field);
$entry->setValue($viewData['field_'.$field->getId()]);
$result->addEntry($entry);
}
return $result;
} | php | public function createResult(Form $form)
{
$result = new Result();
$result->setDatetimeAdded(new \DateTime());
$viewData = $form->getSf2Form()->getViewData();
foreach ($form->getFields() as $field) {
$entry = new Entry();
$entry->setField($field);
$entry->setValue($viewData['field_'.$field->getId()]);
$result->addEntry($entry);
}
return $result;
} | [
"public",
"function",
"createResult",
"(",
"Form",
"$",
"form",
")",
"{",
"$",
"result",
"=",
"new",
"Result",
"(",
")",
";",
"$",
"result",
"->",
"setDatetimeAdded",
"(",
"new",
"\\",
"DateTime",
"(",
")",
")",
";",
"$",
"viewData",
"=",
"$",
"form"... | Creates the result object from the user's input.
@param $form
@return Result | [
"Creates",
"the",
"result",
"object",
"from",
"the",
"user",
"s",
"input",
"."
] | train | https://github.com/netvlies/NetvliesFormBundle/blob/93f9a3321d9925040111374e7c1014a6400a2d08/EventListener/SuccessListener.php#L59-L74 |
netvlies/NetvliesFormBundle | EventListener/SuccessListener.php | SuccessListener.storeResult | public function storeResult(Form $form, Result $result)
{
$entityManager = $this->container->get('doctrine')->getManager();
$form->addResult($result);
$entityManager->persist($form);
$entityManager->flush();
} | php | public function storeResult(Form $form, Result $result)
{
$entityManager = $this->container->get('doctrine')->getManager();
$form->addResult($result);
$entityManager->persist($form);
$entityManager->flush();
} | [
"public",
"function",
"storeResult",
"(",
"Form",
"$",
"form",
",",
"Result",
"$",
"result",
")",
"{",
"$",
"entityManager",
"=",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'doctrine'",
")",
"->",
"getManager",
"(",
")",
";",
"$",
"form",
"->",... | Stores the user input as a result object.
@param $form
@param $result | [
"Stores",
"the",
"user",
"input",
"as",
"a",
"result",
"object",
"."
] | train | https://github.com/netvlies/NetvliesFormBundle/blob/93f9a3321d9925040111374e7c1014a6400a2d08/EventListener/SuccessListener.php#L82-L88 |
netvlies/NetvliesFormBundle | EventListener/SuccessListener.php | SuccessListener.sendMail | public function sendMail(Form $form, Result $result)
{
$message = \Swift_Message::newInstance()
->setSubject($form->getMailSubject())
->setTo(array($form->getMailRecipientEmail() => $form->getMailRecipientName()))
->setBody($this->container->get('templating')->render('NetvliesFormBundle:Mail:result.html.twig', array(
'content' => $form->getMailBody(),
'entries' => $result->getEntries(),
)), 'text/html');
if ($form->getMailSenderName() != null && $form->getMailSenderEmail() != null) {
$message->setFrom(array($form->getMailSenderEmail() => $form->getMailSenderName()));
}
$this->container->get('mailer')->send($message);
$transport = $this->container->get('mailer')->getTransport();
if (!$transport instanceof \Swift_Transport_SpoolTransport) {
return;
}
$spool = $transport->getSpool();
if (!$spool instanceof \Swift_MemorySpool) {
return;
}
$spool->flushQueue($this->container->get('swiftmailer.transport.real'));
} | php | public function sendMail(Form $form, Result $result)
{
$message = \Swift_Message::newInstance()
->setSubject($form->getMailSubject())
->setTo(array($form->getMailRecipientEmail() => $form->getMailRecipientName()))
->setBody($this->container->get('templating')->render('NetvliesFormBundle:Mail:result.html.twig', array(
'content' => $form->getMailBody(),
'entries' => $result->getEntries(),
)), 'text/html');
if ($form->getMailSenderName() != null && $form->getMailSenderEmail() != null) {
$message->setFrom(array($form->getMailSenderEmail() => $form->getMailSenderName()));
}
$this->container->get('mailer')->send($message);
$transport = $this->container->get('mailer')->getTransport();
if (!$transport instanceof \Swift_Transport_SpoolTransport) {
return;
}
$spool = $transport->getSpool();
if (!$spool instanceof \Swift_MemorySpool) {
return;
}
$spool->flushQueue($this->container->get('swiftmailer.transport.real'));
} | [
"public",
"function",
"sendMail",
"(",
"Form",
"$",
"form",
",",
"Result",
"$",
"result",
")",
"{",
"$",
"message",
"=",
"\\",
"Swift_Message",
"::",
"newInstance",
"(",
")",
"->",
"setSubject",
"(",
"$",
"form",
"->",
"getMailSubject",
"(",
")",
")",
... | Sends a mail containing the form values to the contact e-mail address
specified.
@param Form $form
@param Result $result | [
"Sends",
"a",
"mail",
"containing",
"the",
"form",
"values",
"to",
"the",
"contact",
"e",
"-",
"mail",
"address",
"specified",
"."
] | train | https://github.com/netvlies/NetvliesFormBundle/blob/93f9a3321d9925040111374e7c1014a6400a2d08/EventListener/SuccessListener.php#L97-L124 |
InactiveProjects/limoncello-illuminate | app/Database/Migrations/MigrateUsers.php | MigrateUsers.apply | public function apply()
{
Schema::create(Model::TABLE_NAME, function (Blueprint $table) {
$table->increments(Model::FIELD_ID);
$table->unsignedInteger(Model::FIELD_ID_ROLE);
/** @noinspection PhpUndefinedMethodInspection */
$table->string(Model::FIELD_TITLE, Model::LENGTH_TITLE)->nullable();
$table->string(Model::FIELD_FIRST_NAME, Model::LENGTH_FIRST_NAME);
/** @noinspection PhpUndefinedMethodInspection */
$table->string(Model::FIELD_LAST_NAME, Model::LENGTH_LAST_NAME)->nullable();
/** @noinspection PhpUndefinedMethodInspection */
$table->string(Model::FIELD_EMAIL, Model::LENGTH_EMAIL)->unique();
/** @noinspection PhpUndefinedMethodInspection */
$table->string(Model::FIELD_LANGUAGE, Model::LENGTH_LANGUAGE)->nullable();
$table->string(Model::FIELD_PASSWORD_HASH, Model::LENGTH_PASSWORD_HASH);
/** @noinspection PhpUndefinedMethodInspection */
$table->string(Model::FIELD_API_TOKEN, Model::LENGTH_API_TOKEN)->nullable();
$table->rememberToken();
$table->softDeletes();
$table->timestamps();
/** @noinspection PhpUndefinedMethodInspection */
$table->foreign(Model::FIELD_ID_ROLE)->references(Role::FIELD_ID)->on(Role::TABLE_NAME);
});
} | php | public function apply()
{
Schema::create(Model::TABLE_NAME, function (Blueprint $table) {
$table->increments(Model::FIELD_ID);
$table->unsignedInteger(Model::FIELD_ID_ROLE);
/** @noinspection PhpUndefinedMethodInspection */
$table->string(Model::FIELD_TITLE, Model::LENGTH_TITLE)->nullable();
$table->string(Model::FIELD_FIRST_NAME, Model::LENGTH_FIRST_NAME);
/** @noinspection PhpUndefinedMethodInspection */
$table->string(Model::FIELD_LAST_NAME, Model::LENGTH_LAST_NAME)->nullable();
/** @noinspection PhpUndefinedMethodInspection */
$table->string(Model::FIELD_EMAIL, Model::LENGTH_EMAIL)->unique();
/** @noinspection PhpUndefinedMethodInspection */
$table->string(Model::FIELD_LANGUAGE, Model::LENGTH_LANGUAGE)->nullable();
$table->string(Model::FIELD_PASSWORD_HASH, Model::LENGTH_PASSWORD_HASH);
/** @noinspection PhpUndefinedMethodInspection */
$table->string(Model::FIELD_API_TOKEN, Model::LENGTH_API_TOKEN)->nullable();
$table->rememberToken();
$table->softDeletes();
$table->timestamps();
/** @noinspection PhpUndefinedMethodInspection */
$table->foreign(Model::FIELD_ID_ROLE)->references(Role::FIELD_ID)->on(Role::TABLE_NAME);
});
} | [
"public",
"function",
"apply",
"(",
")",
"{",
"Schema",
"::",
"create",
"(",
"Model",
"::",
"TABLE_NAME",
",",
"function",
"(",
"Blueprint",
"$",
"table",
")",
"{",
"$",
"table",
"->",
"increments",
"(",
"Model",
"::",
"FIELD_ID",
")",
";",
"$",
"table... | @inheritdoc
@SuppressWarnings(PHPMD.StaticAccess) | [
"@inheritdoc"
] | train | https://github.com/InactiveProjects/limoncello-illuminate/blob/cae6fc26190efcf090495a5c3582c10fa2430897/app/Database/Migrations/MigrateUsers.php#L17-L41 |
SporkCode/Spork | src/Log/ServiceFactory.php | ServiceFactory.createService | public function createService(ServiceLocatorInterface $serviceLocator)
{
$appConfig = $serviceLocator->get('config');
$config = array_key_exists('log', $appConfig) ? $appConfig['log'] : array();
$class = array_key_exists('class', $config) ? $config['class'] : 'Zend\Log\Logger';
$logger = new $class($config);
return $logger;
} | php | public function createService(ServiceLocatorInterface $serviceLocator)
{
$appConfig = $serviceLocator->get('config');
$config = array_key_exists('log', $appConfig) ? $appConfig['log'] : array();
$class = array_key_exists('class', $config) ? $config['class'] : 'Zend\Log\Logger';
$logger = new $class($config);
return $logger;
} | [
"public",
"function",
"createService",
"(",
"ServiceLocatorInterface",
"$",
"serviceLocator",
")",
"{",
"$",
"appConfig",
"=",
"$",
"serviceLocator",
"->",
"get",
"(",
"'config'",
")",
";",
"$",
"config",
"=",
"array_key_exists",
"(",
"'log'",
",",
"$",
"appCo... | Creates a Logger service
@see \Zend\ServiceManager\FactoryInterface::createService()
@param \Zend\ServiceManager\ServiceLocatorInterface $serviceLocator
@return \Zend\Log\LoggerInterface | [
"Creates",
"a",
"Logger",
"service"
] | train | https://github.com/SporkCode/Spork/blob/7f569efdc0ceb4a9c1c7a8b648b6a7ed50d2088a/src/Log/ServiceFactory.php#L34-L41 |
heidelpay/PhpDoc | src/phpDocumentor/Plugin/Scrybe/Converter/Metadata/TableOfContents/BaseEntry.php | BaseEntry.setParent | public function setParent($parent)
{
if ($parent !== null && !$parent instanceof BaseEntry) {
throw new \InvalidArgumentException('An entry may only have another entry as parent');
}
$this->parent = $parent;
} | php | public function setParent($parent)
{
if ($parent !== null && !$parent instanceof BaseEntry) {
throw new \InvalidArgumentException('An entry may only have another entry as parent');
}
$this->parent = $parent;
} | [
"public",
"function",
"setParent",
"(",
"$",
"parent",
")",
"{",
"if",
"(",
"$",
"parent",
"!==",
"null",
"&&",
"!",
"$",
"parent",
"instanceof",
"BaseEntry",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'An entry may only have another entry... | Sets the parent entry for this entry.
@param BaseEntry|null $parent
@throws \InvalidArgumentException if the given parameter is of an incorrect type.
@return void | [
"Sets",
"the",
"parent",
"entry",
"for",
"this",
"entry",
"."
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Scrybe/Converter/Metadata/TableOfContents/BaseEntry.php#L79-L86 |
Laralum/Events | src/Controllers/PublicEventController.php | PublicEventController.index | public function index()
{
$this->authorize('publicView', Event::class);
return view('laralum_events::public.index', ['events' => Event::where('public', true)->orderBy('id', 'desc')->get()]);
} | php | public function index()
{
$this->authorize('publicView', Event::class);
return view('laralum_events::public.index', ['events' => Event::where('public', true)->orderBy('id', 'desc')->get()]);
} | [
"public",
"function",
"index",
"(",
")",
"{",
"$",
"this",
"->",
"authorize",
"(",
"'publicView'",
",",
"Event",
"::",
"class",
")",
";",
"return",
"view",
"(",
"'laralum_events::public.index'",
",",
"[",
"'events'",
"=>",
"Event",
"::",
"where",
"(",
"'pu... | Display a listing of the resource.
@return \Illuminate\Http\Response | [
"Display",
"a",
"listing",
"of",
"the",
"resource",
"."
] | train | https://github.com/Laralum/Events/blob/9dc36468f4253e7d040863a115ea94cded0e6aa5/src/Controllers/PublicEventController.php#L22-L27 |
Laralum/Events | src/Controllers/PublicEventController.php | PublicEventController.show | public function show(Event $event)
{
$this->authorize('publicView', $event);
abort_if(!$event->public, 404);
return view('laralum_events::public.show', [
'event' => $event,
'users' => $event->users()->paginate(50),
]);
} | php | public function show(Event $event)
{
$this->authorize('publicView', $event);
abort_if(!$event->public, 404);
return view('laralum_events::public.show', [
'event' => $event,
'users' => $event->users()->paginate(50),
]);
} | [
"public",
"function",
"show",
"(",
"Event",
"$",
"event",
")",
"{",
"$",
"this",
"->",
"authorize",
"(",
"'publicView'",
",",
"$",
"event",
")",
";",
"abort_if",
"(",
"!",
"$",
"event",
"->",
"public",
",",
"404",
")",
";",
"return",
"view",
"(",
"... | Display the specified resource.
@param \Laralum\Events\Models\Event $event
@return \Illuminate\Http\Response | [
"Display",
"the",
"specified",
"resource",
"."
] | train | https://github.com/Laralum/Events/blob/9dc36468f4253e7d040863a115ea94cded0e6aa5/src/Controllers/PublicEventController.php#L126-L136 |
opsbears/piccolo | src/Module/ModuleLoader.php | ModuleLoader.loadModules | public function loadModules(DependencyInjectionContainer $dic, array &$config) {
$moduleList = (isset($config['modules']) ? $config['modules'] : []);
/**
* @var Module[] $modules
*/
$modules = [];
foreach ($moduleList as $moduleClass) {
$this->loadModule($moduleClass, $modules, $moduleList, $dic);
}
$this->processModules($dic, $modules, $config);
} | php | public function loadModules(DependencyInjectionContainer $dic, array &$config) {
$moduleList = (isset($config['modules']) ? $config['modules'] : []);
/**
* @var Module[] $modules
*/
$modules = [];
foreach ($moduleList as $moduleClass) {
$this->loadModule($moduleClass, $modules, $moduleList, $dic);
}
$this->processModules($dic, $modules, $config);
} | [
"public",
"function",
"loadModules",
"(",
"DependencyInjectionContainer",
"$",
"dic",
",",
"array",
"&",
"$",
"config",
")",
"{",
"$",
"moduleList",
"=",
"(",
"isset",
"(",
"$",
"config",
"[",
"'modules'",
"]",
")",
"?",
"$",
"config",
"[",
"'modules'",
... | Load all configured modules from the 'modules' configuration key. It calls the modules in this order:
1. query the required modules and load them if needed.
2. call loadConfiguration to load the configuration
3. call configureDependencyInjection to set up the dependency injection container.
@param DependencyInjectionContainer $dic
@param array $config
@return void | [
"Load",
"all",
"configured",
"modules",
"from",
"the",
"modules",
"configuration",
"key",
".",
"It",
"calls",
"the",
"modules",
"in",
"this",
"order",
":"
] | train | https://github.com/opsbears/piccolo/blob/ebba9f892ed35965140265ba1c61b2c645eab6e0/src/Module/ModuleLoader.php#L27-L40 |
opsbears/piccolo | src/Module/ModuleLoader.php | ModuleLoader.processModules | private function processModules(DependencyInjectionContainer $dic, array $modules, array &$config) {
/** @noinspection PhpInternalEntityUsedInspection */
$dependencyGraph = new ModuleDependencyGraph();
$dependencyGraph->addModules($modules);
$modules = $dependencyGraph->getSortedModuleList();
foreach ($modules as $module) {
$this->loadModuleConfiguration($module, $config);
}
foreach ($modules as $module) {
$module->configureDependencyInjection($dic, $config[$module->getModuleKey()], $config);
}
} | php | private function processModules(DependencyInjectionContainer $dic, array $modules, array &$config) {
/** @noinspection PhpInternalEntityUsedInspection */
$dependencyGraph = new ModuleDependencyGraph();
$dependencyGraph->addModules($modules);
$modules = $dependencyGraph->getSortedModuleList();
foreach ($modules as $module) {
$this->loadModuleConfiguration($module, $config);
}
foreach ($modules as $module) {
$module->configureDependencyInjection($dic, $config[$module->getModuleKey()], $config);
}
} | [
"private",
"function",
"processModules",
"(",
"DependencyInjectionContainer",
"$",
"dic",
",",
"array",
"$",
"modules",
",",
"array",
"&",
"$",
"config",
")",
"{",
"/** @noinspection PhpInternalEntityUsedInspection */",
"$",
"dependencyGraph",
"=",
"new",
"ModuleDepende... | Process modules after initial loading.
@param DependencyInjectionContainer $dic
@param array $modules
@param array $config | [
"Process",
"modules",
"after",
"initial",
"loading",
"."
] | train | https://github.com/opsbears/piccolo/blob/ebba9f892ed35965140265ba1c61b2c645eab6e0/src/Module/ModuleLoader.php#L49-L62 |
opsbears/piccolo | src/Module/ModuleLoader.php | ModuleLoader.loadModule | private function loadModule(
$moduleClass,
array &$modules,
array $moduleList,
DependencyInjectionContainer $dic) {
/**
* @var Module $module
*/
$module = $dic->make($moduleClass);
if (!$module instanceof Module) {
throw new ConfigurationException(get_class($module) .
' was configured as a module, but doesn\'t implement ' . Module::class);
}
if (!\in_array($module, $modules)) {
$dic->share($module);
$this->loadRequiredModules($module, $modules, $moduleList, $dic);
$modules[] = $module;
}
} | php | private function loadModule(
$moduleClass,
array &$modules,
array $moduleList,
DependencyInjectionContainer $dic) {
/**
* @var Module $module
*/
$module = $dic->make($moduleClass);
if (!$module instanceof Module) {
throw new ConfigurationException(get_class($module) .
' was configured as a module, but doesn\'t implement ' . Module::class);
}
if (!\in_array($module, $modules)) {
$dic->share($module);
$this->loadRequiredModules($module, $modules, $moduleList, $dic);
$modules[] = $module;
}
} | [
"private",
"function",
"loadModule",
"(",
"$",
"moduleClass",
",",
"array",
"&",
"$",
"modules",
",",
"array",
"$",
"moduleList",
",",
"DependencyInjectionContainer",
"$",
"dic",
")",
"{",
"/**\n\t\t * @var Module $module\n\t\t */",
"$",
"module",
"=",
"$",
"dic",... | Load a module by class name.
@param string $moduleClass The module class to load.
@param Module[] $modules The list of already loaded modules.
@param array $moduleList The complete module list.
@param DependencyInjectionContainer $dic The dependency injection container to use for the module.
@return void
@throws ConfigurationException | [
"Load",
"a",
"module",
"by",
"class",
"name",
"."
] | train | https://github.com/opsbears/piccolo/blob/ebba9f892ed35965140265ba1c61b2c645eab6e0/src/Module/ModuleLoader.php#L76-L98 |
opsbears/piccolo | src/Module/ModuleLoader.php | ModuleLoader.loadRequiredModules | private function loadRequiredModules(
Module $module,
&$modules,
array $moduleList,
DependencyInjectionContainer $dic) {
foreach ($module->getRequiredModules() as $requiredModule) {
if (!\in_array($requiredModule, $moduleList)) {
$this->loadModule($requiredModule, $modules, $moduleList, $dic);
if ($module instanceof RequiredModuleAwareModule) {
$module->addRequiredModule($dic->make($requiredModule));
}
}
}
} | php | private function loadRequiredModules(
Module $module,
&$modules,
array $moduleList,
DependencyInjectionContainer $dic) {
foreach ($module->getRequiredModules() as $requiredModule) {
if (!\in_array($requiredModule, $moduleList)) {
$this->loadModule($requiredModule, $modules, $moduleList, $dic);
if ($module instanceof RequiredModuleAwareModule) {
$module->addRequiredModule($dic->make($requiredModule));
}
}
}
} | [
"private",
"function",
"loadRequiredModules",
"(",
"Module",
"$",
"module",
",",
"&",
"$",
"modules",
",",
"array",
"$",
"moduleList",
",",
"DependencyInjectionContainer",
"$",
"dic",
")",
"{",
"foreach",
"(",
"$",
"module",
"->",
"getRequiredModules",
"(",
")... | Load the modules a certain module requires.
@param Module $module
@param Module[] $modules
@param array $moduleList
@param DependencyInjectionContainer $dic | [
"Load",
"the",
"modules",
"a",
"certain",
"module",
"requires",
"."
] | train | https://github.com/opsbears/piccolo/blob/ebba9f892ed35965140265ba1c61b2c645eab6e0/src/Module/ModuleLoader.php#L108-L121 |
opsbears/piccolo | src/Module/ModuleLoader.php | ModuleLoader.loadModuleConfiguration | private function loadModuleConfiguration(Module $module, array &$config) {
$key = $module->getModuleKey();
if (!isset($config[$key])) {
$config[$key] = array();
}
$module->loadConfiguration($config[$key], $config);
} | php | private function loadModuleConfiguration(Module $module, array &$config) {
$key = $module->getModuleKey();
if (!isset($config[$key])) {
$config[$key] = array();
}
$module->loadConfiguration($config[$key], $config);
} | [
"private",
"function",
"loadModuleConfiguration",
"(",
"Module",
"$",
"module",
",",
"array",
"&",
"$",
"config",
")",
"{",
"$",
"key",
"=",
"$",
"module",
"->",
"getModuleKey",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"config",
"[",
"$",
"k... | Load the configuration for a specific module.
@param Module $module
@param array $config
@return void | [
"Load",
"the",
"configuration",
"for",
"a",
"specific",
"module",
"."
] | train | https://github.com/opsbears/piccolo/blob/ebba9f892ed35965140265ba1c61b2c645eab6e0/src/Module/ModuleLoader.php#L131-L137 |
moneymaxim/TrustpilotAuthenticator | src/AccessToken.php | AccessToken.unserialize | public function unserialize($serialized)
{
list($this->token, $this->expiry) = unserialize($serialized, ['allowed_classes' => [\DateTimeImmutable::class]]);
} | php | public function unserialize($serialized)
{
list($this->token, $this->expiry) = unserialize($serialized, ['allowed_classes' => [\DateTimeImmutable::class]]);
} | [
"public",
"function",
"unserialize",
"(",
"$",
"serialized",
")",
"{",
"list",
"(",
"$",
"this",
"->",
"token",
",",
"$",
"this",
"->",
"expiry",
")",
"=",
"unserialize",
"(",
"$",
"serialized",
",",
"[",
"'allowed_classes'",
"=>",
"[",
"\\",
"DateTimeIm... | {@inheritdoc} | [
"{"
] | train | https://github.com/moneymaxim/TrustpilotAuthenticator/blob/701b60040542c5d32f6ef2eb55e66b57d66021d1/src/AccessToken.php#L52-L55 |
flint/Antenna | src/Security/TokenAuthenticator.php | TokenAuthenticator.createToken | public function createToken(Request $request, $providerKey)
{
$bearer = $request->headers->get('Authorization');
if (!$bearer) {
throw new BadCredentialsException('Authorization was not found in headers.');
}
if (0 !== strpos($bearer, 'Bearer')) {
throw new BadCredentialsException('Authorization was not of type Bearer');
}
return new WebTokenToken($providerKey, $this->coder->decode(substr($bearer, 7)));
} | php | public function createToken(Request $request, $providerKey)
{
$bearer = $request->headers->get('Authorization');
if (!$bearer) {
throw new BadCredentialsException('Authorization was not found in headers.');
}
if (0 !== strpos($bearer, 'Bearer')) {
throw new BadCredentialsException('Authorization was not of type Bearer');
}
return new WebTokenToken($providerKey, $this->coder->decode(substr($bearer, 7)));
} | [
"public",
"function",
"createToken",
"(",
"Request",
"$",
"request",
",",
"$",
"providerKey",
")",
"{",
"$",
"bearer",
"=",
"$",
"request",
"->",
"headers",
"->",
"get",
"(",
"'Authorization'",
")",
";",
"if",
"(",
"!",
"$",
"bearer",
")",
"{",
"throw"... | Look at the request and see if the is a header with the token. If we find
the token, then create a PreAuthenticatedToken and let authenticateToken()
try and authenticate it.
{@inheritdoc} | [
"Look",
"at",
"the",
"request",
"and",
"see",
"if",
"the",
"is",
"a",
"header",
"with",
"the",
"token",
".",
"If",
"we",
"find",
"the",
"token",
"then",
"create",
"a",
"PreAuthenticatedToken",
"and",
"let",
"authenticateToken",
"()",
"try",
"and",
"authent... | train | https://github.com/flint/Antenna/blob/282bafa99bf75bade965b00ef43fc421674048a5/src/Security/TokenAuthenticator.php#L49-L62 |
flint/Antenna | src/Security/TokenAuthenticator.php | TokenAuthenticator.supportsToken | public function supportsToken(TokenInterface $token, $providerKey)
{
if (!$token instanceof WebTokenToken) {
return false;
}
return $providerKey == $token->getProviderKey();
} | php | public function supportsToken(TokenInterface $token, $providerKey)
{
if (!$token instanceof WebTokenToken) {
return false;
}
return $providerKey == $token->getProviderKey();
} | [
"public",
"function",
"supportsToken",
"(",
"TokenInterface",
"$",
"token",
",",
"$",
"providerKey",
")",
"{",
"if",
"(",
"!",
"$",
"token",
"instanceof",
"WebTokenToken",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"providerKey",
"==",
"$",
"tok... | {@inheritdoc} | [
"{"
] | train | https://github.com/flint/Antenna/blob/282bafa99bf75bade965b00ef43fc421674048a5/src/Security/TokenAuthenticator.php#L85-L92 |
video-games-records/TeamBundle | Controller/BadgeController.php | BadgeController.listAction | public function listAction($idTeam, $type)
{
return $this->render(
'VideoGamesRecordsTeamBundle:Badge:list.html.twig',
[
'title' => ucfirst($type),
'list' => $this->getDoctrine()->getRepository('VideoGamesRecordsTeamBundle:TeamBadge')->getFromTeam($idTeam, $type),
]
);
} | php | public function listAction($idTeam, $type)
{
return $this->render(
'VideoGamesRecordsTeamBundle:Badge:list.html.twig',
[
'title' => ucfirst($type),
'list' => $this->getDoctrine()->getRepository('VideoGamesRecordsTeamBundle:TeamBadge')->getFromTeam($idTeam, $type),
]
);
} | [
"public",
"function",
"listAction",
"(",
"$",
"idTeam",
",",
"$",
"type",
")",
"{",
"return",
"$",
"this",
"->",
"render",
"(",
"'VideoGamesRecordsTeamBundle:Badge:list.html.twig'",
",",
"[",
"'title'",
"=>",
"ucfirst",
"(",
"$",
"type",
")",
",",
"'list'",
... | @Route("/list", requirements={"id": "[1-9]\d*"}, name="vgr_badge_team_list")
@Method("GET")
@Cache(smaxage="10")
@param int $idTeam
@param string $type
@return \Symfony\Component\HttpFoundation\Response | [
"@Route",
"(",
"/",
"list",
"requirements",
"=",
"{",
"id",
":",
"[",
"1",
"-",
"9",
"]",
"\\",
"d",
"*",
"}",
"name",
"=",
"vgr_badge_team_list",
")",
"@Method",
"(",
"GET",
")",
"@Cache",
"(",
"smaxage",
"=",
"10",
")"
] | train | https://github.com/video-games-records/TeamBundle/blob/4e5b73874bacb96f70ab16e74d54a1b6efc8e62f/Controller/BadgeController.php#L27-L36 |
ronaldborla/chikka | src/Borla/Chikka/Support/Http/Guzzle.php | Guzzle.post | public function post($url, $body, array $headers = array()) {
// Execute post
$response = $this->getClient()->post($url, [
'body' => $body,
'headers' => $headers,
'verify' => dirname(__FILE__) . '/certs/ca-bundle.crt',
]);
// Get headers
$headers = $response->getHeaders();
// Parse headers
array_walk($headers, function(&$item, $key) {
// Glue array into one
$item = implode(';', $item);
});
// Return response
return new Response((string) $response->getBody(), $response->getStatusCode(), $headers);
} | php | public function post($url, $body, array $headers = array()) {
// Execute post
$response = $this->getClient()->post($url, [
'body' => $body,
'headers' => $headers,
'verify' => dirname(__FILE__) . '/certs/ca-bundle.crt',
]);
// Get headers
$headers = $response->getHeaders();
// Parse headers
array_walk($headers, function(&$item, $key) {
// Glue array into one
$item = implode(';', $item);
});
// Return response
return new Response((string) $response->getBody(), $response->getStatusCode(), $headers);
} | [
"public",
"function",
"post",
"(",
"$",
"url",
",",
"$",
"body",
",",
"array",
"$",
"headers",
"=",
"array",
"(",
")",
")",
"{",
"// Execute post",
"$",
"response",
"=",
"$",
"this",
"->",
"getClient",
"(",
")",
"->",
"post",
"(",
"$",
"url",
",",
... | Post | [
"Post"
] | train | https://github.com/ronaldborla/chikka/blob/446987706f81d5a0efbc8bd6b7d3b259d0527719/src/Borla/Chikka/Support/Http/Guzzle.php#L21-L37 |
mothership-ec/composer | src/Composer/DependencyResolver/Problem.php | Problem.addRule | public function addRule(Rule $rule)
{
$this->addReason($rule->getId(), array(
'rule' => $rule,
'job' => $rule->getJob(),
));
} | php | public function addRule(Rule $rule)
{
$this->addReason($rule->getId(), array(
'rule' => $rule,
'job' => $rule->getJob(),
));
} | [
"public",
"function",
"addRule",
"(",
"Rule",
"$",
"rule",
")",
"{",
"$",
"this",
"->",
"addReason",
"(",
"$",
"rule",
"->",
"getId",
"(",
")",
",",
"array",
"(",
"'rule'",
"=>",
"$",
"rule",
",",
"'job'",
"=>",
"$",
"rule",
"->",
"getJob",
"(",
... | Add a rule as a reason
@param Rule $rule A rule which is a reason for this problem | [
"Add",
"a",
"rule",
"as",
"a",
"reason"
] | train | https://github.com/mothership-ec/composer/blob/fa6ad031a939d8d33b211e428fdbdd28cfce238c/src/Composer/DependencyResolver/Problem.php#L48-L54 |
mothership-ec/composer | src/Composer/DependencyResolver/Problem.php | Problem.jobToText | protected function jobToText($job)
{
switch ($job['cmd']) {
case 'install':
$packages = $this->pool->whatProvides($job['packageName'], $job['constraint']);
if (!$packages) {
return 'No package found to satisfy install request for '.$job['packageName'].$this->constraintToText($job['constraint']);
}
return 'Installation request for '.$job['packageName'].$this->constraintToText($job['constraint']).' -> satisfiable by '.$this->getPackageList($packages).'.';
case 'update':
return 'Update request for '.$job['packageName'].$this->constraintToText($job['constraint']).'.';
case 'remove':
return 'Removal request for '.$job['packageName'].$this->constraintToText($job['constraint']).'';
}
if (isset($job['constraint'])) {
$packages = $this->pool->whatProvides($job['packageName'], $job['constraint']);
} else {
$packages = array();
}
return 'Job(cmd='.$job['cmd'].', target='.$job['packageName'].', packages=['.$this->getPackageList($packages).'])';
} | php | protected function jobToText($job)
{
switch ($job['cmd']) {
case 'install':
$packages = $this->pool->whatProvides($job['packageName'], $job['constraint']);
if (!$packages) {
return 'No package found to satisfy install request for '.$job['packageName'].$this->constraintToText($job['constraint']);
}
return 'Installation request for '.$job['packageName'].$this->constraintToText($job['constraint']).' -> satisfiable by '.$this->getPackageList($packages).'.';
case 'update':
return 'Update request for '.$job['packageName'].$this->constraintToText($job['constraint']).'.';
case 'remove':
return 'Removal request for '.$job['packageName'].$this->constraintToText($job['constraint']).'';
}
if (isset($job['constraint'])) {
$packages = $this->pool->whatProvides($job['packageName'], $job['constraint']);
} else {
$packages = array();
}
return 'Job(cmd='.$job['cmd'].', target='.$job['packageName'].', packages=['.$this->getPackageList($packages).'])';
} | [
"protected",
"function",
"jobToText",
"(",
"$",
"job",
")",
"{",
"switch",
"(",
"$",
"job",
"[",
"'cmd'",
"]",
")",
"{",
"case",
"'install'",
":",
"$",
"packages",
"=",
"$",
"this",
"->",
"pool",
"->",
"whatProvides",
"(",
"$",
"job",
"[",
"'packageN... | Turns a job into a human readable description
@param array $job
@return string | [
"Turns",
"a",
"job",
"into",
"a",
"human",
"readable",
"description"
] | train | https://github.com/mothership-ec/composer/blob/fa6ad031a939d8d33b211e428fdbdd28cfce238c/src/Composer/DependencyResolver/Problem.php#L179-L202 |
ShaoZeMing/laravel-merchant | src/Form/NestedForm.php | NestedForm.getTemplateHtmlAndScript | public function getTemplateHtmlAndScript()
{
$html = '';
$scripts = [];
/* @var Field $field */
foreach ($this->fields() as $field) {
//when field render, will push $script to Merchant
$html .= $field->render();
/*
* Get and remove the last script of Merchant::$script stack.
*/
if ($field->getScript()) {
$scripts[] = array_pop(Merchant::$script);
}
}
return [$html, implode("\r\n", $scripts)];
} | php | public function getTemplateHtmlAndScript()
{
$html = '';
$scripts = [];
/* @var Field $field */
foreach ($this->fields() as $field) {
//when field render, will push $script to Merchant
$html .= $field->render();
/*
* Get and remove the last script of Merchant::$script stack.
*/
if ($field->getScript()) {
$scripts[] = array_pop(Merchant::$script);
}
}
return [$html, implode("\r\n", $scripts)];
} | [
"public",
"function",
"getTemplateHtmlAndScript",
"(",
")",
"{",
"$",
"html",
"=",
"''",
";",
"$",
"scripts",
"=",
"[",
"]",
";",
"/* @var Field $field */",
"foreach",
"(",
"$",
"this",
"->",
"fields",
"(",
")",
"as",
"$",
"field",
")",
"{",
"//when fiel... | Get the html and script of template.
@return array | [
"Get",
"the",
"html",
"and",
"script",
"of",
"template",
"."
] | train | https://github.com/ShaoZeMing/laravel-merchant/blob/20801b1735e7832a6e58b37c2c391328f8d626fa/src/Form/NestedForm.php#L307-L327 |
ShaoZeMing/laravel-merchant | src/Form/NestedForm.php | NestedForm.formatField | protected function formatField(Field $field)
{
$column = $field->column();
$elementName = $elementClass = $errorKey = [];
$key = $this->key ?: 'new_'.static::DEFAULT_KEY_NAME;
if (is_array($column)) {
foreach ($column as $k => $name) {
$errorKey[$k] = sprintf('%s.%s.%s', $this->relationName, $key, $name);
$elementName[$k] = sprintf('%s[%s][%s]', $this->relationName, $key, $name);
$elementClass[$k] = [$this->relationName, $name];
}
} else {
$errorKey = sprintf('%s.%s.%s', $this->relationName, $key, $column);
$elementName = sprintf('%s[%s][%s]', $this->relationName, $key, $column);
$elementClass = [$this->relationName, $column];
}
return $field->setErrorKey($errorKey)
->setElementName($elementName)
->setElementClass($elementClass);
} | php | protected function formatField(Field $field)
{
$column = $field->column();
$elementName = $elementClass = $errorKey = [];
$key = $this->key ?: 'new_'.static::DEFAULT_KEY_NAME;
if (is_array($column)) {
foreach ($column as $k => $name) {
$errorKey[$k] = sprintf('%s.%s.%s', $this->relationName, $key, $name);
$elementName[$k] = sprintf('%s[%s][%s]', $this->relationName, $key, $name);
$elementClass[$k] = [$this->relationName, $name];
}
} else {
$errorKey = sprintf('%s.%s.%s', $this->relationName, $key, $column);
$elementName = sprintf('%s[%s][%s]', $this->relationName, $key, $column);
$elementClass = [$this->relationName, $column];
}
return $field->setErrorKey($errorKey)
->setElementName($elementName)
->setElementClass($elementClass);
} | [
"protected",
"function",
"formatField",
"(",
"Field",
"$",
"field",
")",
"{",
"$",
"column",
"=",
"$",
"field",
"->",
"column",
"(",
")",
";",
"$",
"elementName",
"=",
"$",
"elementClass",
"=",
"$",
"errorKey",
"=",
"[",
"]",
";",
"$",
"key",
"=",
... | Set `errorKey` `elementName` `elementClass` for fields inside hasmany fields.
@param Field $field
@return Field | [
"Set",
"errorKey",
"elementName",
"elementClass",
"for",
"fields",
"inside",
"hasmany",
"fields",
"."
] | train | https://github.com/ShaoZeMing/laravel-merchant/blob/20801b1735e7832a6e58b37c2c391328f8d626fa/src/Form/NestedForm.php#L336-L359 |
nabab/bbn | src/bbn/util/enc.php | enc.encryptOpenssl | public static function encryptOpenssl($textToEncrypt, string $secretHash = null, string $password = ''): ? string
{
if ( !$secretHash ){
$secretHash = self::$salt;
}
if ( $length = openssl_cipher_iv_length(self::$method) ){
$iv = substr(md5(self::$prefix.$password), 0, $length);
return openssl_encrypt($textToEncrypt, self::$method, $secretHash, true, $iv);
}
return null;
} | php | public static function encryptOpenssl($textToEncrypt, string $secretHash = null, string $password = ''): ? string
{
if ( !$secretHash ){
$secretHash = self::$salt;
}
if ( $length = openssl_cipher_iv_length(self::$method) ){
$iv = substr(md5(self::$prefix.$password), 0, $length);
return openssl_encrypt($textToEncrypt, self::$method, $secretHash, true, $iv);
}
return null;
} | [
"public",
"static",
"function",
"encryptOpenssl",
"(",
"$",
"textToEncrypt",
",",
"string",
"$",
"secretHash",
"=",
"null",
",",
"string",
"$",
"password",
"=",
"''",
")",
":",
"?",
"string",
"{",
"if",
"(",
"!",
"$",
"secretHash",
")",
"{",
"$",
"secr... | Encrypt string using openSSL module
@param string $textToEncrypt
@param string $secretHash Any random secure SALT string for your website
@param string $password User's optional password
@return null|string | [
"Encrypt",
"string",
"using",
"openSSL",
"module"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/util/enc.php#L92-L102 |
nabab/bbn | src/bbn/util/enc.php | enc.decryptOpenssl | public static function decryptOpenssl($textToDecrypt, string $secretHash = null, string $password = ''): ? string
{
if ( !$secretHash ){
$secretHash = self::$salt;
}
if ( $length = openssl_cipher_iv_length(self::$method) ){
$iv = substr(md5(self::$prefix.$password), 0, $length);
return openssl_decrypt($textToDecrypt, self::$method, $secretHash, true, $iv);
}
return null;
} | php | public static function decryptOpenssl($textToDecrypt, string $secretHash = null, string $password = ''): ? string
{
if ( !$secretHash ){
$secretHash = self::$salt;
}
if ( $length = openssl_cipher_iv_length(self::$method) ){
$iv = substr(md5(self::$prefix.$password), 0, $length);
return openssl_decrypt($textToDecrypt, self::$method, $secretHash, true, $iv);
}
return null;
} | [
"public",
"static",
"function",
"decryptOpenssl",
"(",
"$",
"textToDecrypt",
",",
"string",
"$",
"secretHash",
"=",
"null",
",",
"string",
"$",
"password",
"=",
"''",
")",
":",
"?",
"string",
"{",
"if",
"(",
"!",
"$",
"secretHash",
")",
"{",
"$",
"secr... | Decrypt string using openSSL module
@param string $textToDecrypt
@param string $secretHash Any random secure SALT string for your website
@param string $password User's optional password
@return null|string | [
"Decrypt",
"string",
"using",
"openSSL",
"module"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/util/enc.php#L111-L121 |
FriendsOfApi/phraseapp | src/Api/Upload.php | Upload.upload | public function upload(string $projectKey, string $ext, string $filename, array $params)
{
if (!file_exists($filename)) {
throw new Exception\InvalidArgumentException('file '.$filename.' not found');
}
if (!isset($params['locale_id'])) {
throw new Exception\InvalidArgumentException('locale_id is missing in params');
}
$postData = [
['name' => 'file', 'content' => file_get_contents($filename), 'filename' => basename($filename)],
['name' => 'file_format', 'content' => $ext],
['name' => 'locale_id', 'content' => $params['locale_id']],
];
if (isset($params['update_translations'])) {
$postData[] = ['name' => 'update_translations', 'content' => $params['update_translations']];
}
if (isset($params['tags'])) {
$postData[] = ['name' => 'tags', 'content' => $params['tags']];
}
$response = $this->httpPostRaw(sprintf('/api/v2/projects/%s/uploads', $projectKey), $postData, [
'Content-Type' => 'application/x-www-form-urlencoded',
]);
if (!$this->hydrator) {
return $response;
}
if ($response->getStatusCode() !== 200 && $response->getStatusCode() !== 201) {
$this->handleErrors($response);
}
return $this->hydrator->hydrate($response, Uploaded::class);
} | php | public function upload(string $projectKey, string $ext, string $filename, array $params)
{
if (!file_exists($filename)) {
throw new Exception\InvalidArgumentException('file '.$filename.' not found');
}
if (!isset($params['locale_id'])) {
throw new Exception\InvalidArgumentException('locale_id is missing in params');
}
$postData = [
['name' => 'file', 'content' => file_get_contents($filename), 'filename' => basename($filename)],
['name' => 'file_format', 'content' => $ext],
['name' => 'locale_id', 'content' => $params['locale_id']],
];
if (isset($params['update_translations'])) {
$postData[] = ['name' => 'update_translations', 'content' => $params['update_translations']];
}
if (isset($params['tags'])) {
$postData[] = ['name' => 'tags', 'content' => $params['tags']];
}
$response = $this->httpPostRaw(sprintf('/api/v2/projects/%s/uploads', $projectKey), $postData, [
'Content-Type' => 'application/x-www-form-urlencoded',
]);
if (!$this->hydrator) {
return $response;
}
if ($response->getStatusCode() !== 200 && $response->getStatusCode() !== 201) {
$this->handleErrors($response);
}
return $this->hydrator->hydrate($response, Uploaded::class);
} | [
"public",
"function",
"upload",
"(",
"string",
"$",
"projectKey",
",",
"string",
"$",
"ext",
",",
"string",
"$",
"filename",
",",
"array",
"$",
"params",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"filename",
")",
")",
"{",
"throw",
"new",
"E... | Upload a locale.
@param string $projectKey
@param string $ext
@param string $filename
@param array $params
@throws Exception
@return Uploaded|ResponseInterface | [
"Upload",
"a",
"locale",
"."
] | train | https://github.com/FriendsOfApi/phraseapp/blob/1553bf857eb0858f9a7eb905b085864d24f80886/src/Api/Upload.php#L33-L70 |
highday/glitter | src/Http/Middleware/Office/ShareFlashMessagesFromSession.php | ShareFlashMessagesFromSession.handle | public function handle($request, Closure $next)
{
$message = $request->session()->get('flash_message', []);
if (is_string($message)) {
$message = [$message];
}
$flash_message = new MessageBag($message);
// $flash_message->setFormat('<div class="alert alert-info alert-dismissible fade show" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>:message</div>');
$this->view->share(compact('flash_message'));
return $next($request);
} | php | public function handle($request, Closure $next)
{
$message = $request->session()->get('flash_message', []);
if (is_string($message)) {
$message = [$message];
}
$flash_message = new MessageBag($message);
// $flash_message->setFormat('<div class="alert alert-info alert-dismissible fade show" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>:message</div>');
$this->view->share(compact('flash_message'));
return $next($request);
} | [
"public",
"function",
"handle",
"(",
"$",
"request",
",",
"Closure",
"$",
"next",
")",
"{",
"$",
"message",
"=",
"$",
"request",
"->",
"session",
"(",
")",
"->",
"get",
"(",
"'flash_message'",
",",
"[",
"]",
")",
";",
"if",
"(",
"is_string",
"(",
"... | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed | [
"Handle",
"an",
"incoming",
"request",
"."
] | train | https://github.com/highday/glitter/blob/d1c7a227fd2343806bd3ec0314e621ced57dfe66/src/Http/Middleware/Office/ShareFlashMessagesFromSession.php#L38-L50 |
php-lug/lug | src/Bundle/ResourceBundle/Behat/Context/AbstractResourceContext.php | AbstractResourceContext.assertResourceFound | public function assertResourceFound($resource, array $criteria)
{
\PHPUnit_Framework_Assert::assertNotNull(
$result = $this->findResource($resource, $criteria),
sprintf('The resource "%s" could not be found. (%s)', $resource, json_encode($criteria))
);
return $result;
} | php | public function assertResourceFound($resource, array $criteria)
{
\PHPUnit_Framework_Assert::assertNotNull(
$result = $this->findResource($resource, $criteria),
sprintf('The resource "%s" could not be found. (%s)', $resource, json_encode($criteria))
);
return $result;
} | [
"public",
"function",
"assertResourceFound",
"(",
"$",
"resource",
",",
"array",
"$",
"criteria",
")",
"{",
"\\",
"PHPUnit_Framework_Assert",
"::",
"assertNotNull",
"(",
"$",
"result",
"=",
"$",
"this",
"->",
"findResource",
"(",
"$",
"resource",
",",
"$",
"... | @param string $resource
@param mixed $criteria
@return object|null | [
"@param",
"string",
"$resource",
"@param",
"mixed",
"$criteria"
] | train | https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/ResourceBundle/Behat/Context/AbstractResourceContext.php#L30-L38 |
php-lug/lug | src/Bundle/ResourceBundle/Behat/Context/AbstractResourceContext.php | AbstractResourceContext.findResource | private function findResource($resource, array &$criteria)
{
array_walk_recursive($criteria, function (&$value) {
if ($value === 'yes') {
$value = true;
} elseif ($value === 'no') {
$value = false;
}
});
$this->getManager($resource)->clear();
return $this->getRepository($resource)->findOneBy($criteria);
} | php | private function findResource($resource, array &$criteria)
{
array_walk_recursive($criteria, function (&$value) {
if ($value === 'yes') {
$value = true;
} elseif ($value === 'no') {
$value = false;
}
});
$this->getManager($resource)->clear();
return $this->getRepository($resource)->findOneBy($criteria);
} | [
"private",
"function",
"findResource",
"(",
"$",
"resource",
",",
"array",
"&",
"$",
"criteria",
")",
"{",
"array_walk_recursive",
"(",
"$",
"criteria",
",",
"function",
"(",
"&",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"'yes'",
")",
"{... | @param string $resource
@param mixed[] $criteria
@return object|null | [
"@param",
"string",
"$resource",
"@param",
"mixed",
"[]",
"$criteria"
] | train | https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/ResourceBundle/Behat/Context/AbstractResourceContext.php#L58-L71 |
surebert/surebert-framework | src/sb/PDO/RecordPager.php | RecordPager.getPage | public function getPage($pagenum = 1, \sb\PDO\RecordPage $ret = null)
{
$pagenum = ($pagenum < 1) ? 1 : $pagenum;
$this->sql = trim($this->sql);
if ($this->sql == '') {
throw(new \Exception("The SQL statement is blank and therefore not valid."));
} else if (strtoupper(substr($this->sql, 0, 6)) != 'SELECT' || stristr($this->sql, " LIMIT ")) {
throw(new \Exception("Expecting SQL statment starting with 'SELECT' and with no 'LIMIT' clause, found: ".$this->sql));
} else {
//start return object
if (!$ret) {
$ret = new \sb\PDO\RecordPage();
}
$this->sql = str_replace(";", "", $this->sql);
$ret->requested_page = $pagenum;
//get counts
$sql = $this->sql;
if ($this->max_limit) {
$sql .= " LIMIT " . $this->max_limit;
}
$count_sql = "SELECT COUNT(*) AS 'count' FROM (" . $sql . ") sb65a";
$res = $this->db->s2o($count_sql, $this->values);
$ret->record_count = isset($res[0]) ? $res[0]->count : 0;
//page count
$temp = round($ret->record_count / $this->pagesize);
$temp2 = $temp * $this->pagesize;
$round_up = ($temp2 < $ret->record_count) ? 1 : 0;
$ret->page_count = round($ret->record_count / $this->pagesize) + $round_up;
$ret->page_count = ($ret->page_count < 1) ? 1 : $ret->page_count;
//current page
$ret->current_page = ($pagenum > $ret->page_count) ? $ret->page_count : $pagenum;
//get limit clause
$start = ($this->pagesize * ($ret->current_page - 1));
$start = ($start < 0) ? 0 : $start;
$limit_sql = $this->sql . " LIMIT $start, $this->pagesize; ";
//debug
//echo $limit_sql; exit;
$ret->rows = $this->db->s2o($limit_sql, $this->values, $this->object_type);
//return
return $ret;
}
return 0;
} | php | public function getPage($pagenum = 1, \sb\PDO\RecordPage $ret = null)
{
$pagenum = ($pagenum < 1) ? 1 : $pagenum;
$this->sql = trim($this->sql);
if ($this->sql == '') {
throw(new \Exception("The SQL statement is blank and therefore not valid."));
} else if (strtoupper(substr($this->sql, 0, 6)) != 'SELECT' || stristr($this->sql, " LIMIT ")) {
throw(new \Exception("Expecting SQL statment starting with 'SELECT' and with no 'LIMIT' clause, found: ".$this->sql));
} else {
//start return object
if (!$ret) {
$ret = new \sb\PDO\RecordPage();
}
$this->sql = str_replace(";", "", $this->sql);
$ret->requested_page = $pagenum;
//get counts
$sql = $this->sql;
if ($this->max_limit) {
$sql .= " LIMIT " . $this->max_limit;
}
$count_sql = "SELECT COUNT(*) AS 'count' FROM (" . $sql . ") sb65a";
$res = $this->db->s2o($count_sql, $this->values);
$ret->record_count = isset($res[0]) ? $res[0]->count : 0;
//page count
$temp = round($ret->record_count / $this->pagesize);
$temp2 = $temp * $this->pagesize;
$round_up = ($temp2 < $ret->record_count) ? 1 : 0;
$ret->page_count = round($ret->record_count / $this->pagesize) + $round_up;
$ret->page_count = ($ret->page_count < 1) ? 1 : $ret->page_count;
//current page
$ret->current_page = ($pagenum > $ret->page_count) ? $ret->page_count : $pagenum;
//get limit clause
$start = ($this->pagesize * ($ret->current_page - 1));
$start = ($start < 0) ? 0 : $start;
$limit_sql = $this->sql . " LIMIT $start, $this->pagesize; ";
//debug
//echo $limit_sql; exit;
$ret->rows = $this->db->s2o($limit_sql, $this->values, $this->object_type);
//return
return $ret;
}
return 0;
} | [
"public",
"function",
"getPage",
"(",
"$",
"pagenum",
"=",
"1",
",",
"\\",
"sb",
"\\",
"PDO",
"\\",
"RecordPage",
"$",
"ret",
"=",
"null",
")",
"{",
"$",
"pagenum",
"=",
"(",
"$",
"pagenum",
"<",
"1",
")",
"?",
"1",
":",
"$",
"pagenum",
";",
"$... | Returns an object of type \sb\PDO\RecordPage set to the page numberd $pagenum
Changed this 05/06/2008 Paul Visco added use of $this->values and
$this->object_type to support additional \sb\PDO->s2o() arguments
@param integer $pagenum
@return \sb\PDORecordPage
<code>
//get the current requested page from an internet user
$pnum = (isset($_REQUEST['page']))?$_REQUEST['page']:1;
$pager = new \sb\PDO\RecordPager($mysqlconn);
$pager->sql = "SELECT * FROM user ORDER BY lname DESC;";
$pager->pagesize = 20 //optional default is set to 10
$res = $pager->getPage($punm);
echo '<pre>' . print_r($res->rows) . '</pre>';
</code> | [
"Returns",
"an",
"object",
"of",
"type",
"\\",
"sb",
"\\",
"PDO",
"\\",
"RecordPage",
"set",
"to",
"the",
"page",
"numberd",
"$pagenum"
] | train | https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/PDO/RecordPager.php#L96-L151 |
surebert/surebert-framework | src/sb/PDO/RecordPager.php | RecordPager.flipTo | public function flipTo($field, $value)
{
$ret = new \stdClass();
$ret->found = 0;
$ret->page = new \stdClass();
if (trim($this->sql) != '') {
//get the page count
$temp = $this->getPage();
$count = $temp->page_count;
for ($pnum = 1; $pnum <= $count; $pnum++) {
//get the next page
$page = $this->getPage($pnum);
//look for the value
foreach ($page->rows as $rec) {
if (isset($rec->{$field})) {
if ($rec->{$field} == $value) {
return $page;
}
} else {
throw(new \Exception(
"The field $field is not contained in the recordset you request to search"
));
}
}
}
} else {
throw(new \Exception("\$sql not set. Please set SQL before flipping to a page"));
}
return 0;
} | php | public function flipTo($field, $value)
{
$ret = new \stdClass();
$ret->found = 0;
$ret->page = new \stdClass();
if (trim($this->sql) != '') {
//get the page count
$temp = $this->getPage();
$count = $temp->page_count;
for ($pnum = 1; $pnum <= $count; $pnum++) {
//get the next page
$page = $this->getPage($pnum);
//look for the value
foreach ($page->rows as $rec) {
if (isset($rec->{$field})) {
if ($rec->{$field} == $value) {
return $page;
}
} else {
throw(new \Exception(
"The field $field is not contained in the recordset you request to search"
));
}
}
}
} else {
throw(new \Exception("\$sql not set. Please set SQL before flipping to a page"));
}
return 0;
} | [
"public",
"function",
"flipTo",
"(",
"$",
"field",
",",
"$",
"value",
")",
"{",
"$",
"ret",
"=",
"new",
"\\",
"stdClass",
"(",
")",
";",
"$",
"ret",
"->",
"found",
"=",
"0",
";",
"$",
"ret",
"->",
"page",
"=",
"new",
"\\",
"stdClass",
"(",
")",... | After a sql statment has been set for this object this method will return
a class of type \sb\PDORecordPage that is the first page that meets the following
search critieria:
$field (the field to search)
$value (the value of the specified field)
NOTE: This functionaly is very slow to use.
@author Tony Cashaw
@param string $field
@param string $value
@return object \sb\PDORecordPage or 0 if the value is not found
<code>
//... continued from above
if($flipped = $pager->flipTo('lname', 'cashaw')){
//prints the contents of the first page that contained a row with the column
//'lname' set to the value of 'cashaw'
echo '<pre>' . print_r($res->rows) . '</pre>';
}else{
}
</code> | [
"After",
"a",
"sql",
"statment",
"has",
"been",
"set",
"for",
"this",
"object",
"this",
"method",
"will",
"return",
"a",
"class",
"of",
"type",
"\\",
"sb",
"\\",
"PDORecordPage",
"that",
"is",
"the",
"first",
"page",
"that",
"meets",
"the",
"following",
... | train | https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/PDO/RecordPager.php#L181-L216 |
rhosocial/yii2-user | grid/ActionColumn.php | ActionColumn.initDefaultButtons | protected function initDefaultButtons()
{
$this->initDefaultButton('view', $this->useIcon ? 'eye-open' : false);
$this->initDefaultButton('update', $this->useIcon ? 'pencil' : false);
$this->initDefaultButton('delete', $this->useIcon ? 'trash' : false, [
'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
'data-method' => 'post',
]);
} | php | protected function initDefaultButtons()
{
$this->initDefaultButton('view', $this->useIcon ? 'eye-open' : false);
$this->initDefaultButton('update', $this->useIcon ? 'pencil' : false);
$this->initDefaultButton('delete', $this->useIcon ? 'trash' : false, [
'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
'data-method' => 'post',
]);
} | [
"protected",
"function",
"initDefaultButtons",
"(",
")",
"{",
"$",
"this",
"->",
"initDefaultButton",
"(",
"'view'",
",",
"$",
"this",
"->",
"useIcon",
"?",
"'eye-open'",
":",
"false",
")",
";",
"$",
"this",
"->",
"initDefaultButton",
"(",
"'update'",
",",
... | Initializes the default button rendering callbacks. | [
"Initializes",
"the",
"default",
"button",
"rendering",
"callbacks",
"."
] | train | https://github.com/rhosocial/yii2-user/blob/96737a9d8ca7e9c42cd2b7736d6c0a90ede6e5bc/grid/ActionColumn.php#L34-L42 |
KunstmaanLegacy/KunstmaanSentryBundle | EventListener/ExceptionListener.php | ExceptionListener.onKernelException | public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if ($exception instanceof HttpException) {
return;
}
$culprit = null;
if ($event->getRequest()->attributes->has("_controller")) {
$culprit = $event->getRequest()->attributes->get("_controller");
}
$event_id = $this->client->getIdent($this->client->captureException($exception, $culprit, $this->client->getEnvironment()));
return error_log("[$event_id] " . $exception->getMessage() . ' in: ' . $exception->getFile() . ':' . $exception->getLine());
} | php | public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if ($exception instanceof HttpException) {
return;
}
$culprit = null;
if ($event->getRequest()->attributes->has("_controller")) {
$culprit = $event->getRequest()->attributes->get("_controller");
}
$event_id = $this->client->getIdent($this->client->captureException($exception, $culprit, $this->client->getEnvironment()));
return error_log("[$event_id] " . $exception->getMessage() . ' in: ' . $exception->getFile() . ':' . $exception->getLine());
} | [
"public",
"function",
"onKernelException",
"(",
"GetResponseForExceptionEvent",
"$",
"event",
")",
"{",
"$",
"exception",
"=",
"$",
"event",
"->",
"getException",
"(",
")",
";",
"if",
"(",
"$",
"exception",
"instanceof",
"HttpException",
")",
"{",
"return",
";... | @param GetResponseForExceptionEvent $event
@return array|null; | [
"@param",
"GetResponseForExceptionEvent",
"$event"
] | train | https://github.com/KunstmaanLegacy/KunstmaanSentryBundle/blob/db2bcf2ac5c6864b24715bc596c5feb41c8951cf/EventListener/ExceptionListener.php#L31-L44 |
LeaseCloud/leasecloud-php-sdk | src/HttpClient/CurlClient.php | CurlClient.request | public function request($method, $absUrl, $params, $headers)
{
$curl = curl_init();
$method = strtolower($method);
$opts = array();
if ($method == 'get') {
$opts[CURLOPT_HTTPGET] = 1;
if (count($params) > 0) {
$encoded = self::urlEncode($params);
$absUrl = "$absUrl?$encoded";
}
} elseif ($method == 'post') {
$opts[CURLOPT_POST] = 1;
$opts[CURLOPT_POSTFIELDS] = json_encode($params);
} elseif ($method == 'delete') {
$opts[CURLOPT_CUSTOMREQUEST] = 'DELETE';
if (count($params) > 0) {
$encoded = self::urlEncode($params);
$absUrl = "$absUrl?$encoded";
}
} else {
throw new Error("Unrecognized method $method");
}
// Create a callback to capture HTTP headers for the response
$rheaders = array();
$headerCallback = function ($curl, $header_line) use (&$rheaders) {
// Ignore the HTTP request line (HTTP/1.1 200 OK)
if (strpos($header_line, ":") === false) {
return strlen($header_line);
}
list($key, $value) = explode(":", trim($header_line), 2);
$rheaders[trim($key)] = trim($value);
return strlen($header_line);
};
// By default for large request body sizes (> 1024 bytes), cURL will
// send a request without a body and with a `Expect: 100-continue`
// header, which gives the server a chance to respond with an error
// status code in cases where one can be determined right away (say
// on an authentication problem for example), and saves the "large"
// request body from being ever sent.
//
// Unfortunately, the bindings don't currently correctly handle the
// success case (in which the server sends back a 100 CONTINUE), so
// we'll error under that condition. To compensate for that problem
// for the time being, override cURL's behavior by simply always
// sending an empty `Expect:` header.
array_push($headers, 'Expect: ');
$opts[CURLOPT_URL] = $absUrl;
$opts[CURLOPT_RETURNTRANSFER] = true;
$opts[CURLOPT_CONNECTTIMEOUT] = 80;
$opts[CURLOPT_TIMEOUT] = 30;
$opts[CURLOPT_HEADERFUNCTION] = $headerCallback;
$opts[CURLOPT_HTTPHEADER] = $headers;
curl_setopt_array($curl, $opts);
$rbody = curl_exec($curl);
if ($rbody === false) {
$errno = curl_errno($curl);
$message = curl_error($curl);
curl_close($curl);
$this->handleCurlError($errno, $message);
}
$rcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return array(json_decode($rbody), $rcode, $rheaders);
} | php | public function request($method, $absUrl, $params, $headers)
{
$curl = curl_init();
$method = strtolower($method);
$opts = array();
if ($method == 'get') {
$opts[CURLOPT_HTTPGET] = 1;
if (count($params) > 0) {
$encoded = self::urlEncode($params);
$absUrl = "$absUrl?$encoded";
}
} elseif ($method == 'post') {
$opts[CURLOPT_POST] = 1;
$opts[CURLOPT_POSTFIELDS] = json_encode($params);
} elseif ($method == 'delete') {
$opts[CURLOPT_CUSTOMREQUEST] = 'DELETE';
if (count($params) > 0) {
$encoded = self::urlEncode($params);
$absUrl = "$absUrl?$encoded";
}
} else {
throw new Error("Unrecognized method $method");
}
// Create a callback to capture HTTP headers for the response
$rheaders = array();
$headerCallback = function ($curl, $header_line) use (&$rheaders) {
// Ignore the HTTP request line (HTTP/1.1 200 OK)
if (strpos($header_line, ":") === false) {
return strlen($header_line);
}
list($key, $value) = explode(":", trim($header_line), 2);
$rheaders[trim($key)] = trim($value);
return strlen($header_line);
};
// By default for large request body sizes (> 1024 bytes), cURL will
// send a request without a body and with a `Expect: 100-continue`
// header, which gives the server a chance to respond with an error
// status code in cases where one can be determined right away (say
// on an authentication problem for example), and saves the "large"
// request body from being ever sent.
//
// Unfortunately, the bindings don't currently correctly handle the
// success case (in which the server sends back a 100 CONTINUE), so
// we'll error under that condition. To compensate for that problem
// for the time being, override cURL's behavior by simply always
// sending an empty `Expect:` header.
array_push($headers, 'Expect: ');
$opts[CURLOPT_URL] = $absUrl;
$opts[CURLOPT_RETURNTRANSFER] = true;
$opts[CURLOPT_CONNECTTIMEOUT] = 80;
$opts[CURLOPT_TIMEOUT] = 30;
$opts[CURLOPT_HEADERFUNCTION] = $headerCallback;
$opts[CURLOPT_HTTPHEADER] = $headers;
curl_setopt_array($curl, $opts);
$rbody = curl_exec($curl);
if ($rbody === false) {
$errno = curl_errno($curl);
$message = curl_error($curl);
curl_close($curl);
$this->handleCurlError($errno, $message);
}
$rcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return array(json_decode($rbody), $rcode, $rheaders);
} | [
"public",
"function",
"request",
"(",
"$",
"method",
",",
"$",
"absUrl",
",",
"$",
"params",
",",
"$",
"headers",
")",
"{",
"$",
"curl",
"=",
"curl_init",
"(",
")",
";",
"$",
"method",
"=",
"strtolower",
"(",
"$",
"method",
")",
";",
"$",
"opts",
... | Make the request
@param string $method
@param string $absUrl
@param array $params
@param array $headers
@return array A zero indexed array.
0 => Response
1 => Response http code
2 => Array of response headers | [
"Make",
"the",
"request"
] | train | https://github.com/LeaseCloud/leasecloud-php-sdk/blob/091b073dd4f79ba915a68c0ed151bd9bfa61e7ca/src/HttpClient/CurlClient.php#L43-L115 |
LeaseCloud/leasecloud-php-sdk | src/HttpClient/CurlClient.php | CurlClient.handleCurlError | private function handleCurlError($errno, $message)
{
switch ($errno) {
case CURLE_COULDNT_CONNECT:
case CURLE_COULDNT_RESOLVE_HOST:
case CURLE_OPERATION_TIMEOUTED:
$msg = "Could not connect";
break;
case CURLE_SSL_CACERT:
case CURLE_SSL_PEER_CERTIFICATE:
$msg = "Could not verify SSL certificate.";
break;
default:
$msg = "Unexpected curl error.";
}
$msg .= "\n\n(Network error [errno $errno]: $message)";
throw new \LeaseCloud\Error($msg);
} | php | private function handleCurlError($errno, $message)
{
switch ($errno) {
case CURLE_COULDNT_CONNECT:
case CURLE_COULDNT_RESOLVE_HOST:
case CURLE_OPERATION_TIMEOUTED:
$msg = "Could not connect";
break;
case CURLE_SSL_CACERT:
case CURLE_SSL_PEER_CERTIFICATE:
$msg = "Could not verify SSL certificate.";
break;
default:
$msg = "Unexpected curl error.";
}
$msg .= "\n\n(Network error [errno $errno]: $message)";
throw new \LeaseCloud\Error($msg);
} | [
"private",
"function",
"handleCurlError",
"(",
"$",
"errno",
",",
"$",
"message",
")",
"{",
"switch",
"(",
"$",
"errno",
")",
"{",
"case",
"CURLE_COULDNT_CONNECT",
":",
"case",
"CURLE_COULDNT_RESOLVE_HOST",
":",
"case",
"CURLE_OPERATION_TIMEOUTED",
":",
"$",
"ms... | Throw an exception with message indicating type of http error
@param number $errno
@param string $message
@throws Error | [
"Throw",
"an",
"exception",
"with",
"message",
"indicating",
"type",
"of",
"http",
"error"
] | train | https://github.com/LeaseCloud/leasecloud-php-sdk/blob/091b073dd4f79ba915a68c0ed151bd9bfa61e7ca/src/HttpClient/CurlClient.php#L124-L142 |
php-lug/lug | src/Component/Resource/Model/Resource.php | Resource.getRelation | public function getRelation($name)
{
return isset($this->relations[$name]) ? $this->relations[$name] : null;
} | php | public function getRelation($name)
{
return isset($this->relations[$name]) ? $this->relations[$name] : null;
} | [
"public",
"function",
"getRelation",
"(",
"$",
"name",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"relations",
"[",
"$",
"name",
"]",
")",
"?",
"$",
"this",
"->",
"relations",
"[",
"$",
"name",
"]",
":",
"null",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Component/Resource/Model/Resource.php#L346-L349 |
php-lug/lug | src/Component/Resource/Model/Resource.php | Resource.setRelations | public function setRelations(array $relations)
{
$this->relations = [];
foreach ($relations as $name => $relation) {
$this->addRelation($name, $relation);
}
} | php | public function setRelations(array $relations)
{
$this->relations = [];
foreach ($relations as $name => $relation) {
$this->addRelation($name, $relation);
}
} | [
"public",
"function",
"setRelations",
"(",
"array",
"$",
"relations",
")",
"{",
"$",
"this",
"->",
"relations",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"relations",
"as",
"$",
"name",
"=>",
"$",
"relation",
")",
"{",
"$",
"this",
"->",
"addRelation",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Component/Resource/Model/Resource.php#L354-L361 |
tompedals/radish | src/Broker/QueueCollection.php | QueueCollection.pop | public function pop()
{
$keys = array_keys($this->queues);
for ($this->queueCounter; isset($keys[$this->queueCounter]); $this->queueCounter++) {
$queue = $this->queues[$keys[$this->queueCounter]];
$message = $queue->pop();
if ($message !== null) {
$this->queueCounter++;
$this->processedMessages++;
return $message;
}
// After the last queue has been popped
if ((count($this->queues) -1) === $this->queueCounter) {
$this->queueCounter = 0;
if ($this->processedMessages === 0) {
return null;
}
$this->processedMessages = 0;
}
}
return null;
} | php | public function pop()
{
$keys = array_keys($this->queues);
for ($this->queueCounter; isset($keys[$this->queueCounter]); $this->queueCounter++) {
$queue = $this->queues[$keys[$this->queueCounter]];
$message = $queue->pop();
if ($message !== null) {
$this->queueCounter++;
$this->processedMessages++;
return $message;
}
// After the last queue has been popped
if ((count($this->queues) -1) === $this->queueCounter) {
$this->queueCounter = 0;
if ($this->processedMessages === 0) {
return null;
}
$this->processedMessages = 0;
}
}
return null;
} | [
"public",
"function",
"pop",
"(",
")",
"{",
"$",
"keys",
"=",
"array_keys",
"(",
"$",
"this",
"->",
"queues",
")",
";",
"for",
"(",
"$",
"this",
"->",
"queueCounter",
";",
"isset",
"(",
"$",
"keys",
"[",
"$",
"this",
"->",
"queueCounter",
"]",
")",... | Returns the next message from each queue until all are empty
@return Message|null | [
"Returns",
"the",
"next",
"message",
"from",
"each",
"queue",
"until",
"all",
"are",
"empty"
] | train | https://github.com/tompedals/radish/blob/7728567ae6226a5e3f627116118198b22d1b507d/src/Broker/QueueCollection.php#L66-L94 |
thelia-modules/CustomerGroup | EventListener/ModuleEventListener.php | ModuleEventListener.loadCustomerGroupConfigFile | public function loadCustomerGroupConfigFile(ModuleToggleActivationEvent $event)
{
$event->setModule(ModuleQuery::create()->findPk($event->getModuleId()));
if ($event->getModule()->getActivate() === BaseModule::IS_NOT_ACTIVATED) {
$this->configurationFileHandler->loadConfigurationFile($event->getModule());
}
} | php | public function loadCustomerGroupConfigFile(ModuleToggleActivationEvent $event)
{
$event->setModule(ModuleQuery::create()->findPk($event->getModuleId()));
if ($event->getModule()->getActivate() === BaseModule::IS_NOT_ACTIVATED) {
$this->configurationFileHandler->loadConfigurationFile($event->getModule());
}
} | [
"public",
"function",
"loadCustomerGroupConfigFile",
"(",
"ModuleToggleActivationEvent",
"$",
"event",
")",
"{",
"$",
"event",
"->",
"setModule",
"(",
"ModuleQuery",
"::",
"create",
"(",
")",
"->",
"findPk",
"(",
"$",
"event",
"->",
"getModuleId",
"(",
")",
")... | Load customer group definitions
@param ModuleToggleActivationEvent $event A module toggle activation event | [
"Load",
"customer",
"group",
"definitions"
] | train | https://github.com/thelia-modules/CustomerGroup/blob/672cc64c686812f6a95cf0d702111f93d8c0e850/EventListener/ModuleEventListener.php#L44-L51 |
heidelpay/PhpDoc | src/phpDocumentor/Compiler/Pass/MarkerFromTagsExtractor.php | MarkerFromTagsExtractor.getFileDescriptor | protected function getFileDescriptor($element)
{
$fileDescriptor = $element instanceof FileDescriptor
? $element
: $element->getFile();
if (!$fileDescriptor instanceof FileDescriptor) {
throw new \UnexpectedValueException('An element should always have a file associated with it');
}
return $fileDescriptor;
} | php | protected function getFileDescriptor($element)
{
$fileDescriptor = $element instanceof FileDescriptor
? $element
: $element->getFile();
if (!$fileDescriptor instanceof FileDescriptor) {
throw new \UnexpectedValueException('An element should always have a file associated with it');
}
return $fileDescriptor;
} | [
"protected",
"function",
"getFileDescriptor",
"(",
"$",
"element",
")",
"{",
"$",
"fileDescriptor",
"=",
"$",
"element",
"instanceof",
"FileDescriptor",
"?",
"$",
"element",
":",
"$",
"element",
"->",
"getFile",
"(",
")",
";",
"if",
"(",
"!",
"$",
"fileDes... | Retrieves the File Descriptor from the given element.
@param DescriptorAbstract $element
@throws \UnexpectedValueException if the provided element does not have a file associated with it.
@return FileDescriptor | [
"Retrieves",
"the",
"File",
"Descriptor",
"from",
"the",
"given",
"element",
"."
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Compiler/Pass/MarkerFromTagsExtractor.php#L66-L77 |
heidelpay/PhpDoc | src/phpDocumentor/Compiler/Pass/MarkerFromTagsExtractor.php | MarkerFromTagsExtractor.addTodoMarkerToFile | protected function addTodoMarkerToFile($fileDescriptor, $todo, $lineNumber)
{
$fileDescriptor->getMarkers()->add(
array(
'type' => 'TODO',
'message' => $todo->getDescription(),
'line' => $lineNumber,
)
);
} | php | protected function addTodoMarkerToFile($fileDescriptor, $todo, $lineNumber)
{
$fileDescriptor->getMarkers()->add(
array(
'type' => 'TODO',
'message' => $todo->getDescription(),
'line' => $lineNumber,
)
);
} | [
"protected",
"function",
"addTodoMarkerToFile",
"(",
"$",
"fileDescriptor",
",",
"$",
"todo",
",",
"$",
"lineNumber",
")",
"{",
"$",
"fileDescriptor",
"->",
"getMarkers",
"(",
")",
"->",
"add",
"(",
"array",
"(",
"'type'",
"=>",
"'TODO'",
",",
"'message'",
... | Adds a marker with the TO DO information to the file on a given line number.
@param FileDescriptor $fileDescriptor
@param TagDescriptor $todo
@param integer $lineNumber
@return void | [
"Adds",
"a",
"marker",
"with",
"the",
"TO",
"DO",
"information",
"to",
"the",
"file",
"on",
"a",
"given",
"line",
"number",
"."
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Compiler/Pass/MarkerFromTagsExtractor.php#L88-L97 |
interactivesolutions/honeycomb-core | src/providers/HCBaseServiceProvider.php | HCBaseServiceProvider.boot | public function boot (Gate $gate, Router $router)
{
// register artisan commands
$this->commands ($this->commands);
// loading views
$this->loadViewsFrom ($this->homeDirectory . '/../../resources/views', $this->serviceProviderNameSpace);
// loading translations
$this->loadTranslationsFrom ($this->homeDirectory . '/../../resources/lang', $this->serviceProviderNameSpace);
// registering elements to publish
$this->registerPublishElements ();
//registering middleware
$this->registerMiddleWare($router);
// registering routes
$this->registerRoutes ($router);
//registering router items
$this->registerRouterItems ($router);
//registering gate items
$this->registerGateItems ($gate);
} | php | public function boot (Gate $gate, Router $router)
{
// register artisan commands
$this->commands ($this->commands);
// loading views
$this->loadViewsFrom ($this->homeDirectory . '/../../resources/views', $this->serviceProviderNameSpace);
// loading translations
$this->loadTranslationsFrom ($this->homeDirectory . '/../../resources/lang', $this->serviceProviderNameSpace);
// registering elements to publish
$this->registerPublishElements ();
//registering middleware
$this->registerMiddleWare($router);
// registering routes
$this->registerRoutes ($router);
//registering router items
$this->registerRouterItems ($router);
//registering gate items
$this->registerGateItems ($gate);
} | [
"public",
"function",
"boot",
"(",
"Gate",
"$",
"gate",
",",
"Router",
"$",
"router",
")",
"{",
"// register artisan commands",
"$",
"this",
"->",
"commands",
"(",
"$",
"this",
"->",
"commands",
")",
";",
"// loading views",
"$",
"this",
"->",
"loadViewsFrom... | Bootstrap the application services.
@param Gate $gate
@param Router $router | [
"Bootstrap",
"the",
"application",
"services",
"."
] | train | https://github.com/interactivesolutions/honeycomb-core/blob/06b8d88bb285e73a1a286e60411ca5f41863f39f/src/providers/HCBaseServiceProvider.php#L38-L63 |
interactivesolutions/honeycomb-core | src/providers/HCBaseServiceProvider.php | HCBaseServiceProvider.registerPublishElements | protected function registerPublishElements ()
{
$directory = $this->homeDirectory . '/../../database/migrations/';
// Publish your migrations
if (file_exists ($directory))
$this->publishes ([
$this->homeDirectory . '/../../database/migrations/' => database_path ('/migrations'),
], 'migrations');
$directory = $this->homeDirectory . '/../public';
// Publishing assets
if (file_exists ($directory))
$this->publishes ([
$this->homeDirectory . '/../public' => public_path ('honeycomb'),
], 'public');
$directory = $this->homeDirectory . '/../config';
// Publishing assets
if (file_exists ($directory))
$this->publishes ([
$this->homeDirectory . '/../config' => config_path('/'),
], 'config');
} | php | protected function registerPublishElements ()
{
$directory = $this->homeDirectory . '/../../database/migrations/';
// Publish your migrations
if (file_exists ($directory))
$this->publishes ([
$this->homeDirectory . '/../../database/migrations/' => database_path ('/migrations'),
], 'migrations');
$directory = $this->homeDirectory . '/../public';
// Publishing assets
if (file_exists ($directory))
$this->publishes ([
$this->homeDirectory . '/../public' => public_path ('honeycomb'),
], 'public');
$directory = $this->homeDirectory . '/../config';
// Publishing assets
if (file_exists ($directory))
$this->publishes ([
$this->homeDirectory . '/../config' => config_path('/'),
], 'config');
} | [
"protected",
"function",
"registerPublishElements",
"(",
")",
"{",
"$",
"directory",
"=",
"$",
"this",
"->",
"homeDirectory",
".",
"'/../../database/migrations/'",
";",
"// Publish your migrations",
"if",
"(",
"file_exists",
"(",
"$",
"directory",
")",
")",
"$",
"... | Registering all vendor items which needs to be published | [
"Registering",
"all",
"vendor",
"items",
"which",
"needs",
"to",
"be",
"published"
] | train | https://github.com/interactivesolutions/honeycomb-core/blob/06b8d88bb285e73a1a286e60411ca5f41863f39f/src/providers/HCBaseServiceProvider.php#L94-L119 |
interactivesolutions/honeycomb-core | src/providers/HCBaseServiceProvider.php | HCBaseServiceProvider.registerRoutes | protected function registerRoutes (Router $router)
{
$filePath = $this->homeDirectory . '/../../app/honeycomb/routes.php';
if( file_exists($filePath) ) {
if (! $this->app->routesAreCached()) {
$router->group([
'namespace' => $this->namespace,
], function (Router $router) use ($filePath) {
require $filePath;
});
}
}
} | php | protected function registerRoutes (Router $router)
{
$filePath = $this->homeDirectory . '/../../app/honeycomb/routes.php';
if( file_exists($filePath) ) {
if (! $this->app->routesAreCached()) {
$router->group([
'namespace' => $this->namespace,
], function (Router $router) use ($filePath) {
require $filePath;
});
}
}
} | [
"protected",
"function",
"registerRoutes",
"(",
"Router",
"$",
"router",
")",
"{",
"$",
"filePath",
"=",
"$",
"this",
"->",
"homeDirectory",
".",
"'/../../app/honeycomb/routes.php'",
";",
"if",
"(",
"file_exists",
"(",
"$",
"filePath",
")",
")",
"{",
"if",
"... | Registering routes
@param Router $router | [
"Registering",
"routes"
] | train | https://github.com/interactivesolutions/honeycomb-core/blob/06b8d88bb285e73a1a286e60411ca5f41863f39f/src/providers/HCBaseServiceProvider.php#L125-L138 |
mothership-ec/composer | src/Composer/Installer/LibraryInstaller.php | LibraryInstaller.install | public function install(InstalledRepositoryInterface $repo, PackageInterface $package)
{
$this->initializeVendorDir();
$downloadPath = $this->getInstallPath($package);
// remove the binaries if it appears the package files are missing
if (!is_readable($downloadPath) && $repo->hasPackage($package)) {
$this->removeBinaries($package);
}
$this->installCode($package);
$this->installBinaries($package);
if (!$repo->hasPackage($package)) {
$repo->addPackage(clone $package);
}
} | php | public function install(InstalledRepositoryInterface $repo, PackageInterface $package)
{
$this->initializeVendorDir();
$downloadPath = $this->getInstallPath($package);
// remove the binaries if it appears the package files are missing
if (!is_readable($downloadPath) && $repo->hasPackage($package)) {
$this->removeBinaries($package);
}
$this->installCode($package);
$this->installBinaries($package);
if (!$repo->hasPackage($package)) {
$repo->addPackage(clone $package);
}
} | [
"public",
"function",
"install",
"(",
"InstalledRepositoryInterface",
"$",
"repo",
",",
"PackageInterface",
"$",
"package",
")",
"{",
"$",
"this",
"->",
"initializeVendorDir",
"(",
")",
";",
"$",
"downloadPath",
"=",
"$",
"this",
"->",
"getInstallPath",
"(",
"... | {@inheritDoc} | [
"{"
] | train | https://github.com/mothership-ec/composer/blob/fa6ad031a939d8d33b211e428fdbdd28cfce238c/src/Composer/Installer/LibraryInstaller.php#L77-L92 |
gn36/phpbb-oo-posting-api | src/Gn36/OoPostingApi/post.php | post.submit_without_sync | function submit_without_sync($sync_not_needed = null)
{
global $config, $db, $auth, $user;
if(!$this->post_id)
{
//new post, set some default values if not set yet
if(!$this->poster_id) $this->poster_id = $user->data['user_id'];
if(!$this->poster_ip) $this->poster_ip = $user->ip;
if(!$this->post_time) $this->post_time = time();
}
$this->post_subject = truncate_string($this->post_subject);
if (!$this->post_username && $this->poster_id != ANONYMOUS)
{
if ($this->poster_id == $user->data['user_id'])
{
$this->post_username = $user->data['username'];
}
else
{
// Username is not known, fetch it
$sql = 'SELECT username FROM ' . USERS_TABLE . ' WHERE user_id = ' . (int) $this->poster_id;
$result = $db->sql_query($sql);
$username = $db->sql_fetchfield('username', false, $result);
$this->post_username = ($username ? $username : '');
}
}
$sql_data = array(
'poster_id' => $this->poster_id,
'poster_ip' => $this->poster_ip,
'topic_id' => $this->topic_id,
'forum_id' => $this->forum_id,
'post_username' => $this->post_username,
'icon_id' => $this->icon_id,
'post_time' => $this->post_time,
'post_postcount' => $this->post_postcount ? 1 : 0,
'post_visibility' => $this->post_visibility,
'post_reported' => $this->post_reported ? 1 : 0,
'enable_bbcode' => $this->enable_bbcode ? 1 : 0,
'enable_smilies' => $this->enable_smilies ? 1 : 0,
'enable_magic_url' => $this->enable_magic_url ? 1 : 0,
'enable_urls' => $this->enable_urls ? 1 : 0,
'enable_sig' => $this->enable_sig ? 1 : 0,
'post_subject' => $this->post_subject,
'bbcode_bitfield' => 0,
'bbcode_uid' => '',
//'post_text' => $this->post_text,
//'post_checksum' => md5($this->post_text),
//'post_attachment' => $this->post_attachment ? 1 : 0,
'post_edit_time' => $this->post_edit_time,
'post_edit_reason' => $this->post_edit_reason,
'post_edit_user' => $this->post_edit_user,
'post_edit_count' => $this->post_edit_count,
'post_edit_locked' => $this->post_edit_locked,
'post_delete_time' => $this->post_delete_time,
'post_delete_reason' => $this->post_delete_reason,
'post_delete_user' => $this->post_delete_user,
'message' => $this->post_text,
'message_md5' => md5($this->post_text),
'enable_indexing' => $this->enable_indexing,
'notify_set' => $this->notify_set,
'notify' => $this->notify,
'topic_title' => $this->post_subject,
);
$flags = '';
generate_text_for_storage($sql_data['message'], $sql_data['bbcode_uid'], $sql_data['bbcode_bitfield'], $flags, $this->enable_bbcode, $this->enable_magic_url, $this->enable_smilies);
$topic_type = isset($this->_topic) ? $this->_topic->topic_type : POST_NORMAL;
if($this->topic_id && !$this->forum_id)
{
$sql = 'SELECT forum_id FROM ' . TOPICS_TABLE . ' WHERE topic_id = ' . $this->topic_id;
$result = $db->sql_query($sql);
$this->forum_id = $db->sql_fetchfield('forum_id');
$db->sql_freeresult($result);
if(!$this->forum_id)
{
throw(new \phpbb\exception\runtime_exception('TOPIC_NOT_EXIST'));
}
}
elseif(!$this->forum_id)
{
throw(new \phpbb\exception\runtime_exception('Neither topic_id nor forum_id given. Post cannot be created.'));
}
// Post:
if($this->post_id && $this->topic_id)
{
// Edit
$mode = 'edit';
$sql_data['post_id'] = $this->post_id;
// TODO: We need more data on topic_posts_approved, topic_posts_unapproved, topic_posts_softdeleted, topic_first_post_id, topic_last_post_id
// This is required by submit_post currently
// Somewhere it also needs forum_name in $data for the notifications
if($this->_topic == null)
{
$this->_topic = topic::from_post($this);
}
$sql = 'SELECT forum_name FROM ' . FORUMS_TABLE . ' WHERE forum_id = ' . (int) $this->forum_id;
$result = $db->sql_query($sql, 48600);
$forum_name = $db->sql_fetchfield('forum_name', false, $result);
$db->sql_freeresult($result);
$sql_data = array_merge($sql_data, array(
'topic_posts_approved' => $this->_topic->topic_posts_approved,
'topic_posts_unapproved' => $this->_topic->topic_posts_unapproved,
'topic_posts_softdeleted' => $this->_topic->topic_posts_softdeleted,
'topic_first_post_id' => $this->_topic->topic_first_post_id,
'topic_last_post_id' => $this->_topic->topic_last_post_id,
'forum_name' => $forum_name,
));
}
elseif($this->topic_id)
{
// Reply
$mode = 'reply';
}
else
{
// New Topic
$mode = 'post';
}
$poll = array();
$post_data = $this->submit_post($mode, $this->post_subject, $this->post_username, $topic_type, $poll, $sql_data);
// Re-Read topic_id and post_id:
$this->topic_id = $post_data['topic_id'];
$this->post_id = $post_data['post_id'];
//TODO
foreach($this->attachments as $attachment)
{
$attachment->post_msg_id = $this->post_id;
$attachment->topic_id = $this->topic_id;
$attachment->poster_id = $this->poster_id;
$attachment->in_message = 0;
$attachment->is_orphan = 0;
$attachment->submit();
}
} | php | function submit_without_sync($sync_not_needed = null)
{
global $config, $db, $auth, $user;
if(!$this->post_id)
{
//new post, set some default values if not set yet
if(!$this->poster_id) $this->poster_id = $user->data['user_id'];
if(!$this->poster_ip) $this->poster_ip = $user->ip;
if(!$this->post_time) $this->post_time = time();
}
$this->post_subject = truncate_string($this->post_subject);
if (!$this->post_username && $this->poster_id != ANONYMOUS)
{
if ($this->poster_id == $user->data['user_id'])
{
$this->post_username = $user->data['username'];
}
else
{
// Username is not known, fetch it
$sql = 'SELECT username FROM ' . USERS_TABLE . ' WHERE user_id = ' . (int) $this->poster_id;
$result = $db->sql_query($sql);
$username = $db->sql_fetchfield('username', false, $result);
$this->post_username = ($username ? $username : '');
}
}
$sql_data = array(
'poster_id' => $this->poster_id,
'poster_ip' => $this->poster_ip,
'topic_id' => $this->topic_id,
'forum_id' => $this->forum_id,
'post_username' => $this->post_username,
'icon_id' => $this->icon_id,
'post_time' => $this->post_time,
'post_postcount' => $this->post_postcount ? 1 : 0,
'post_visibility' => $this->post_visibility,
'post_reported' => $this->post_reported ? 1 : 0,
'enable_bbcode' => $this->enable_bbcode ? 1 : 0,
'enable_smilies' => $this->enable_smilies ? 1 : 0,
'enable_magic_url' => $this->enable_magic_url ? 1 : 0,
'enable_urls' => $this->enable_urls ? 1 : 0,
'enable_sig' => $this->enable_sig ? 1 : 0,
'post_subject' => $this->post_subject,
'bbcode_bitfield' => 0,
'bbcode_uid' => '',
//'post_text' => $this->post_text,
//'post_checksum' => md5($this->post_text),
//'post_attachment' => $this->post_attachment ? 1 : 0,
'post_edit_time' => $this->post_edit_time,
'post_edit_reason' => $this->post_edit_reason,
'post_edit_user' => $this->post_edit_user,
'post_edit_count' => $this->post_edit_count,
'post_edit_locked' => $this->post_edit_locked,
'post_delete_time' => $this->post_delete_time,
'post_delete_reason' => $this->post_delete_reason,
'post_delete_user' => $this->post_delete_user,
'message' => $this->post_text,
'message_md5' => md5($this->post_text),
'enable_indexing' => $this->enable_indexing,
'notify_set' => $this->notify_set,
'notify' => $this->notify,
'topic_title' => $this->post_subject,
);
$flags = '';
generate_text_for_storage($sql_data['message'], $sql_data['bbcode_uid'], $sql_data['bbcode_bitfield'], $flags, $this->enable_bbcode, $this->enable_magic_url, $this->enable_smilies);
$topic_type = isset($this->_topic) ? $this->_topic->topic_type : POST_NORMAL;
if($this->topic_id && !$this->forum_id)
{
$sql = 'SELECT forum_id FROM ' . TOPICS_TABLE . ' WHERE topic_id = ' . $this->topic_id;
$result = $db->sql_query($sql);
$this->forum_id = $db->sql_fetchfield('forum_id');
$db->sql_freeresult($result);
if(!$this->forum_id)
{
throw(new \phpbb\exception\runtime_exception('TOPIC_NOT_EXIST'));
}
}
elseif(!$this->forum_id)
{
throw(new \phpbb\exception\runtime_exception('Neither topic_id nor forum_id given. Post cannot be created.'));
}
// Post:
if($this->post_id && $this->topic_id)
{
// Edit
$mode = 'edit';
$sql_data['post_id'] = $this->post_id;
// TODO: We need more data on topic_posts_approved, topic_posts_unapproved, topic_posts_softdeleted, topic_first_post_id, topic_last_post_id
// This is required by submit_post currently
// Somewhere it also needs forum_name in $data for the notifications
if($this->_topic == null)
{
$this->_topic = topic::from_post($this);
}
$sql = 'SELECT forum_name FROM ' . FORUMS_TABLE . ' WHERE forum_id = ' . (int) $this->forum_id;
$result = $db->sql_query($sql, 48600);
$forum_name = $db->sql_fetchfield('forum_name', false, $result);
$db->sql_freeresult($result);
$sql_data = array_merge($sql_data, array(
'topic_posts_approved' => $this->_topic->topic_posts_approved,
'topic_posts_unapproved' => $this->_topic->topic_posts_unapproved,
'topic_posts_softdeleted' => $this->_topic->topic_posts_softdeleted,
'topic_first_post_id' => $this->_topic->topic_first_post_id,
'topic_last_post_id' => $this->_topic->topic_last_post_id,
'forum_name' => $forum_name,
));
}
elseif($this->topic_id)
{
// Reply
$mode = 'reply';
}
else
{
// New Topic
$mode = 'post';
}
$poll = array();
$post_data = $this->submit_post($mode, $this->post_subject, $this->post_username, $topic_type, $poll, $sql_data);
// Re-Read topic_id and post_id:
$this->topic_id = $post_data['topic_id'];
$this->post_id = $post_data['post_id'];
//TODO
foreach($this->attachments as $attachment)
{
$attachment->post_msg_id = $this->post_id;
$attachment->topic_id = $this->topic_id;
$attachment->poster_id = $this->poster_id;
$attachment->in_message = 0;
$attachment->is_orphan = 0;
$attachment->submit();
}
} | [
"function",
"submit_without_sync",
"(",
"$",
"sync_not_needed",
"=",
"null",
")",
"{",
"global",
"$",
"config",
",",
"$",
"db",
",",
"$",
"auth",
",",
"$",
"user",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"post_id",
")",
"{",
"//new post, set some default... | Submit the post to database - contrary to naming, this will sync. | [
"Submit",
"the",
"post",
"to",
"database",
"-",
"contrary",
"to",
"naming",
"this",
"will",
"sync",
"."
] | train | https://github.com/gn36/phpbb-oo-posting-api/blob/d0e19482a9e1e93a435c1758a66df9324145381a/src/Gn36/OoPostingApi/post.php#L221-L372 |
gn36/phpbb-oo-posting-api | src/Gn36/OoPostingApi/post.php | post.reindex | function reindex($mode, $post_id, $message, $subject, $poster_id, $forum_id)
{
global $config, $phpbb_root_path, $phpEx;
// Select the search method and do some additional checks to ensure it can actually be utilised
$search_type = basename($config['search_type']);
if (!file_exists($phpbb_root_path . 'phpbb/search/' . $search_type . '.' . $phpEx))
{
trigger_error('NO_SUCH_SEARCH_MODULE', E_USER_ERROR);
}
require_once("{$phpbb_root_path}phpbb/search/$search_type.$phpEx");
$search_type = "\\phpbb\\search\\" . $search_type;
$error = false;
$search = new $search_type($error);
if ($error)
{
trigger_error($error);
}
$search->index($mode, $post_id, $message, $subject, $poster_id, $forum_id);
} | php | function reindex($mode, $post_id, $message, $subject, $poster_id, $forum_id)
{
global $config, $phpbb_root_path, $phpEx;
// Select the search method and do some additional checks to ensure it can actually be utilised
$search_type = basename($config['search_type']);
if (!file_exists($phpbb_root_path . 'phpbb/search/' . $search_type . '.' . $phpEx))
{
trigger_error('NO_SUCH_SEARCH_MODULE', E_USER_ERROR);
}
require_once("{$phpbb_root_path}phpbb/search/$search_type.$phpEx");
$search_type = "\\phpbb\\search\\" . $search_type;
$error = false;
$search = new $search_type($error);
if ($error)
{
trigger_error($error);
}
$search->index($mode, $post_id, $message, $subject, $poster_id, $forum_id);
} | [
"function",
"reindex",
"(",
"$",
"mode",
",",
"$",
"post_id",
",",
"$",
"message",
",",
"$",
"subject",
",",
"$",
"poster_id",
",",
"$",
"forum_id",
")",
"{",
"global",
"$",
"config",
",",
"$",
"phpbb_root_path",
",",
"$",
"phpEx",
";",
"// Select the ... | Reindex post in search
@param string $mode
@param int $post_id
@param string $message
@param string $subject
@param int $poster_id
@param int $forum_id | [
"Reindex",
"post",
"in",
"search"
] | train | https://github.com/gn36/phpbb-oo-posting-api/blob/d0e19482a9e1e93a435c1758a66df9324145381a/src/Gn36/OoPostingApi/post.php#L384-L407 |
rhosocial/yii2-user | forms/ChangePasswordForm.php | ChangePasswordForm.changePassword | public function changePassword()
{
if ($this->validate()) {
if (!($user = $this->getUser())) {
return false;
}
if (!$user->applyForNewPassword()) {
return false;
}
return $user->resetPassword($this->new_password, $user->getPasswordResetToken());
}
return false;
} | php | public function changePassword()
{
if ($this->validate()) {
if (!($user = $this->getUser())) {
return false;
}
if (!$user->applyForNewPassword()) {
return false;
}
return $user->resetPassword($this->new_password, $user->getPasswordResetToken());
}
return false;
} | [
"public",
"function",
"changePassword",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"validate",
"(",
")",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"user",
"=",
"$",
"this",
"->",
"getUser",
"(",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"if"... | Change password.
@return boolean Whether the password changed. | [
"Change",
"password",
"."
] | train | https://github.com/rhosocial/yii2-user/blob/96737a9d8ca7e9c42cd2b7736d6c0a90ede6e5bc/forms/ChangePasswordForm.php#L82-L94 |
rhosocial/yii2-user | forms/ChangePasswordForm.php | ChangePasswordForm.setUser | public function setUser($user)
{
if ($user instanceof User) {
$this->_user = $user;
return true;
}
$this->_user = null;
return false;
} | php | public function setUser($user)
{
if ($user instanceof User) {
$this->_user = $user;
return true;
}
$this->_user = null;
return false;
} | [
"public",
"function",
"setUser",
"(",
"$",
"user",
")",
"{",
"if",
"(",
"$",
"user",
"instanceof",
"User",
")",
"{",
"$",
"this",
"->",
"_user",
"=",
"$",
"user",
";",
"return",
"true",
";",
"}",
"$",
"this",
"->",
"_user",
"=",
"null",
";",
"ret... | Set user.
@param User $user
@return bool | [
"Set",
"user",
"."
] | train | https://github.com/rhosocial/yii2-user/blob/96737a9d8ca7e9c42cd2b7736d6c0a90ede6e5bc/forms/ChangePasswordForm.php#L101-L109 |
php-lug/lug | src/Bundle/GridBundle/Behat/Context/GridApiContext.php | GridApiContext.assertSorting | public function assertSorting($property, $sort, $format)
{
$data = $sortedData = $this->decodeByProperty($property, $format);
array_multisort($sortedData, $sort === 'ASC' ? SORT_ASC : SORT_DESC, SORT_STRING | SORT_FLAG_CASE);
\PHPUnit_Framework_Assert::assertSame(
$sortedData,
$data,
sprintf(
'The sorting does not match for the property "%s". Expected "%s", got "%s".',
$property,
json_encode($sortedData),
json_encode($data)
)
);
} | php | public function assertSorting($property, $sort, $format)
{
$data = $sortedData = $this->decodeByProperty($property, $format);
array_multisort($sortedData, $sort === 'ASC' ? SORT_ASC : SORT_DESC, SORT_STRING | SORT_FLAG_CASE);
\PHPUnit_Framework_Assert::assertSame(
$sortedData,
$data,
sprintf(
'The sorting does not match for the property "%s". Expected "%s", got "%s".',
$property,
json_encode($sortedData),
json_encode($data)
)
);
} | [
"public",
"function",
"assertSorting",
"(",
"$",
"property",
",",
"$",
"sort",
",",
"$",
"format",
")",
"{",
"$",
"data",
"=",
"$",
"sortedData",
"=",
"$",
"this",
"->",
"decodeByProperty",
"(",
"$",
"property",
",",
"$",
"format",
")",
";",
"array_mul... | @param string $property
@param string $sort
@param string $format
@Given the ":format" response should be sorted by ":property" ":sort" | [
"@param",
"string",
"$property",
"@param",
"string",
"$sort",
"@param",
"string",
"$format"
] | train | https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/GridBundle/Behat/Context/GridApiContext.php#L57-L73 |
php-lug/lug | src/Bundle/GridBundle/Behat/Context/GridApiContext.php | GridApiContext.assertResponseFiltering | public function assertResponseFiltering($property, $values, $format)
{
\PHPUnit_Framework_Assert::assertSame(
$expected = !empty($values) ? array_map('trim', explode(';', $values)) : [],
$data = $this->decodeByProperty($property, $format),
sprintf(
'The filtering does not match for the property "%s". Expected "%s", got "%s".',
$property,
json_encode($expected),
json_encode($data)
)
);
} | php | public function assertResponseFiltering($property, $values, $format)
{
\PHPUnit_Framework_Assert::assertSame(
$expected = !empty($values) ? array_map('trim', explode(';', $values)) : [],
$data = $this->decodeByProperty($property, $format),
sprintf(
'The filtering does not match for the property "%s". Expected "%s", got "%s".',
$property,
json_encode($expected),
json_encode($data)
)
);
} | [
"public",
"function",
"assertResponseFiltering",
"(",
"$",
"property",
",",
"$",
"values",
",",
"$",
"format",
")",
"{",
"\\",
"PHPUnit_Framework_Assert",
"::",
"assertSame",
"(",
"$",
"expected",
"=",
"!",
"empty",
"(",
"$",
"values",
")",
"?",
"array_map",... | @param string $property
@param string $values
@param string $format
@Given the ":format" response should be filtered by ":property" ":values" | [
"@param",
"string",
"$property",
"@param",
"string",
"$values",
"@param",
"string",
"$format"
] | train | https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/GridBundle/Behat/Context/GridApiContext.php#L82-L94 |
php-lug/lug | src/Bundle/GridBundle/Behat/Context/GridApiContext.php | GridApiContext.decodeByProperty | private function decodeByProperty($property, $format)
{
return array_map(function ($entry) use ($property) {
\PHPUnit_Framework_Assert::assertInternalType('array', $entry);
\PHPUnit_Framework_Assert::assertArrayHasKey($property, $entry);
return $entry[$property];
}, $this->decode($format));
} | php | private function decodeByProperty($property, $format)
{
return array_map(function ($entry) use ($property) {
\PHPUnit_Framework_Assert::assertInternalType('array', $entry);
\PHPUnit_Framework_Assert::assertArrayHasKey($property, $entry);
return $entry[$property];
}, $this->decode($format));
} | [
"private",
"function",
"decodeByProperty",
"(",
"$",
"property",
",",
"$",
"format",
")",
"{",
"return",
"array_map",
"(",
"function",
"(",
"$",
"entry",
")",
"use",
"(",
"$",
"property",
")",
"{",
"\\",
"PHPUnit_Framework_Assert",
"::",
"assertInternalType",
... | @param string $property
@param string $format
@return mixed[] | [
"@param",
"string",
"$property",
"@param",
"string",
"$format"
] | train | https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/GridBundle/Behat/Context/GridApiContext.php#L102-L110 |
php-lug/lug | src/Bundle/GridBundle/Behat/Context/GridApiContext.php | GridApiContext.decode | private function decode($format)
{
$data = $this->decoder->decode((string) $this->apiContext->getResponse()->getBody(), $format);
if ($format === 'json' && isset($data['_embedded']['items'])) {
$data = $data['_embedded']['items'];
}
if ($format === 'xml') {
if (!empty($data) && isset($data['entry'])) {
if (is_int(key($data['entry']))) {
$data = $data['entry'];
} elseif (isset($data['entry']['@rel'])) {
$data = array_pop($data['entry']);
} else {
$data = [$data['entry']];
}
} else {
$data = [];
}
}
return $data;
} | php | private function decode($format)
{
$data = $this->decoder->decode((string) $this->apiContext->getResponse()->getBody(), $format);
if ($format === 'json' && isset($data['_embedded']['items'])) {
$data = $data['_embedded']['items'];
}
if ($format === 'xml') {
if (!empty($data) && isset($data['entry'])) {
if (is_int(key($data['entry']))) {
$data = $data['entry'];
} elseif (isset($data['entry']['@rel'])) {
$data = array_pop($data['entry']);
} else {
$data = [$data['entry']];
}
} else {
$data = [];
}
}
return $data;
} | [
"private",
"function",
"decode",
"(",
"$",
"format",
")",
"{",
"$",
"data",
"=",
"$",
"this",
"->",
"decoder",
"->",
"decode",
"(",
"(",
"string",
")",
"$",
"this",
"->",
"apiContext",
"->",
"getResponse",
"(",
")",
"->",
"getBody",
"(",
")",
",",
... | @param $format
@return array|mixed | [
"@param",
"$format"
] | train | https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/GridBundle/Behat/Context/GridApiContext.php#L117-L140 |
petrica/php-statsd-system | Gauge/MemoryGauge.php | MemoryGauge.getCollection | public function getCollection()
{
$collection = new ValuesCollection();
$info = $this->getSystemMemoryInfo();
if (!empty($info) &&
isset($info['MemTotal']) &&
isset($info['MemFree'])) {
$collection->add('total.value', $info['MemTotal']);
$collection->add('free.value', $info['MemFree']);
$collection->add('used.value', $this->getUsedMemory($info));
}
return $collection;
} | php | public function getCollection()
{
$collection = new ValuesCollection();
$info = $this->getSystemMemoryInfo();
if (!empty($info) &&
isset($info['MemTotal']) &&
isset($info['MemFree'])) {
$collection->add('total.value', $info['MemTotal']);
$collection->add('free.value', $info['MemFree']);
$collection->add('used.value', $this->getUsedMemory($info));
}
return $collection;
} | [
"public",
"function",
"getCollection",
"(",
")",
"{",
"$",
"collection",
"=",
"new",
"ValuesCollection",
"(",
")",
";",
"$",
"info",
"=",
"$",
"this",
"->",
"getSystemMemoryInfo",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"info",
")",
"&&",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/petrica/php-statsd-system/blob/c476be3514a631a605737888bb8f6eb096789c9d/Gauge/MemoryGauge.php#L27-L43 |
petrica/php-statsd-system | Gauge/MemoryGauge.php | MemoryGauge.getSystemMemoryInfo | protected function getSystemMemoryInfo()
{
$meminfo = array();
if (file_exists(static::MEMINFO_PATH)) {
$data = explode("\n", file_get_contents(static::MEMINFO_PATH));
$meminfo = array();
foreach ($data as $line) {
if (!empty($line)) {
list($key, $val) = explode(":", $line);
$meminfo[$key] = intval($val);
}
}
}
return $meminfo;
} | php | protected function getSystemMemoryInfo()
{
$meminfo = array();
if (file_exists(static::MEMINFO_PATH)) {
$data = explode("\n", file_get_contents(static::MEMINFO_PATH));
$meminfo = array();
foreach ($data as $line) {
if (!empty($line)) {
list($key, $val) = explode(":", $line);
$meminfo[$key] = intval($val);
}
}
}
return $meminfo;
} | [
"protected",
"function",
"getSystemMemoryInfo",
"(",
")",
"{",
"$",
"meminfo",
"=",
"array",
"(",
")",
";",
"if",
"(",
"file_exists",
"(",
"static",
"::",
"MEMINFO_PATH",
")",
")",
"{",
"$",
"data",
"=",
"explode",
"(",
"\"\\n\"",
",",
"file_get_contents",... | Only for linux/unix OS
@return array | [
"Only",
"for",
"linux",
"/",
"unix",
"OS"
] | train | https://github.com/petrica/php-statsd-system/blob/c476be3514a631a605737888bb8f6eb096789c9d/Gauge/MemoryGauge.php#L50-L67 |
sauls/widget | src/View/PhpFileView.php | PhpFileView.resolveViewFile | private function resolveViewFile(string $viewFile): string
{
try {
if (file_exists($viewFile)) {
return $viewFile;
}
$this->checkTemplatesDirectoryExists();
return $this->resolveTemplateFile($viewFile);
} catch (\Exception $e) {
throw new \RuntimeException($e->getMessage());
} catch (\Throwable $t) {
throw new \RuntimeException(
sprintf(
'Template %s was not found. Looked in %s',
$viewFile,
implode(',', $this->templatesDirectories))
);
}
} | php | private function resolveViewFile(string $viewFile): string
{
try {
if (file_exists($viewFile)) {
return $viewFile;
}
$this->checkTemplatesDirectoryExists();
return $this->resolveTemplateFile($viewFile);
} catch (\Exception $e) {
throw new \RuntimeException($e->getMessage());
} catch (\Throwable $t) {
throw new \RuntimeException(
sprintf(
'Template %s was not found. Looked in %s',
$viewFile,
implode(',', $this->templatesDirectories))
);
}
} | [
"private",
"function",
"resolveViewFile",
"(",
"string",
"$",
"viewFile",
")",
":",
"string",
"{",
"try",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"viewFile",
")",
")",
"{",
"return",
"$",
"viewFile",
";",
"}",
"$",
"this",
"->",
"checkTemplatesDirectoryEx... | @param string $viewFile
@return string
@throws \RuntimeException | [
"@param",
"string",
"$viewFile"
] | train | https://github.com/sauls/widget/blob/552c8118e92565f3f54969779269855b6a1d076a/src/View/PhpFileView.php#L58-L80 |
php-lug/lug | src/Bundle/ResourceBundle/Form/Extension/XmlHttpRequestExtension.php | XmlHttpRequestExtension.buildForm | public function buildForm(FormBuilderInterface $builder, array $options)
{
if (!$options['xml_http_request'] || $options['xml_http_request_trigger']) {
return;
}
$builder
->add('_xml_http_request', HiddenType::class, ['mapped' => false, 'error_bubbling' => false])
->addEventSubscriber($this->xmlHttpRequestSubscriber);
} | php | public function buildForm(FormBuilderInterface $builder, array $options)
{
if (!$options['xml_http_request'] || $options['xml_http_request_trigger']) {
return;
}
$builder
->add('_xml_http_request', HiddenType::class, ['mapped' => false, 'error_bubbling' => false])
->addEventSubscriber($this->xmlHttpRequestSubscriber);
} | [
"public",
"function",
"buildForm",
"(",
"FormBuilderInterface",
"$",
"builder",
",",
"array",
"$",
"options",
")",
"{",
"if",
"(",
"!",
"$",
"options",
"[",
"'xml_http_request'",
"]",
"||",
"$",
"options",
"[",
"'xml_http_request_trigger'",
"]",
")",
"{",
"r... | {@inheritdoc} | [
"{"
] | train | https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/ResourceBundle/Form/Extension/XmlHttpRequestExtension.php#L44-L53 |
InfiniteSoftware/ISEcommpayPayum | Action/AuthorizeAction.php | AuthorizeAction.execute | public function execute($request)
{
RequestNotSupportedException::assertSupports($this, $request);
$model = ArrayObject::ensureArrayObject($request->getModel());
$request = $model->get('request');
$signature = $request['signature'];
unset($request['signature']);
$mySignature = Signer::sign($request, $this->api['secretKey']);
if ($mySignature !== $signature) {
$this->logger->critical('Ecommpay payment signature is invalid');
throw new BadRequestHttpException();
}
} | php | public function execute($request)
{
RequestNotSupportedException::assertSupports($this, $request);
$model = ArrayObject::ensureArrayObject($request->getModel());
$request = $model->get('request');
$signature = $request['signature'];
unset($request['signature']);
$mySignature = Signer::sign($request, $this->api['secretKey']);
if ($mySignature !== $signature) {
$this->logger->critical('Ecommpay payment signature is invalid');
throw new BadRequestHttpException();
}
} | [
"public",
"function",
"execute",
"(",
"$",
"request",
")",
"{",
"RequestNotSupportedException",
"::",
"assertSupports",
"(",
"$",
"this",
",",
"$",
"request",
")",
";",
"$",
"model",
"=",
"ArrayObject",
"::",
"ensureArrayObject",
"(",
"$",
"request",
"->",
"... | {@inheritDoc}
@param Authorize $request | [
"{",
"@inheritDoc",
"}"
] | train | https://github.com/InfiniteSoftware/ISEcommpayPayum/blob/44a073e3d885d9007aa54d6ff13aea93a9e52e7c/Action/AuthorizeAction.php#L46-L60 |
DeprecatedPackages/EventDispatcher | src/DI/EventDispatcherExtension.php | EventDispatcherExtension.loadConfiguration | public function loadConfiguration()
{
if ($this->isKdybyEventsRegistered()) {
return;
}
$containerBuilder = $this->getContainerBuilder();
$containerBuilder->addDefinition($this->prefix('eventDispatcher'))
->setClass(EventDispatcher::class);
} | php | public function loadConfiguration()
{
if ($this->isKdybyEventsRegistered()) {
return;
}
$containerBuilder = $this->getContainerBuilder();
$containerBuilder->addDefinition($this->prefix('eventDispatcher'))
->setClass(EventDispatcher::class);
} | [
"public",
"function",
"loadConfiguration",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isKdybyEventsRegistered",
"(",
")",
")",
"{",
"return",
";",
"}",
"$",
"containerBuilder",
"=",
"$",
"this",
"->",
"getContainerBuilder",
"(",
")",
";",
"$",
"containe... | {@inheritdoc} | [
"{"
] | train | https://github.com/DeprecatedPackages/EventDispatcher/blob/1359bb86e208626578bd7049b48bfb8a25d57b64/src/DI/EventDispatcherExtension.php#L25-L34 |
DeprecatedPackages/EventDispatcher | src/DI/EventDispatcherExtension.php | EventDispatcherExtension.beforeCompile | public function beforeCompile()
{
$eventDispatcher = $this->getDefinitionByType(EventDispatcherInterface::class);
if ($this->isKdybyEventsRegistered()) {
$eventDispatcher->setClass(EventDispatcher::class)
->setFactory(NULL);
}
$this->addSubscribersToEventDispatcher();
$this->bindNetteEvents();
$this->bindEventDispatcherToSymfonyConsole();
} | php | public function beforeCompile()
{
$eventDispatcher = $this->getDefinitionByType(EventDispatcherInterface::class);
if ($this->isKdybyEventsRegistered()) {
$eventDispatcher->setClass(EventDispatcher::class)
->setFactory(NULL);
}
$this->addSubscribersToEventDispatcher();
$this->bindNetteEvents();
$this->bindEventDispatcherToSymfonyConsole();
} | [
"public",
"function",
"beforeCompile",
"(",
")",
"{",
"$",
"eventDispatcher",
"=",
"$",
"this",
"->",
"getDefinitionByType",
"(",
"EventDispatcherInterface",
"::",
"class",
")",
";",
"if",
"(",
"$",
"this",
"->",
"isKdybyEventsRegistered",
"(",
")",
")",
"{",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/DeprecatedPackages/EventDispatcher/blob/1359bb86e208626578bd7049b48bfb8a25d57b64/src/DI/EventDispatcherExtension.php#L40-L52 |
nabab/bbn | src/bbn/appui/imessages.php | imessages.from_notes | private function from_notes(array $messages, $simple = true){
if ( !empty($messages) ){
foreach ( $messages as $idx => $mess ){
if ( empty($mess['id_note']) ){
unset($messages[$idx]);
continue;
}
$note = $this->notes->get($mess['id_note']);
$note = [
'id' => $mess['id'],
'title' => $note['title'],
'content' => $note['content']
];
if ( $simple ){
$messages[$idx] = $note;
}
else {
$messages[$idx] = \bbn\x::merge_arrays($messages[$idx], $note);
}
}
}
return $messages;
} | php | private function from_notes(array $messages, $simple = true){
if ( !empty($messages) ){
foreach ( $messages as $idx => $mess ){
if ( empty($mess['id_note']) ){
unset($messages[$idx]);
continue;
}
$note = $this->notes->get($mess['id_note']);
$note = [
'id' => $mess['id'],
'title' => $note['title'],
'content' => $note['content']
];
if ( $simple ){
$messages[$idx] = $note;
}
else {
$messages[$idx] = \bbn\x::merge_arrays($messages[$idx], $note);
}
}
}
return $messages;
} | [
"private",
"function",
"from_notes",
"(",
"array",
"$",
"messages",
",",
"$",
"simple",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"messages",
")",
")",
"{",
"foreach",
"(",
"$",
"messages",
"as",
"$",
"idx",
"=>",
"$",
"mess",
")",
... | Gets internal messages' info from notes archive
@param array $messages
@param bool $simple
@return array | [
"Gets",
"internal",
"messages",
"info",
"from",
"notes",
"archive"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/imessages.php#L85-L107 |
nabab/bbn | src/bbn/appui/imessages.php | imessages.insert | public function insert($imess){
$cfg =& $this->class_cfg;
// Get default page if it isn't set
if ( empty($imess['id_option']) ){
$perm = new \bbn\user\permissions();
$imess['id_option'] = $perm->is(self::BBN_DEFAULT_PERM);
}
if (
!empty($imess['id_option']) &&
!empty($imess['title']) &&
!empty($imess['content']) &&
!empty($this->_id_type()) &&
// Insert the new note
($id_note = $this->notes->insert($imess['title'], $imess['content'], $this->_id_type())) &&
// Insert the new internal message
$this->db->insert($cfg['table'], [
$cfg['arch']['imessages']['id_note'] => $id_note,
$cfg['arch']['imessages']['id_option'] => $imess['id_option'],
$cfg['arch']['imessages']['id_user'] => $imess['id_user'] ?: NULL,
$cfg['arch']['imessages']['id_group'] => $imess['id_group'] ?: NULL,
$cfg['arch']['imessages']['start'] => $imess['start'] ?: NULL,
$cfg['arch']['imessages']['end'] => $imess['end'] ?: NULL
])
){
return $this->db->last_id();
}
return false;
} | php | public function insert($imess){
$cfg =& $this->class_cfg;
// Get default page if it isn't set
if ( empty($imess['id_option']) ){
$perm = new \bbn\user\permissions();
$imess['id_option'] = $perm->is(self::BBN_DEFAULT_PERM);
}
if (
!empty($imess['id_option']) &&
!empty($imess['title']) &&
!empty($imess['content']) &&
!empty($this->_id_type()) &&
// Insert the new note
($id_note = $this->notes->insert($imess['title'], $imess['content'], $this->_id_type())) &&
// Insert the new internal message
$this->db->insert($cfg['table'], [
$cfg['arch']['imessages']['id_note'] => $id_note,
$cfg['arch']['imessages']['id_option'] => $imess['id_option'],
$cfg['arch']['imessages']['id_user'] => $imess['id_user'] ?: NULL,
$cfg['arch']['imessages']['id_group'] => $imess['id_group'] ?: NULL,
$cfg['arch']['imessages']['start'] => $imess['start'] ?: NULL,
$cfg['arch']['imessages']['end'] => $imess['end'] ?: NULL
])
){
return $this->db->last_id();
}
return false;
} | [
"public",
"function",
"insert",
"(",
"$",
"imess",
")",
"{",
"$",
"cfg",
"=",
"&",
"$",
"this",
"->",
"class_cfg",
";",
"// Get default page if it isn't set",
"if",
"(",
"empty",
"(",
"$",
"imess",
"[",
"'id_option'",
"]",
")",
")",
"{",
"$",
"perm",
"... | Inserts a new page's internal message
@param $imess
@return bool|int | [
"Inserts",
"a",
"new",
"page",
"s",
"internal",
"message"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/imessages.php#L126-L153 |
nabab/bbn | src/bbn/appui/imessages.php | imessages.get | public function get(string $id_option, string $id_user, $simple = true){
$cfg =& $this->class_cfg;
// Current datetime
$now = date('Y-m-d H:i:s');
// Get the user's group
$id_group = $this->db->select_one('bbn_users', 'id_group', ['id' => $id_user]);
// Get the page's internal messages of the user
$messages = $this->db->get_rows("
SELECT {$cfg['table']}.*
FROM {$cfg['tables']['users']}
RIGHT JOIN {$cfg['table']}
ON {$cfg['table']}.{$cfg['arch']['imessages']['id']} = {$cfg['tables']['users']}.{$cfg['arch']['users']['id_imessage']}
WHERE (
{$cfg['table']}.{$cfg['arch']['imessages']['start']} IS NULL
OR {$cfg['table']}.{$cfg['arch']['imessages']['start']} <= ?
)
AND (
{$cfg['table']}.{$cfg['arch']['imessages']['end']} IS NULL
OR {$cfg['table']}.{$cfg['arch']['imessages']['end']} > ?
)
AND (
{$cfg['table']}.{$cfg['arch']['imessages']['id_user']} = ?
OR {$cfg['table']}.{$cfg['arch']['imessages']['id_group']} = ?
OR (
{$cfg['table']}.{$cfg['arch']['imessages']['id_user']} IS NULL
AND {$cfg['table']}.{$cfg['arch']['imessages']['id_group']} IS NULL
)
)
AND {$cfg['table']}.{$cfg['arch']['imessages']['id_option']} = ?
AND (
{$cfg['tables']['users']}.{$cfg['arch']['users']['hidden']} IS NULL
OR {$cfg['tables']['users']}.{$cfg['arch']['users']['hidden']} = 0
)",
$now,
$now,
hex2bin($id_user),
hex2bin($id_group),
hex2bin($id_option)
);
// Get and return the imessage's content|title from notes archive
return $this->from_notes($messages, $simple);
} | php | public function get(string $id_option, string $id_user, $simple = true){
$cfg =& $this->class_cfg;
// Current datetime
$now = date('Y-m-d H:i:s');
// Get the user's group
$id_group = $this->db->select_one('bbn_users', 'id_group', ['id' => $id_user]);
// Get the page's internal messages of the user
$messages = $this->db->get_rows("
SELECT {$cfg['table']}.*
FROM {$cfg['tables']['users']}
RIGHT JOIN {$cfg['table']}
ON {$cfg['table']}.{$cfg['arch']['imessages']['id']} = {$cfg['tables']['users']}.{$cfg['arch']['users']['id_imessage']}
WHERE (
{$cfg['table']}.{$cfg['arch']['imessages']['start']} IS NULL
OR {$cfg['table']}.{$cfg['arch']['imessages']['start']} <= ?
)
AND (
{$cfg['table']}.{$cfg['arch']['imessages']['end']} IS NULL
OR {$cfg['table']}.{$cfg['arch']['imessages']['end']} > ?
)
AND (
{$cfg['table']}.{$cfg['arch']['imessages']['id_user']} = ?
OR {$cfg['table']}.{$cfg['arch']['imessages']['id_group']} = ?
OR (
{$cfg['table']}.{$cfg['arch']['imessages']['id_user']} IS NULL
AND {$cfg['table']}.{$cfg['arch']['imessages']['id_group']} IS NULL
)
)
AND {$cfg['table']}.{$cfg['arch']['imessages']['id_option']} = ?
AND (
{$cfg['tables']['users']}.{$cfg['arch']['users']['hidden']} IS NULL
OR {$cfg['tables']['users']}.{$cfg['arch']['users']['hidden']} = 0
)",
$now,
$now,
hex2bin($id_user),
hex2bin($id_group),
hex2bin($id_option)
);
// Get and return the imessage's content|title from notes archive
return $this->from_notes($messages, $simple);
} | [
"public",
"function",
"get",
"(",
"string",
"$",
"id_option",
",",
"string",
"$",
"id_user",
",",
"$",
"simple",
"=",
"true",
")",
"{",
"$",
"cfg",
"=",
"&",
"$",
"this",
"->",
"class_cfg",
";",
"// Current datetime",
"$",
"now",
"=",
"date",
"(",
"'... | Gets the page's internal messages of an user
@param string $id_option
@param string $id_user
@param bool $simple
@return array | [
"Gets",
"the",
"page",
"s",
"internal",
"messages",
"of",
"an",
"user"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/imessages.php#L163-L204 |
nabab/bbn | src/bbn/appui/imessages.php | imessages.set_hidden | public function set_hidden(string $id_imess, string $id_user){
$cfg =& $this->class_cfg;
if ( !empty($id_imess) && !empty($id_user) ){
return !!$this->db->insert_update($cfg['tables']['users'], [
$cfg['arch']['users']['id_imessage'] => $id_imess,
$cfg['arch']['users']['id_user'] => $id_user,
$cfg['arch']['users']['hidden'] => 1,
$cfg['arch']['users']['moment'] => date('Y-m-d H:i:s'),
], [
$cfg['arch']['users']['id_imessage'] => $id_imess,
$cfg['arch']['users']['id_user'] => $id_user
]);
}
return false;
} | php | public function set_hidden(string $id_imess, string $id_user){
$cfg =& $this->class_cfg;
if ( !empty($id_imess) && !empty($id_user) ){
return !!$this->db->insert_update($cfg['tables']['users'], [
$cfg['arch']['users']['id_imessage'] => $id_imess,
$cfg['arch']['users']['id_user'] => $id_user,
$cfg['arch']['users']['hidden'] => 1,
$cfg['arch']['users']['moment'] => date('Y-m-d H:i:s'),
], [
$cfg['arch']['users']['id_imessage'] => $id_imess,
$cfg['arch']['users']['id_user'] => $id_user
]);
}
return false;
} | [
"public",
"function",
"set_hidden",
"(",
"string",
"$",
"id_imess",
",",
"string",
"$",
"id_user",
")",
"{",
"$",
"cfg",
"=",
"&",
"$",
"this",
"->",
"class_cfg",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"id_imess",
")",
"&&",
"!",
"empty",
"(",
"$"... | Sets an user's internal message as visible
@param string $id_imess
@param string $id_user
@return bool | [
"Sets",
"an",
"user",
"s",
"internal",
"message",
"as",
"visible"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/imessages.php#L213-L227 |
nabab/bbn | src/bbn/appui/imessages.php | imessages.unset_hidden | public function unset_hidden(string $id_imess, string $id_user){
$cfg =& $this->class_cfg;
if ( !empty($id_imess) && !empty($id_user) ){
return !!$this->db->update_ignore($cfg['tables']['users'], [
$cfg['arch']['users']['id_imessage'] => $id_imess,
$cfg['arch']['users']['id_user'] => $id_user,
$cfg['arch']['users']['hidden'] => 0,
$cfg['arch']['users']['moment'] => date('Y-m-d H:i:s'),
], [
$cfg['arch']['users']['id_imessage'] => $id_imess,
$cfg['arch']['users']['id_user'] => $id_user
]);
}
return false;
} | php | public function unset_hidden(string $id_imess, string $id_user){
$cfg =& $this->class_cfg;
if ( !empty($id_imess) && !empty($id_user) ){
return !!$this->db->update_ignore($cfg['tables']['users'], [
$cfg['arch']['users']['id_imessage'] => $id_imess,
$cfg['arch']['users']['id_user'] => $id_user,
$cfg['arch']['users']['hidden'] => 0,
$cfg['arch']['users']['moment'] => date('Y-m-d H:i:s'),
], [
$cfg['arch']['users']['id_imessage'] => $id_imess,
$cfg['arch']['users']['id_user'] => $id_user
]);
}
return false;
} | [
"public",
"function",
"unset_hidden",
"(",
"string",
"$",
"id_imess",
",",
"string",
"$",
"id_user",
")",
"{",
"$",
"cfg",
"=",
"&",
"$",
"this",
"->",
"class_cfg",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"id_imess",
")",
"&&",
"!",
"empty",
"(",
"... | Sets an user's internal message as not visible
@param string $id_imess
@param string $id_user
@return bool | [
"Sets",
"an",
"user",
"s",
"internal",
"message",
"as",
"not",
"visible"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/imessages.php#L236-L250 |
nabab/bbn | src/bbn/appui/imessages.php | imessages.get_by_user | public function get_by_user(string $id_user){
$cfg =& $this->class_cfg;
// Current datetime
$now = date('Y-m-d H:i:s');
// Get the user's group
$id_group = $this->db->select_one('bbn_users', 'id_group', ['id' => $id_user]);
// Get all user's internal messages
$messages = $this->db->get_rows("
SELECT {$cfg['table']}.*
FROM {$cfg['tables']['users']}
RIGHT JOIN {$cfg['table']}
ON {$cfg['table']}.{$cfg['arch']['imessages']['id_user']} = {$cfg['tables']['users']}.{$cfg['arch']['users']['id_user']}
AND {$cfg['table']}.{$cfg['arch']['imessages']['id']} = {$cfg['tables']['users']}.{$cfg['arch']['users']['id_imessage']}
WHERE (
{$cfg['table']}.{$cfg['arch']['imessages']['start']} IS NULL
OR {$cfg['table']}.{$cfg['arch']['imessages']['start']} <= ?
)
AND (
{$cfg['table']}.{$cfg['arch']['imessages']['end']} IS NULL
OR {$cfg['table']}.{$cfg['arch']['imessages']['end']} > ?
)
AND (
(
{$cfg['table']}.{$cfg['arch']['imessages']['id_user']} = ?
OR {$cfg['table']}.{$cfg['arch']['imessages']['id_group']} = ?
)
OR (
{$cfg['table']}.{$cfg['arch']['imessages']['id_user']} IS NULL
OR {$cfg['table']}.{$cfg['arch']['imessages']['id_group']} IS NULL
)
)
AND (
{$cfg['tables']['users']}.{$cfg['arch']['users']['hidden']} IS NULL
OR {$cfg['tables']['users']}.{$cfg['arch']['users']['hidden']} = 0
)",
$now,
$now,
hex2bin($id_user),
hex2bin($id_group)
);
// Get and return the imessage's info from notes archive
return $this->from_notes($messages);
} | php | public function get_by_user(string $id_user){
$cfg =& $this->class_cfg;
// Current datetime
$now = date('Y-m-d H:i:s');
// Get the user's group
$id_group = $this->db->select_one('bbn_users', 'id_group', ['id' => $id_user]);
// Get all user's internal messages
$messages = $this->db->get_rows("
SELECT {$cfg['table']}.*
FROM {$cfg['tables']['users']}
RIGHT JOIN {$cfg['table']}
ON {$cfg['table']}.{$cfg['arch']['imessages']['id_user']} = {$cfg['tables']['users']}.{$cfg['arch']['users']['id_user']}
AND {$cfg['table']}.{$cfg['arch']['imessages']['id']} = {$cfg['tables']['users']}.{$cfg['arch']['users']['id_imessage']}
WHERE (
{$cfg['table']}.{$cfg['arch']['imessages']['start']} IS NULL
OR {$cfg['table']}.{$cfg['arch']['imessages']['start']} <= ?
)
AND (
{$cfg['table']}.{$cfg['arch']['imessages']['end']} IS NULL
OR {$cfg['table']}.{$cfg['arch']['imessages']['end']} > ?
)
AND (
(
{$cfg['table']}.{$cfg['arch']['imessages']['id_user']} = ?
OR {$cfg['table']}.{$cfg['arch']['imessages']['id_group']} = ?
)
OR (
{$cfg['table']}.{$cfg['arch']['imessages']['id_user']} IS NULL
OR {$cfg['table']}.{$cfg['arch']['imessages']['id_group']} IS NULL
)
)
AND (
{$cfg['tables']['users']}.{$cfg['arch']['users']['hidden']} IS NULL
OR {$cfg['tables']['users']}.{$cfg['arch']['users']['hidden']} = 0
)",
$now,
$now,
hex2bin($id_user),
hex2bin($id_group)
);
// Get and return the imessage's info from notes archive
return $this->from_notes($messages);
} | [
"public",
"function",
"get_by_user",
"(",
"string",
"$",
"id_user",
")",
"{",
"$",
"cfg",
"=",
"&",
"$",
"this",
"->",
"class_cfg",
";",
"// Current datetime",
"$",
"now",
"=",
"date",
"(",
"'Y-m-d H:i:s'",
")",
";",
"// Get the user's group",
"$",
"id_group... | Gets all user's internal messages
@param string $id_user
@return array | [
"Gets",
"all",
"user",
"s",
"internal",
"messages"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/imessages.php#L271-L313 |
weew/http | src/Weew/Http/DataSerializer.php | DataSerializer.serialize | public function serialize($data) {
if (is_array($data)) {
return $this->serializeArray($data);
} else if (is_object($data)) {
return $this->serializeItem($data);
}
return $data;
} | php | public function serialize($data) {
if (is_array($data)) {
return $this->serializeArray($data);
} else if (is_object($data)) {
return $this->serializeItem($data);
}
return $data;
} | [
"public",
"function",
"serialize",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"data",
")",
")",
"{",
"return",
"$",
"this",
"->",
"serializeArray",
"(",
"$",
"data",
")",
";",
"}",
"else",
"if",
"(",
"is_object",
"(",
"$",
"data",... | @param $data
@return array|string | [
"@param",
"$data"
] | train | https://github.com/weew/http/blob/fd34d3d5643ca01c8e0946e888224a8e8dcc3c0d/src/Weew/Http/DataSerializer.php#L15-L23 |
weew/http | src/Weew/Http/DataSerializer.php | DataSerializer.serializeArray | protected function serializeArray(array $array) {
$data = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$data[$key] = $this->serializeArray($value);
} else {
$data[$key] = $this->serializeItem($value);
}
}
return $data;
} | php | protected function serializeArray(array $array) {
$data = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$data[$key] = $this->serializeArray($value);
} else {
$data[$key] = $this->serializeItem($value);
}
}
return $data;
} | [
"protected",
"function",
"serializeArray",
"(",
"array",
"$",
"array",
")",
"{",
"$",
"data",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"array",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{... | @param array $array
@return array | [
"@param",
"array",
"$array"
] | train | https://github.com/weew/http/blob/fd34d3d5643ca01c8e0946e888224a8e8dcc3c0d/src/Weew/Http/DataSerializer.php#L30-L42 |
weew/http | src/Weew/Http/DataSerializer.php | DataSerializer.serializeItem | protected function serializeItem($data) {
if ($data instanceof IArrayable) {
return $data->toArray();
} else if ($data instanceof IJsonable) {
return $data->toJson();
} else if ($data instanceof IStringable) {
return $data->toString();
}
return $data;
} | php | protected function serializeItem($data) {
if ($data instanceof IArrayable) {
return $data->toArray();
} else if ($data instanceof IJsonable) {
return $data->toJson();
} else if ($data instanceof IStringable) {
return $data->toString();
}
return $data;
} | [
"protected",
"function",
"serializeItem",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"$",
"data",
"instanceof",
"IArrayable",
")",
"{",
"return",
"$",
"data",
"->",
"toArray",
"(",
")",
";",
"}",
"else",
"if",
"(",
"$",
"data",
"instanceof",
"IJsonable",
"... | @param $data
@return array|string | [
"@param",
"$data"
] | train | https://github.com/weew/http/blob/fd34d3d5643ca01c8e0946e888224a8e8dcc3c0d/src/Weew/Http/DataSerializer.php#L49-L59 |
welderlourenco/laravel-facebook | src/WelderLourenco/Facebook/Providers/FacebookServiceProvider.php | FacebookServiceProvider.register | public function register()
{
$this->app['facebook'] = $this->app->share(function($app)
{
return new Facebook;
});
$this->app['config']->package('welderlourenco/laravel-facebook', __DIR__ . '/../../../config');
} | php | public function register()
{
$this->app['facebook'] = $this->app->share(function($app)
{
return new Facebook;
});
$this->app['config']->package('welderlourenco/laravel-facebook', __DIR__ . '/../../../config');
} | [
"public",
"function",
"register",
"(",
")",
"{",
"$",
"this",
"->",
"app",
"[",
"'facebook'",
"]",
"=",
"$",
"this",
"->",
"app",
"->",
"share",
"(",
"function",
"(",
"$",
"app",
")",
"{",
"return",
"new",
"Facebook",
";",
"}",
")",
";",
"$",
"th... | Register the service provider.
@return void | [
"Register",
"the",
"service",
"provider",
"."
] | train | https://github.com/welderlourenco/laravel-facebook/blob/e0c80ab5ff1c95b634da8c15a5fd3c00ded232dd/src/WelderLourenco/Facebook/Providers/FacebookServiceProvider.php#L31-L39 |
glynnforrest/active-doctrine | src/ActiveDoctrine/Entity/Traits/SlugTrait.php | SlugTrait.initSlugTrait | public function initSlugTrait()
{
$slugs = isset(static::$slugs) ? static::$slugs : ['title' => 'slug'];
$slugger = function ($entity) use ($slugs) {
foreach ($slugs as $column => $slug_column) {
//do nothing if the slug has been manually modified
if (in_array($slug_column, $entity->getModifiedFields())) {
continue;
}
$entity->setRaw($slug_column, $this->slugify($entity->getRaw($column)));
}
};
$this->addEventCallBack('insert', $slugger);
$this->addEventCallBack('update', $slugger);
} | php | public function initSlugTrait()
{
$slugs = isset(static::$slugs) ? static::$slugs : ['title' => 'slug'];
$slugger = function ($entity) use ($slugs) {
foreach ($slugs as $column => $slug_column) {
//do nothing if the slug has been manually modified
if (in_array($slug_column, $entity->getModifiedFields())) {
continue;
}
$entity->setRaw($slug_column, $this->slugify($entity->getRaw($column)));
}
};
$this->addEventCallBack('insert', $slugger);
$this->addEventCallBack('update', $slugger);
} | [
"public",
"function",
"initSlugTrait",
"(",
")",
"{",
"$",
"slugs",
"=",
"isset",
"(",
"static",
"::",
"$",
"slugs",
")",
"?",
"static",
"::",
"$",
"slugs",
":",
"[",
"'title'",
"=>",
"'slug'",
"]",
";",
"$",
"slugger",
"=",
"function",
"(",
"$",
"... | Configure slugs with the $slugs property.
protected static $slugs = [
<column> => <slug_column>,
e.g.
'title' => 'slug',
]; | [
"Configure",
"slugs",
"with",
"the",
"$slugs",
"property",
"."
] | train | https://github.com/glynnforrest/active-doctrine/blob/fcf8c434c7df4704966107bf9a95c005a0b37168/src/ActiveDoctrine/Entity/Traits/SlugTrait.php#L21-L38 |
mr-luke/configuration | src/Schema.php | Schema.check | public function check(array $insert, bool $throw = true): bool
{
foreach ($this->schema as $key => $rules) {
// Check each key by given rules and respond
// due to required flow.
$result = $this->processRules($key, explode('|', $rules), $insert);
if (!$result['status'] && $throw) {
throw new InvalidArgumentException(
sprintf($result['message'], $key)
);
}
}
return $result['status'] ?? true;
} | php | public function check(array $insert, bool $throw = true): bool
{
foreach ($this->schema as $key => $rules) {
// Check each key by given rules and respond
// due to required flow.
$result = $this->processRules($key, explode('|', $rules), $insert);
if (!$result['status'] && $throw) {
throw new InvalidArgumentException(
sprintf($result['message'], $key)
);
}
}
return $result['status'] ?? true;
} | [
"public",
"function",
"check",
"(",
"array",
"$",
"insert",
",",
"bool",
"$",
"throw",
"=",
"true",
")",
":",
"bool",
"{",
"foreach",
"(",
"$",
"this",
"->",
"schema",
"as",
"$",
"key",
"=>",
"$",
"rules",
")",
"{",
"// Check each key by given rules and ... | Check if given array is matching the schema.
@param array $insert
@param bool $throw
@return bool
@throws \InvalidArgumentException | [
"Check",
"if",
"given",
"array",
"is",
"matching",
"the",
"schema",
"."
] | train | https://github.com/mr-luke/configuration/blob/487c90011dc15556787785ed60c60ea92655beac/src/Schema.php#L51-L66 |
mr-luke/configuration | src/Schema.php | Schema.createFromFile | public static function createFromFile(string $path, bool $json = false): Schema
{
static::fileExists($path);
$schema = $json ? json_decode(file_get_contents($path), true) : include $path;
if (!is_array($schema)) {
throw new InvalidArgumentException(
'[createFromFile] method requires file that return a php array or json.'
);
}
return new static($schema);
} | php | public static function createFromFile(string $path, bool $json = false): Schema
{
static::fileExists($path);
$schema = $json ? json_decode(file_get_contents($path), true) : include $path;
if (!is_array($schema)) {
throw new InvalidArgumentException(
'[createFromFile] method requires file that return a php array or json.'
);
}
return new static($schema);
} | [
"public",
"static",
"function",
"createFromFile",
"(",
"string",
"$",
"path",
",",
"bool",
"$",
"json",
"=",
"false",
")",
":",
"Schema",
"{",
"static",
"::",
"fileExists",
"(",
"$",
"path",
")",
";",
"$",
"schema",
"=",
"$",
"json",
"?",
"json_decode"... | Create new Schema instance based on file.
@param string $path
@param bool $json
@return Mrluke\Configuration\Schema | [
"Create",
"new",
"Schema",
"instance",
"based",
"on",
"file",
"."
] | train | https://github.com/mr-luke/configuration/blob/487c90011dc15556787785ed60c60ea92655beac/src/Schema.php#L75-L88 |
mr-luke/configuration | src/Schema.php | Schema.processRules | private function processRules(string $key, array $rules, array $insert): array
{
$status = true;
if (!isset($insert[$key])) {
$status = false;
$message = 'Schema key [%s] not present on insert.';
}
do {
$r = array_shift($rules);
$method = 'checkRule'. ucfirst($r);
if (!in_array($r, $this->rules)) {
// There's no rule defined and allowed.
continue;
}
if (!$this->{$method}($insert[$key])) {
// When given key is not valid we need to stop process
// and set message related to validation error.
$status = false;
$message = $this->messages()[$r];
break;
}
} while (count($rules));
return compact('status', 'message');
} | php | private function processRules(string $key, array $rules, array $insert): array
{
$status = true;
if (!isset($insert[$key])) {
$status = false;
$message = 'Schema key [%s] not present on insert.';
}
do {
$r = array_shift($rules);
$method = 'checkRule'. ucfirst($r);
if (!in_array($r, $this->rules)) {
// There's no rule defined and allowed.
continue;
}
if (!$this->{$method}($insert[$key])) {
// When given key is not valid we need to stop process
// and set message related to validation error.
$status = false;
$message = $this->messages()[$r];
break;
}
} while (count($rules));
return compact('status', 'message');
} | [
"private",
"function",
"processRules",
"(",
"string",
"$",
"key",
",",
"array",
"$",
"rules",
",",
"array",
"$",
"insert",
")",
":",
"array",
"{",
"$",
"status",
"=",
"true",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"insert",
"[",
"$",
"key",
"]",
... | Parse each rules for given key of insert.
@param string $key
@param array $rules
@param array $insert
@return array | [
"Parse",
"each",
"rules",
"for",
"given",
"key",
"of",
"insert",
"."
] | train | https://github.com/mr-luke/configuration/blob/487c90011dc15556787785ed60c60ea92655beac/src/Schema.php#L197-L226 |
phpnfe/tools | src/XMLGet.php | XMLGet.value | public function value()
{
if (is_null($this->value)) {
if (is_null($this->elem)) {
$this->value = '';
} else {
$this->value = $this->elem->textContent;
}
}
return $this->value;
} | php | public function value()
{
if (is_null($this->value)) {
if (is_null($this->elem)) {
$this->value = '';
} else {
$this->value = $this->elem->textContent;
}
}
return $this->value;
} | [
"public",
"function",
"value",
"(",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"value",
")",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"elem",
")",
")",
"{",
"$",
"this",
"->",
"value",
"=",
"''",
";",
"}",
"else",
... | Retorna o valor.
@return string | [
"Retorna",
"o",
"valor",
"."
] | train | https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/XMLGet.php#L33-L44 |
phpnfe/tools | src/XMLGet.php | XMLGet.pad | public function pad($num, $char = '0', $dir = STR_PAD_LEFT)
{
$this->value = str_pad($this->value(), $num, $char, $dir);
return $this;
} | php | public function pad($num, $char = '0', $dir = STR_PAD_LEFT)
{
$this->value = str_pad($this->value(), $num, $char, $dir);
return $this;
} | [
"public",
"function",
"pad",
"(",
"$",
"num",
",",
"$",
"char",
"=",
"'0'",
",",
"$",
"dir",
"=",
"STR_PAD_LEFT",
")",
"{",
"$",
"this",
"->",
"value",
"=",
"str_pad",
"(",
"$",
"this",
"->",
"value",
"(",
")",
",",
"$",
"num",
",",
"$",
"char"... | Aplicar PAD.
@param $num
@param string $char
@param int $dir
@return $this | [
"Aplicar",
"PAD",
"."
] | train | https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/XMLGet.php#L54-L59 |
phpnfe/tools | src/XMLGet.php | XMLGet.number | public function number($dec, $zeroNull = true)
{
$val = floatval($this->value());
if (($val == 0) && ($zeroNull)) {
$this->value = '';
} else {
$this->value = number_format($val, $dec, ',', '.');
}
return $this;
} | php | public function number($dec, $zeroNull = true)
{
$val = floatval($this->value());
if (($val == 0) && ($zeroNull)) {
$this->value = '';
} else {
$this->value = number_format($val, $dec, ',', '.');
}
return $this;
} | [
"public",
"function",
"number",
"(",
"$",
"dec",
",",
"$",
"zeroNull",
"=",
"true",
")",
"{",
"$",
"val",
"=",
"floatval",
"(",
"$",
"this",
"->",
"value",
"(",
")",
")",
";",
"if",
"(",
"(",
"$",
"val",
"==",
"0",
")",
"&&",
"(",
"$",
"zeroN... | Aplica formatação numérica.
@param $dec
@return $this | [
"Aplica",
"formatação",
"numérica",
"."
] | train | https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/XMLGet.php#L67-L77 |
phpnfe/tools | src/XMLGet.php | XMLGet.frete | public function frete()
{
switch ($this->value()) {
case '0':
$this->value = '0 - EMIT';
break;
case '1':
$this->value = '1 - DEST/REM';
break;
case '2':
$this->value = '2 - TERC';
break;
case '9':
$this->value = '3 - S/F';
break;
default:
$this->value = '';
break;
}
return $this;
} | php | public function frete()
{
switch ($this->value()) {
case '0':
$this->value = '0 - EMIT';
break;
case '1':
$this->value = '1 - DEST/REM';
break;
case '2':
$this->value = '2 - TERC';
break;
case '9':
$this->value = '3 - S/F';
break;
default:
$this->value = '';
break;
}
return $this;
} | [
"public",
"function",
"frete",
"(",
")",
"{",
"switch",
"(",
"$",
"this",
"->",
"value",
"(",
")",
")",
"{",
"case",
"'0'",
":",
"$",
"this",
"->",
"value",
"=",
"'0 - EMIT'",
";",
"break",
";",
"case",
"'1'",
":",
"$",
"this",
"->",
"value",
"="... | Retorna o texto certo para o valor atribuído ao frete.
@param $valor
@return string | [
"Retorna",
"o",
"texto",
"certo",
"para",
"o",
"valor",
"atribuído",
"ao",
"frete",
"."
] | train | https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/XMLGet.php#L84-L105 |
phpnfe/tools | src/XMLGet.php | XMLGet.format | public function format($format)
{
$string = str_replace(' ', '', $this->value());
for ($i = 0; $i < strlen($string); $i++) {
$pos = strpos($format, '#');
// verificar se string eh maior que a qtdade de #.
if ($pos === false) {
break;
}
$format[$pos] = $string[$i];
}
// verificar se sobrou # para trocar
if (strpos($format, '#') !== false) {
$format = $this->value();
}
$this->value = $format;
return $this;
} | php | public function format($format)
{
$string = str_replace(' ', '', $this->value());
for ($i = 0; $i < strlen($string); $i++) {
$pos = strpos($format, '#');
// verificar se string eh maior que a qtdade de #.
if ($pos === false) {
break;
}
$format[$pos] = $string[$i];
}
// verificar se sobrou # para trocar
if (strpos($format, '#') !== false) {
$format = $this->value();
}
$this->value = $format;
return $this;
} | [
"public",
"function",
"format",
"(",
"$",
"format",
")",
"{",
"$",
"string",
"=",
"str_replace",
"(",
"' '",
",",
"''",
",",
"$",
"this",
"->",
"value",
"(",
")",
")",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"strlen",
"(",
"$... | Aplica a mascara de formação do value.
@param $format
@return $this | [
"Aplica",
"a",
"mascara",
"de",
"formação",
"do",
"value",
"."
] | train | https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/XMLGet.php#L112-L133 |
blast-project/BaseEntitiesBundle | src/Loggable/Mapping/Driver/Xml.php | Xml.readExtendedMetadata | public function readExtendedMetadata($meta, array &$config)
{
/**
* @var \SimpleXmlElement
*/
$xml = $this->_getMapping($meta->name);
$xmlDoctrine = $xml;
$xml = $xml->children(self::GEDMO_NAMESPACE_URI);
if ($xmlDoctrine->getName() == 'entity' || $xmlDoctrine->getName() == 'document' || $xmlDoctrine->getName() == 'mapped-superclass') {
if (isset($xml->loggable)) {
/**
* @var \SimpleXMLElement;
*/
$data = $xml->loggable;
$config['loggable'] = true;
if ($this->_isAttributeSet($data, 'log-entry-class')) {
$class = $this->_getAttribute($data, 'log-entry-class');
if (!$cl = $this->getRelatedClassName($meta, $class)) {
throw new InvalidMappingException("LogEntry class: {$class} does not exist.");
}
$config['logEntryClass'] = $cl;
}
}
}
if (isset($xmlDoctrine->field)) {
$this->inspectElementForVersioned($xmlDoctrine->field, $config, $meta);
}
if (isset($xmlDoctrine->{'many-to-one'})) {
$this->inspectElementForVersioned($xmlDoctrine->{'many-to-one'}, $config, $meta);
}
if (isset($xmlDoctrine->{'one-to-one'})) {
$this->inspectElementForVersioned($xmlDoctrine->{'one-to-one'}, $config, $meta);
}
if (isset($xmlDoctrine->{'reference-one'})) {
$this->inspectElementForVersioned($xmlDoctrine->{'reference-one'}, $config, $meta);
}
if (isset($xmlDoctrine->{'embedded'})) {
$this->inspectElementForVersioned($xmlDoctrine->{'embedded'}, $config, $meta);
}
if (!$meta->isMappedSuperclass && $config) {
if (is_array($meta->identifier) && count($meta->identifier) > 1) {
throw new InvalidMappingException("Loggable does not support composite identifiers in class - {$meta->name}");
}
if (isset($config['versioned']) && !isset($config['loggable'])) {
throw new InvalidMappingException("Class must be annotated with Loggable annotation in order to track versioned fields in class - {$meta->name}");
}
}
} | php | public function readExtendedMetadata($meta, array &$config)
{
/**
* @var \SimpleXmlElement
*/
$xml = $this->_getMapping($meta->name);
$xmlDoctrine = $xml;
$xml = $xml->children(self::GEDMO_NAMESPACE_URI);
if ($xmlDoctrine->getName() == 'entity' || $xmlDoctrine->getName() == 'document' || $xmlDoctrine->getName() == 'mapped-superclass') {
if (isset($xml->loggable)) {
/**
* @var \SimpleXMLElement;
*/
$data = $xml->loggable;
$config['loggable'] = true;
if ($this->_isAttributeSet($data, 'log-entry-class')) {
$class = $this->_getAttribute($data, 'log-entry-class');
if (!$cl = $this->getRelatedClassName($meta, $class)) {
throw new InvalidMappingException("LogEntry class: {$class} does not exist.");
}
$config['logEntryClass'] = $cl;
}
}
}
if (isset($xmlDoctrine->field)) {
$this->inspectElementForVersioned($xmlDoctrine->field, $config, $meta);
}
if (isset($xmlDoctrine->{'many-to-one'})) {
$this->inspectElementForVersioned($xmlDoctrine->{'many-to-one'}, $config, $meta);
}
if (isset($xmlDoctrine->{'one-to-one'})) {
$this->inspectElementForVersioned($xmlDoctrine->{'one-to-one'}, $config, $meta);
}
if (isset($xmlDoctrine->{'reference-one'})) {
$this->inspectElementForVersioned($xmlDoctrine->{'reference-one'}, $config, $meta);
}
if (isset($xmlDoctrine->{'embedded'})) {
$this->inspectElementForVersioned($xmlDoctrine->{'embedded'}, $config, $meta);
}
if (!$meta->isMappedSuperclass && $config) {
if (is_array($meta->identifier) && count($meta->identifier) > 1) {
throw new InvalidMappingException("Loggable does not support composite identifiers in class - {$meta->name}");
}
if (isset($config['versioned']) && !isset($config['loggable'])) {
throw new InvalidMappingException("Class must be annotated with Loggable annotation in order to track versioned fields in class - {$meta->name}");
}
}
} | [
"public",
"function",
"readExtendedMetadata",
"(",
"$",
"meta",
",",
"array",
"&",
"$",
"config",
")",
"{",
"/**\n * @var \\SimpleXmlElement\n */",
"$",
"xml",
"=",
"$",
"this",
"->",
"_getMapping",
"(",
"$",
"meta",
"->",
"name",
")",
";",
"$"... | {@inheritdoc} | [
"{"
] | train | https://github.com/blast-project/BaseEntitiesBundle/blob/abd06891fc38922225ab7e4fcb437a286ba2c0c4/src/Loggable/Mapping/Driver/Xml.php#L42-L93 |
blast-project/BaseEntitiesBundle | src/Loggable/Mapping/Driver/Xml.php | Xml.inspectElementForVersioned | private function inspectElementForVersioned(\SimpleXMLElement $element, array &$config, $meta)
{
foreach ($element as $mapping) {
$mappingDoctrine = $mapping;
/**
* @var \SimpleXmlElement
*/
$mapping = $mapping->children(self::GEDMO_NAMESPACE_URI);
$isAssoc = $this->_isAttributeSet($mappingDoctrine, 'field');
$field = $this->_getAttribute($mappingDoctrine, $isAssoc ? 'field' : 'name');
if (isset($mapping->versioned)) {
if ($isAssoc && !$meta->associationMappings[$field]['isOwningSide']) {
throw new InvalidMappingException("Cannot version [{$field}] as it is not the owning side in object - {$meta->name}");
}
$config['versioned'][] = $field;
}
}
} | php | private function inspectElementForVersioned(\SimpleXMLElement $element, array &$config, $meta)
{
foreach ($element as $mapping) {
$mappingDoctrine = $mapping;
/**
* @var \SimpleXmlElement
*/
$mapping = $mapping->children(self::GEDMO_NAMESPACE_URI);
$isAssoc = $this->_isAttributeSet($mappingDoctrine, 'field');
$field = $this->_getAttribute($mappingDoctrine, $isAssoc ? 'field' : 'name');
if (isset($mapping->versioned)) {
if ($isAssoc && !$meta->associationMappings[$field]['isOwningSide']) {
throw new InvalidMappingException("Cannot version [{$field}] as it is not the owning side in object - {$meta->name}");
}
$config['versioned'][] = $field;
}
}
} | [
"private",
"function",
"inspectElementForVersioned",
"(",
"\\",
"SimpleXMLElement",
"$",
"element",
",",
"array",
"&",
"$",
"config",
",",
"$",
"meta",
")",
"{",
"foreach",
"(",
"$",
"element",
"as",
"$",
"mapping",
")",
"{",
"$",
"mappingDoctrine",
"=",
"... | Searches mappings on element for versioned fields.
@param \SimpleXMLElement $element
@param array $config
@param object $meta | [
"Searches",
"mappings",
"on",
"element",
"for",
"versioned",
"fields",
"."
] | train | https://github.com/blast-project/BaseEntitiesBundle/blob/abd06891fc38922225ab7e4fcb437a286ba2c0c4/src/Loggable/Mapping/Driver/Xml.php#L102-L121 |
digipolisgent/robo-digipolis-package-drupal8 | src/ThemesCleanDrupal8.php | ThemesCleanDrupal8.run | public function run()
{
$themesFromConfig = $this->getConfig()->get('digipolis.themes.drupal8', false);
$themeNamesFromConfig = [];
if ($themesFromConfig) {
$themeNamesFromConfig = array_keys((array) $themesFromConfig);
}
$themes = empty($this->themes)
? $themeNamesFromConfig
: $this->themes;
if (!$themes) {
return \Robo\Result::success($this);
}
$collection = $this->collectionBuilder();
foreach ($this->getThemePaths($themes) as $themeName => $path) {
$themeSettings = isset($themesFromConfig[$themeName])
? $themesFromConfig[$themeName]
: [];
if (is_string($themeSettings)) {
// Backward compatibility.
$themeSettings = ['command' => $themeSettings];
}
$themeSettings = array_merge(
['command' => 'build', 'sourcedir' => 'source'],
$themeSettings
);
if ($themeSettings['sourcedir'] && is_dir($path . '/' . $themeSettings['sourcedir'])) {
$collection->addTask($this->taskDeleteDir([$path . '/' . $themeSettings['sourcedir']]));
continue;
}
$collection->addTask($this->taskThemeClean($path));
}
return $collection->run();
} | php | public function run()
{
$themesFromConfig = $this->getConfig()->get('digipolis.themes.drupal8', false);
$themeNamesFromConfig = [];
if ($themesFromConfig) {
$themeNamesFromConfig = array_keys((array) $themesFromConfig);
}
$themes = empty($this->themes)
? $themeNamesFromConfig
: $this->themes;
if (!$themes) {
return \Robo\Result::success($this);
}
$collection = $this->collectionBuilder();
foreach ($this->getThemePaths($themes) as $themeName => $path) {
$themeSettings = isset($themesFromConfig[$themeName])
? $themesFromConfig[$themeName]
: [];
if (is_string($themeSettings)) {
// Backward compatibility.
$themeSettings = ['command' => $themeSettings];
}
$themeSettings = array_merge(
['command' => 'build', 'sourcedir' => 'source'],
$themeSettings
);
if ($themeSettings['sourcedir'] && is_dir($path . '/' . $themeSettings['sourcedir'])) {
$collection->addTask($this->taskDeleteDir([$path . '/' . $themeSettings['sourcedir']]));
continue;
}
$collection->addTask($this->taskThemeClean($path));
}
return $collection->run();
} | [
"public",
"function",
"run",
"(",
")",
"{",
"$",
"themesFromConfig",
"=",
"$",
"this",
"->",
"getConfig",
"(",
")",
"->",
"get",
"(",
"'digipolis.themes.drupal8'",
",",
"false",
")",
";",
"$",
"themeNamesFromConfig",
"=",
"[",
"]",
";",
"if",
"(",
"$",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/digipolisgent/robo-digipolis-package-drupal8/blob/dc03ae0f68d56a027291e9574ff7aa433c27690a/src/ThemesCleanDrupal8.php#L98-L131 |
rhosocial/yii2-user | console/controllers/UserController.php | UserController.checkUserClass | protected function checkUserClass()
{
$userClass = $this->userClass;
if (!class_exists($userClass)) {
throw new Exception('User Class Invalid.');
}
if (!((new $userClass()) instanceof User)) {
throw new Exception('User Class(' . $userClass . ') does not inherited from `\rhosocial\user\User`.');
}
return $userClass;
} | php | protected function checkUserClass()
{
$userClass = $this->userClass;
if (!class_exists($userClass)) {
throw new Exception('User Class Invalid.');
}
if (!((new $userClass()) instanceof User)) {
throw new Exception('User Class(' . $userClass . ') does not inherited from `\rhosocial\user\User`.');
}
return $userClass;
} | [
"protected",
"function",
"checkUserClass",
"(",
")",
"{",
"$",
"userClass",
"=",
"$",
"this",
"->",
"userClass",
";",
"if",
"(",
"!",
"class_exists",
"(",
"$",
"userClass",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'User Class Invalid.'",
")",
";",... | Check and get valid User.
@return User
@throws Exception throw if User is not an instance inherited from `\rhosocial\user\User`. | [
"Check",
"and",
"get",
"valid",
"User",
"."
] | train | https://github.com/rhosocial/yii2-user/blob/96737a9d8ca7e9c42cd2b7736d6c0a90ede6e5bc/console/controllers/UserController.php#L41-L51 |
rhosocial/yii2-user | console/controllers/UserController.php | UserController.getUser | protected function getUser($user)
{
$userClass = $this->checkUserClass();
if (is_numeric($user)) {
$user = $userClass::find()->id($user)->one();
} elseif (is_string($user) && strlen($user)) {
$user = $userClass::find()->guid($user)->one();
}
if (!$user || $user->getIsNewRecord()) {
throw new Exception('User Not Registered.');
}
return $user;
} | php | protected function getUser($user)
{
$userClass = $this->checkUserClass();
if (is_numeric($user)) {
$user = $userClass::find()->id($user)->one();
} elseif (is_string($user) && strlen($user)) {
$user = $userClass::find()->guid($user)->one();
}
if (!$user || $user->getIsNewRecord()) {
throw new Exception('User Not Registered.');
}
return $user;
} | [
"protected",
"function",
"getUser",
"(",
"$",
"user",
")",
"{",
"$",
"userClass",
"=",
"$",
"this",
"->",
"checkUserClass",
"(",
")",
";",
"if",
"(",
"is_numeric",
"(",
"$",
"user",
")",
")",
"{",
"$",
"user",
"=",
"$",
"userClass",
"::",
"find",
"... | Get user from database.
@param User|string|integer $user User ID.
@return User
@throws Exception | [
"Get",
"user",
"from",
"database",
"."
] | train | https://github.com/rhosocial/yii2-user/blob/96737a9d8ca7e9c42cd2b7736d6c0a90ede6e5bc/console/controllers/UserController.php#L59-L71 |
rhosocial/yii2-user | console/controllers/UserController.php | UserController.actionRegister | public function actionRegister($password, $nickname = null, $firstName = null, $lastName = null)
{
$userClass = $this->checkUserClass();
$user = new $userClass(['password' => $password]);
/* @var $user User */
$profile = $user->createProfile([
'nickname' => $nickname,
'first_name' => $firstName,
'last_name' => $lastName,
]);
/* @var $profile Profile */
try {
is_null($profile) ? $user->register(): $user->register([$profile]);
} catch (\Exception $ex) {
throw new Exception($ex->getMessage());
}
echo "User Registered:\n";
return $this->actionShow($user);
} | php | public function actionRegister($password, $nickname = null, $firstName = null, $lastName = null)
{
$userClass = $this->checkUserClass();
$user = new $userClass(['password' => $password]);
/* @var $user User */
$profile = $user->createProfile([
'nickname' => $nickname,
'first_name' => $firstName,
'last_name' => $lastName,
]);
/* @var $profile Profile */
try {
is_null($profile) ? $user->register(): $user->register([$profile]);
} catch (\Exception $ex) {
throw new Exception($ex->getMessage());
}
echo "User Registered:\n";
return $this->actionShow($user);
} | [
"public",
"function",
"actionRegister",
"(",
"$",
"password",
",",
"$",
"nickname",
"=",
"null",
",",
"$",
"firstName",
"=",
"null",
",",
"$",
"lastName",
"=",
"null",
")",
"{",
"$",
"userClass",
"=",
"$",
"this",
"->",
"checkUserClass",
"(",
")",
";",... | Register new User.
@param string $password Password.
@param string $nickname If profile contains this property, this parameter is required.
@param string $firstName If profile contains this property, this parameter is required.
@param string $lastName If profile contains this propery, this parameter is required.
@return int
@throws Exception | [
"Register",
"new",
"User",
"."
] | train | https://github.com/rhosocial/yii2-user/blob/96737a9d8ca7e9c42cd2b7736d6c0a90ede6e5bc/console/controllers/UserController.php#L82-L101 |
rhosocial/yii2-user | console/controllers/UserController.php | UserController.actionDeregister | public function actionDeregister($user)
{
$user = $this->getUser($user);
if ($user->deregister()) {
echo "User (" . $user->getID() . ") Deregistered.\n";
return static::EXIT_CODE_NORMAL;
}
return static::EXIT_CODE_ERROR;
} | php | public function actionDeregister($user)
{
$user = $this->getUser($user);
if ($user->deregister()) {
echo "User (" . $user->getID() . ") Deregistered.\n";
return static::EXIT_CODE_NORMAL;
}
return static::EXIT_CODE_ERROR;
} | [
"public",
"function",
"actionDeregister",
"(",
"$",
"user",
")",
"{",
"$",
"user",
"=",
"$",
"this",
"->",
"getUser",
"(",
"$",
"user",
")",
";",
"if",
"(",
"$",
"user",
"->",
"deregister",
"(",
")",
")",
"{",
"echo",
"\"User (\"",
".",
"$",
"user"... | Deregister user.
@param User|string|integer $user The user to be deregistered.
@return int | [
"Deregister",
"user",
"."
] | train | https://github.com/rhosocial/yii2-user/blob/96737a9d8ca7e9c42cd2b7736d6c0a90ede6e5bc/console/controllers/UserController.php#L108-L116 |
rhosocial/yii2-user | console/controllers/UserController.php | UserController.actionShow | public function actionShow($user, $guid = false, $passHash = false, $accessToken = false, $authKey = false)
{
$user = $this->getUser($user);
echo Yii::t('app', 'User') . " (" . $user->getID() . "), " . Yii::t('app', 'registered at') . " (" . $user->getCreatedAt() . ")"
. ($user->getCreatedAt() == $user->getUpdatedAt() ? "" : ", " . Yii::t('app', 'last updated at') . " (" . $user->getUpdatedAt() . ")") .".\n";
if ($guid) {
echo "GUID: " . $user->getGUID() . "\n";
}
if ($passHash) {
echo "Password Hash: " . $user->{$user->passwordHashAttribute} . "\n";
}
if ($accessToken) {
echo "Access Token: " . $user->getAccessToken() . "\n";
}
if ($authKey) {
echo "Authentication Key: " . $user->getAuthKey() . "\n";
}
return static::EXIT_CODE_NORMAL;
} | php | public function actionShow($user, $guid = false, $passHash = false, $accessToken = false, $authKey = false)
{
$user = $this->getUser($user);
echo Yii::t('app', 'User') . " (" . $user->getID() . "), " . Yii::t('app', 'registered at') . " (" . $user->getCreatedAt() . ")"
. ($user->getCreatedAt() == $user->getUpdatedAt() ? "" : ", " . Yii::t('app', 'last updated at') . " (" . $user->getUpdatedAt() . ")") .".\n";
if ($guid) {
echo "GUID: " . $user->getGUID() . "\n";
}
if ($passHash) {
echo "Password Hash: " . $user->{$user->passwordHashAttribute} . "\n";
}
if ($accessToken) {
echo "Access Token: " . $user->getAccessToken() . "\n";
}
if ($authKey) {
echo "Authentication Key: " . $user->getAuthKey() . "\n";
}
return static::EXIT_CODE_NORMAL;
} | [
"public",
"function",
"actionShow",
"(",
"$",
"user",
",",
"$",
"guid",
"=",
"false",
",",
"$",
"passHash",
"=",
"false",
",",
"$",
"accessToken",
"=",
"false",
",",
"$",
"authKey",
"=",
"false",
")",
"{",
"$",
"user",
"=",
"$",
"this",
"->",
"getU... | Show User Information.
@param User|string|integer $user User ID.
@param boolean $guid Show GUID?
@param boolean $passHash Show PasswordH Hash?
@param boolean $accessToken Show Access Token?
@param boolean $authKey Show Authentication Key?
@return int | [
"Show",
"User",
"Information",
"."
] | train | https://github.com/rhosocial/yii2-user/blob/96737a9d8ca7e9c42cd2b7736d6c0a90ede6e5bc/console/controllers/UserController.php#L127-L145 |
rhosocial/yii2-user | console/controllers/UserController.php | UserController.actionStat | public function actionStat($user = null)
{
if ($user === null) {
$count = User::find()->count();
echo "Total number of user(s): " . $count . "\n";
if ($count == 0) {
return static::EXIT_CODE_NORMAL;
}
$last = User::find()->orderByCreatedAt(SORT_DESC)->one();
/* @var $last User */
echo "Latest user (" . $last->getID() . ") registered at " . $last->getCreatedAt() . "\n";
return static::EXIT_CODE_NORMAL;
}
$user = $this->getUser($user);
return static::EXIT_CODE_NORMAL;
} | php | public function actionStat($user = null)
{
if ($user === null) {
$count = User::find()->count();
echo "Total number of user(s): " . $count . "\n";
if ($count == 0) {
return static::EXIT_CODE_NORMAL;
}
$last = User::find()->orderByCreatedAt(SORT_DESC)->one();
/* @var $last User */
echo "Latest user (" . $last->getID() . ") registered at " . $last->getCreatedAt() . "\n";
return static::EXIT_CODE_NORMAL;
}
$user = $this->getUser($user);
return static::EXIT_CODE_NORMAL;
} | [
"public",
"function",
"actionStat",
"(",
"$",
"user",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"user",
"===",
"null",
")",
"{",
"$",
"count",
"=",
"User",
"::",
"find",
"(",
")",
"->",
"count",
"(",
")",
";",
"echo",
"\"Total number of user(s): \"",
".... | Show statistics.
@param User|string|integer $user User ID.
@return int | [
"Show",
"statistics",
"."
] | train | https://github.com/rhosocial/yii2-user/blob/96737a9d8ca7e9c42cd2b7736d6c0a90ede6e5bc/console/controllers/UserController.php#L152-L167 |
rhosocial/yii2-user | console/controllers/UserController.php | UserController.actionRole | public function actionRole($user, $operation, $role)
{
$user = $this->getUser($user);
$role = Yii::$app->authManager->getRole($role);
if ($operation == 'assign') {
try {
$assignment = Yii::$app->authManager->assign($role, $user);
} catch (\yii\db\IntegrityException $ex) {
echo "Failed to assign `" . $role->name . "`.\n";
echo "Maybe the role has been assigned.\n";
return static::EXIT_CODE_ERROR;
}
if ($assignment) {
echo "`$role->name`" . " assigned to User (" . $user->getID() . ") successfully.\n";
} else {
echo "Failed to assign `" . $role->name . "`.\n";
}
return static::EXIT_CODE_NORMAL;
}
if ($operation == 'revoke') {
$assignment = Yii::$app->authManager->revoke($role, $user);
if ($assignment) {
echo "`$role->name`" . " revoked from User (" . $user->getID() . ").\n";
} else {
echo "Failed to revoke `" . $role->name . "`.\n";
echo "Maybe the role has not been assigned yet.\n";
}
return static::EXIT_CODE_NORMAL;
}
echo "Unrecognized operation: $operation.\n";
echo "The accepted operations are `assign` and `revoke`.\n";
return static::EXIT_CODE_ERROR;
} | php | public function actionRole($user, $operation, $role)
{
$user = $this->getUser($user);
$role = Yii::$app->authManager->getRole($role);
if ($operation == 'assign') {
try {
$assignment = Yii::$app->authManager->assign($role, $user);
} catch (\yii\db\IntegrityException $ex) {
echo "Failed to assign `" . $role->name . "`.\n";
echo "Maybe the role has been assigned.\n";
return static::EXIT_CODE_ERROR;
}
if ($assignment) {
echo "`$role->name`" . " assigned to User (" . $user->getID() . ") successfully.\n";
} else {
echo "Failed to assign `" . $role->name . "`.\n";
}
return static::EXIT_CODE_NORMAL;
}
if ($operation == 'revoke') {
$assignment = Yii::$app->authManager->revoke($role, $user);
if ($assignment) {
echo "`$role->name`" . " revoked from User (" . $user->getID() . ").\n";
} else {
echo "Failed to revoke `" . $role->name . "`.\n";
echo "Maybe the role has not been assigned yet.\n";
}
return static::EXIT_CODE_NORMAL;
}
echo "Unrecognized operation: $operation.\n";
echo "The accepted operations are `assign` and `revoke`.\n";
return static::EXIT_CODE_ERROR;
} | [
"public",
"function",
"actionRole",
"(",
"$",
"user",
",",
"$",
"operation",
",",
"$",
"role",
")",
"{",
"$",
"user",
"=",
"$",
"this",
"->",
"getUser",
"(",
"$",
"user",
")",
";",
"$",
"role",
"=",
"Yii",
"::",
"$",
"app",
"->",
"authManager",
"... | Assign a role to user or revoke a role.
@param User|string|integer $user User ID.
@param string $operation Only `assign` and `revoke` are acceptable.
@param string $role Role name.
@return int | [
"Assign",
"a",
"role",
"to",
"user",
"or",
"revoke",
"a",
"role",
"."
] | train | https://github.com/rhosocial/yii2-user/blob/96737a9d8ca7e9c42cd2b7736d6c0a90ede6e5bc/console/controllers/UserController.php#L176-L208 |
rhosocial/yii2-user | console/controllers/UserController.php | UserController.actionPermission | public function actionPermission($user, $operation, $permission)
{
$user = $this->getUser($user);
$permission = Yii::$app->authManager->getPermission($permission);
if ($operation == 'assign') {
try {
$assignment = Yii::$app->authManager->assign($permission, $user);
} catch (\yii\db\IntegrityException $ex) {
echo "Failed to assign `" . $permission->name . "`.\n";
echo "Maybe the permission has been assigned.\n";
return static::EXIT_CODE_ERROR;
}
if ($assignment) {
echo "`$permission->name`" . " assigned to User (" . $user->getID() . ") successfully.\n";
} else {
echo "Failed to assign `" . $permission->name . "`.\n";
}
return static::EXIT_CODE_NORMAL;
}
if ($operation == 'revoke') {
$assignment = Yii::$app->authManager->revoke($permission, $user);
if ($assignment) {
echo "`$permission->name`" . " revoked from User (" . $user->getID() . ").\n";
} else {
echo "Failed to revoke `" . $permission->name . "`.\n";
echo "Maybe the permission has not been assigned yet.\n";
}
return static::EXIT_CODE_NORMAL;
}
echo "Unrecognized operation: $operation.\n";
echo "The accepted operations are `assign` and `revoke`.\n";
return static::EXIT_CODE_ERROR;
} | php | public function actionPermission($user, $operation, $permission)
{
$user = $this->getUser($user);
$permission = Yii::$app->authManager->getPermission($permission);
if ($operation == 'assign') {
try {
$assignment = Yii::$app->authManager->assign($permission, $user);
} catch (\yii\db\IntegrityException $ex) {
echo "Failed to assign `" . $permission->name . "`.\n";
echo "Maybe the permission has been assigned.\n";
return static::EXIT_CODE_ERROR;
}
if ($assignment) {
echo "`$permission->name`" . " assigned to User (" . $user->getID() . ") successfully.\n";
} else {
echo "Failed to assign `" . $permission->name . "`.\n";
}
return static::EXIT_CODE_NORMAL;
}
if ($operation == 'revoke') {
$assignment = Yii::$app->authManager->revoke($permission, $user);
if ($assignment) {
echo "`$permission->name`" . " revoked from User (" . $user->getID() . ").\n";
} else {
echo "Failed to revoke `" . $permission->name . "`.\n";
echo "Maybe the permission has not been assigned yet.\n";
}
return static::EXIT_CODE_NORMAL;
}
echo "Unrecognized operation: $operation.\n";
echo "The accepted operations are `assign` and `revoke`.\n";
return static::EXIT_CODE_ERROR;
} | [
"public",
"function",
"actionPermission",
"(",
"$",
"user",
",",
"$",
"operation",
",",
"$",
"permission",
")",
"{",
"$",
"user",
"=",
"$",
"this",
"->",
"getUser",
"(",
"$",
"user",
")",
";",
"$",
"permission",
"=",
"Yii",
"::",
"$",
"app",
"->",
... | Assign a permission to user or revoke a permission.
@param User|string|integer $user User ID.
@param string $operation Only `assign` and `revoke` are acceptable.
@param string $permission Permission name.
@return int | [
"Assign",
"a",
"permission",
"to",
"user",
"or",
"revoke",
"a",
"permission",
"."
] | train | https://github.com/rhosocial/yii2-user/blob/96737a9d8ca7e9c42cd2b7736d6c0a90ede6e5bc/console/controllers/UserController.php#L217-L249 |
rhosocial/yii2-user | console/controllers/UserController.php | UserController.actionValidatePassword | public function actionValidatePassword($user, $password)
{
$user = $this->getUser($user);
$result = $user->validatePassword($password);
if ($result) {
echo "Correct.\n";
} else {
echo "Incorrect.\n";
}
return static::EXIT_CODE_NORMAL;
} | php | public function actionValidatePassword($user, $password)
{
$user = $this->getUser($user);
$result = $user->validatePassword($password);
if ($result) {
echo "Correct.\n";
} else {
echo "Incorrect.\n";
}
return static::EXIT_CODE_NORMAL;
} | [
"public",
"function",
"actionValidatePassword",
"(",
"$",
"user",
",",
"$",
"password",
")",
"{",
"$",
"user",
"=",
"$",
"this",
"->",
"getUser",
"(",
"$",
"user",
")",
";",
"$",
"result",
"=",
"$",
"user",
"->",
"validatePassword",
"(",
"$",
"password... | Validate password.
@param User|string|integer $user User ID.
@param password $password Password.
@return int | [
"Validate",
"password",
"."
] | train | https://github.com/rhosocial/yii2-user/blob/96737a9d8ca7e9c42cd2b7736d6c0a90ede6e5bc/console/controllers/UserController.php#L257-L267 |
rhosocial/yii2-user | console/controllers/UserController.php | UserController.actionPassword | public function actionPassword($user, $password)
{
$user = $this->getUser($user);
$user->applyForNewPassword();
$result = $user->resetPassword($password, $user->getPasswordResetToken());
if ($result) {
echo "Password changed.\n";
} else {
echo "Password not changed.\n";
}
return static::EXIT_CODE_NORMAL;
} | php | public function actionPassword($user, $password)
{
$user = $this->getUser($user);
$user->applyForNewPassword();
$result = $user->resetPassword($password, $user->getPasswordResetToken());
if ($result) {
echo "Password changed.\n";
} else {
echo "Password not changed.\n";
}
return static::EXIT_CODE_NORMAL;
} | [
"public",
"function",
"actionPassword",
"(",
"$",
"user",
",",
"$",
"password",
")",
"{",
"$",
"user",
"=",
"$",
"this",
"->",
"getUser",
"(",
"$",
"user",
")",
";",
"$",
"user",
"->",
"applyForNewPassword",
"(",
")",
";",
"$",
"result",
"=",
"$",
... | Change password directly.
@param User|string|integer $user User ID.
@param string $password Password.
@return int | [
"Change",
"password",
"directly",
"."
] | train | https://github.com/rhosocial/yii2-user/blob/96737a9d8ca7e9c42cd2b7736d6c0a90ede6e5bc/console/controllers/UserController.php#L275-L286 |
rhosocial/yii2-user | console/controllers/UserController.php | UserController.actionConfirmPasswordHistory | public function actionConfirmPasswordHistory($user, $password)
{
$user = $this->getUser($user);
$passwordHistory = $user->passwordHistories;
$passwordInHistory = 0;
foreach ($passwordHistory as $pass) {
if ($pass->validatePassword($password)) {
$passwordInHistory++;
echo "This password was created at " . $pass->getCreatedAt() . ".\n";
}
}
if ($passwordInHistory) {
echo "$passwordInHistory matched.\n";
return static::EXIT_CODE_NORMAL;
}
echo "No password matched.\n";
return static::EXIT_CODE_ERROR;
} | php | public function actionConfirmPasswordHistory($user, $password)
{
$user = $this->getUser($user);
$passwordHistory = $user->passwordHistories;
$passwordInHistory = 0;
foreach ($passwordHistory as $pass) {
if ($pass->validatePassword($password)) {
$passwordInHistory++;
echo "This password was created at " . $pass->getCreatedAt() . ".\n";
}
}
if ($passwordInHistory) {
echo "$passwordInHistory matched.\n";
return static::EXIT_CODE_NORMAL;
}
echo "No password matched.\n";
return static::EXIT_CODE_ERROR;
} | [
"public",
"function",
"actionConfirmPasswordHistory",
"(",
"$",
"user",
",",
"$",
"password",
")",
"{",
"$",
"user",
"=",
"$",
"this",
"->",
"getUser",
"(",
"$",
"user",
")",
";",
"$",
"passwordHistory",
"=",
"$",
"user",
"->",
"passwordHistories",
";",
... | Confirm password in history.
This command will list all matching passwords in reverse order.
@param User|string|integer $user User ID.
@param string $password Password.
@return int | [
"Confirm",
"password",
"in",
"history",
".",
"This",
"command",
"will",
"list",
"all",
"matching",
"passwords",
"in",
"reverse",
"order",
"."
] | train | https://github.com/rhosocial/yii2-user/blob/96737a9d8ca7e9c42cd2b7736d6c0a90ede6e5bc/console/controllers/UserController.php#L295-L312 |
Eresus/EresusCMS | src/ext-3rd/tinymce/plugins/images/connector/php/exifReader.php | phpExifReader.phpExifReader | function phpExifReader($file = "")
{
$this->timeStart = $this->getmicrotime();
if (!empty($file))
{
$this->file = $file;
}
/**
* Initialize some variables. Avoid lots of errors with fulll error_reporting
*/
$this->ExifImageLength = 0;
$this->ImageInfo['h']["resolutionUnit"] = 0;
$this->ImageInfo[TAG_MAXAPERTURE] = 0;
$this->ImageInfo[TAG_ISO_EQUIVALENT] = 0;
$this->ImageInfo[TAG_ORIENTATION] = 0;
$this->ThumbnailSize = 0;
if ($this->caching)
{
$this->cacheDir = dirname(__FILE__) . "/.cache_thumbs";
/**
* If Cache directory does not exists then attempt to create it.
*/
if (!is_dir($this->cacheDir))
{
mkdir($this->cacheDir);
}
// Prepare the ame of thumbnail
if (is_dir($this->cacheDir))
{
$this->thumbnail = $this->cacheDir . "/" . basename($this->file);
$this->thumbnailURL = ".cache_thumbs/" . basename($this->file);
}
}
/** check if file exists! */
if (!file_exists($this->file))
{
$this->errno = 1;
$this->errstr = "File '" . $this->file . "' does not exists!";
}
$this->currSection = 0;
$this->processFile();
} | php | function phpExifReader($file = "")
{
$this->timeStart = $this->getmicrotime();
if (!empty($file))
{
$this->file = $file;
}
/**
* Initialize some variables. Avoid lots of errors with fulll error_reporting
*/
$this->ExifImageLength = 0;
$this->ImageInfo['h']["resolutionUnit"] = 0;
$this->ImageInfo[TAG_MAXAPERTURE] = 0;
$this->ImageInfo[TAG_ISO_EQUIVALENT] = 0;
$this->ImageInfo[TAG_ORIENTATION] = 0;
$this->ThumbnailSize = 0;
if ($this->caching)
{
$this->cacheDir = dirname(__FILE__) . "/.cache_thumbs";
/**
* If Cache directory does not exists then attempt to create it.
*/
if (!is_dir($this->cacheDir))
{
mkdir($this->cacheDir);
}
// Prepare the ame of thumbnail
if (is_dir($this->cacheDir))
{
$this->thumbnail = $this->cacheDir . "/" . basename($this->file);
$this->thumbnailURL = ".cache_thumbs/" . basename($this->file);
}
}
/** check if file exists! */
if (!file_exists($this->file))
{
$this->errno = 1;
$this->errstr = "File '" . $this->file . "' does not exists!";
}
$this->currSection = 0;
$this->processFile();
} | [
"function",
"phpExifReader",
"(",
"$",
"file",
"=",
"\"\"",
")",
"{",
"$",
"this",
"->",
"timeStart",
"=",
"$",
"this",
"->",
"getmicrotime",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"file",
")",
")",
"{",
"$",
"this",
"->",
"file",
"=",... | Constructor
@param string $file File name to be parsed. | [
"Constructor",
"@param",
"string",
"$file",
"File",
"name",
"to",
"be",
"parsed",
"."
] | train | https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/ext-3rd/tinymce/plugins/images/connector/php/exifReader.php#L370-L419 |
Eresus/EresusCMS | src/ext-3rd/tinymce/plugins/images/connector/php/exifReader.php | phpExifReader.debug | function debug($str, $TYPE = 0, $file = "", $line = 0)
{
if ($this->debug)
{
echo "<br>[$file:$line:" . ($this->getDiffTime()) . "]$str";
flush();
if ($TYPE == 1)
{
exit;
}
}
} | php | function debug($str, $TYPE = 0, $file = "", $line = 0)
{
if ($this->debug)
{
echo "<br>[$file:$line:" . ($this->getDiffTime()) . "]$str";
flush();
if ($TYPE == 1)
{
exit;
}
}
} | [
"function",
"debug",
"(",
"$",
"str",
",",
"$",
"TYPE",
"=",
"0",
",",
"$",
"file",
"=",
"\"\"",
",",
"$",
"line",
"=",
"0",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"debug",
")",
"{",
"echo",
"\"<br>[$file:$line:\"",
".",
"(",
"$",
"this",
"->"... | Show Debugging information
@param string $str Debugging message to display
@param int $TYPE Type of error (0 - Warning, 1 - Error)
@param string $file
@param int $line
@return void | [
"Show",
"Debugging",
"information"
] | train | https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/ext-3rd/tinymce/plugins/images/connector/php/exifReader.php#L430-L441 |
Eresus/EresusCMS | src/ext-3rd/tinymce/plugins/images/connector/php/exifReader.php | phpExifReader.processFile | public function processFile()
{
/** don't reparse the whole file. */
if (!$this->newFile)
{
return true;
}
if (!file_exists($this->file))
{
echo "<br>Error: File " . ($this->file) . "does not exists!";
exit;
}
$this->debug("Stating Processing of " . $this->newFile, 0, __FILE__, __LINE__);
$i = 0;
$exitAll = 0;
/** Open the JPEG in binary safe reading mode */
$fp = fopen($this->file, "rb");
$this->ImageInfo["h"]["FileName"] = $this->file;
$this->ImageInfo["h"]["FileSize"] = filesize($this->file);
/** Size of the File */
$this->ImageInfo["h"]["FileDateTime"] = filectime($this->file);
/** File node change time */
/** check whether jped image or not */
$a = fgetc($fp);
if (ord($a) != 0xff || ord(fgetc($fp)) != M_SOI)
{
$this->debug("Not a JPEG FILE", 1);
$this->errorno = 1;
$this->errorstr = "File '" . $this->file . "' is not a JPEG File!";
}
$tmpTestLevel = 0;
/** Examines each byte one-by-one */
while (!feof($fp))
{
$marker = -1;
for ($a = 0; $a < 7; $a++)
{
$marker = fgetc($fp);
if (ord($marker) != 0xff)
{
break;
}
if ($a >= 6)
{
$this->errno = 10;
$this->errstr = "too many padding bytes!";
$this->debug($this->errstr, 1);
return false;
}
}
if (ord($marker) == 0xff)
{
// 0xff is legal padding, but if we get that many, something wrong.
$this->errno = 10;
$this->errstr = "too many padding bytes!";
$this->debug($this->errstr, 1);
}
$marker = ord($marker);
$this->sections[$this->currSection]["type"] = $marker;
// Read the length of the section.
$lh = ord(fgetc($fp));
$ll = ord(fgetc($fp));
$itemLength = ($lh << 8) | $ll;
if ($itemLength < 2)
{
$this->errno = 11;
$this->errstr = "invalid marker";
$this->debug($this->errstr, 1);
}
$this->sections[$this->currSection]["size"] = $itemLength;
$tmpDataArr = array();
/** Temporary Array */
$tmpStr = fread($fp, $itemLength - 2);
/*
$tmpDataArr[] = chr($lh);
$tmpDataArr[] = chr($ll);
$chars = preg_split('//', $tmpStr, -1, PREG_SPLIT_NO_EMPTY);
$tmpDataArr = array_merge($tmpDataArr,$chars);
$data = $tmpDataArr;
*/
$data = chr($lh) . chr($ll) . $tmpStr;
//$this->sections[$this->currSection]["data"] = $data;
$this->debug("<hr><h1>" . $this->currSection . ":</h1>");
//print_r($data);
$this->debug("<hr>");
//if(count($data) != $itemlen) {
if (strlen($data) != $itemLength)
{
$this->errno = 12;
$this->errstr = "Premature end of file?";
$this->debug($this->errstr, 1);
}
$this->currSection++;
/** */
switch ($marker)
{
case M_SOS:
$this->debug("<br>Found '" . M_SOS . "' Section, Prcessing it... <br>");;
// If reading entire image is requested, read the rest of the data.
if ($this->ImageReadMode & $this->ReadMode["READ_IMAGE"])
{
// Determine how much file is left.
$cp = ftell($fp);
fseek($fp, 0, SEEK_END);
$ep = ftell($fp);
fseek($fp, $cp, SEEK_SET);
$size = $ep - $cp;
$got = fread($fp, $size);
$this->sections[$this->currSection]["data"] = $got;
$this->sections[$this->currSection]["size"] = $size;
$this->sections[$this->currSection]["type"] = PSEUDO_IMAGE_MARKER;
$this->currSection++;
$HaveAll = 1;
$exitAll = 1;
}
$this->debug("<br>'" . M_SOS . "' Section, PROCESSED<br>");
break;
case M_COM: // Comment section
$this->debug("<br>Found '" . M_COM . "'(Comment) Section, Processing<br>");
$this->process_COM($data, $itemLength);
$this->debug("<br>'" . M_COM . "'(Comment) Section, PROCESSED<br>");
$tmpTestLevel++;
break;
case M_SOI:
$this->debug(" <br> === START OF IMAGE =====<br>");
break;
case M_EOI:
$this->debug(" <br>=== END OF IMAGE =====<br> ");
break;
case M_JFIF:
// Regular jpegs always have this tag, exif images have the exif
// marker instead, althogh ACDsee will write images with both markers.
// this program will re-create this marker on absence of exif marker.
// hence no need to keep the copy from the file.
//echo " <br> === M_JFIF =====<br>";
$this->sections[--$this->currSection]["data"] = "";
break;
case M_EXIF:
// Seen files from some 'U-lead' software with Vivitar scanner
// that uses marker 31 for non exif stuff. Thus make sure
// it says 'Exif' in the section before treating it as exif.
$this->debug("<br>Found '" . M_EXIF . "'(Exif) Section, Proccessing<br>");
$this->exifSection = $this->currSection - 1;
if (($this->ImageReadMode & $this->ReadMode["READ_EXIF"]) && ($data[2] . $data[3] . $data[4] . $data[5]) == "Exif")
{
$this->process_EXIF($data, $itemLength);
}
else
{
// Discard this section.
$this->sections[--$this->currSection]["data"] = "";
}
$this->debug("<br>'" . M_EXIF . "'(Exif) Section, PROCESSED<br>");
$tmpTestLevel++;
break;
case M_SOF0:
case M_SOF1:
case M_SOF2:
case M_SOF3:
case M_SOF5:
case M_SOF6:
case M_SOF7:
case M_SOF9:
case M_SOF10:
case M_SOF11:
case M_SOF13:
case M_SOF14:
case M_SOF15:
$this->debug("<br>Found M_SOFn Section, Processing<br>");
$this->process_SOFn($data, $marker);
$this->debug("<br>M_SOFn Section, PROCESSED<br>");
break;
case M_EXIF_EXT: // 226 - Exif Extended Data
$this->debug("<br><b>Found 'Exif Extended Data' Section, Processing</b><br>-------------------------------<br>");
$this->process_EXT_EXIF($data, $itemLength);
$this->debug("<br>--------------------------PROCESSED<br>");
break;
case M_QUANTA: // 219 - Quantisation Table Definition
$this->debug("<br><b>Found 'Quantisation Table Definition' Section, Processing</b><br>-------------------------------<br>");
$this->debug("<br>--------------------------PROCESSED<br>");
break;
case M_HUFF: // Huffman Table
$this->debug("<br><b>Found 'Huffman Table' Section, Processing</b><br>-------------------------------<br>");
$this->debug("<br>--------------------------PROCESSED<br>");
break;
default:
$this->debug("DEFAULT: Jpeg section marker 0x$marker x size $itemLength\n");
}
$i++;
if ($exitAll == 1)
{
break;
}
//if($tmpTestLevel == 2) break;
}
fclose($fp);
$this->newFile = 0;
return null;
} | php | public function processFile()
{
/** don't reparse the whole file. */
if (!$this->newFile)
{
return true;
}
if (!file_exists($this->file))
{
echo "<br>Error: File " . ($this->file) . "does not exists!";
exit;
}
$this->debug("Stating Processing of " . $this->newFile, 0, __FILE__, __LINE__);
$i = 0;
$exitAll = 0;
/** Open the JPEG in binary safe reading mode */
$fp = fopen($this->file, "rb");
$this->ImageInfo["h"]["FileName"] = $this->file;
$this->ImageInfo["h"]["FileSize"] = filesize($this->file);
/** Size of the File */
$this->ImageInfo["h"]["FileDateTime"] = filectime($this->file);
/** File node change time */
/** check whether jped image or not */
$a = fgetc($fp);
if (ord($a) != 0xff || ord(fgetc($fp)) != M_SOI)
{
$this->debug("Not a JPEG FILE", 1);
$this->errorno = 1;
$this->errorstr = "File '" . $this->file . "' is not a JPEG File!";
}
$tmpTestLevel = 0;
/** Examines each byte one-by-one */
while (!feof($fp))
{
$marker = -1;
for ($a = 0; $a < 7; $a++)
{
$marker = fgetc($fp);
if (ord($marker) != 0xff)
{
break;
}
if ($a >= 6)
{
$this->errno = 10;
$this->errstr = "too many padding bytes!";
$this->debug($this->errstr, 1);
return false;
}
}
if (ord($marker) == 0xff)
{
// 0xff is legal padding, but if we get that many, something wrong.
$this->errno = 10;
$this->errstr = "too many padding bytes!";
$this->debug($this->errstr, 1);
}
$marker = ord($marker);
$this->sections[$this->currSection]["type"] = $marker;
// Read the length of the section.
$lh = ord(fgetc($fp));
$ll = ord(fgetc($fp));
$itemLength = ($lh << 8) | $ll;
if ($itemLength < 2)
{
$this->errno = 11;
$this->errstr = "invalid marker";
$this->debug($this->errstr, 1);
}
$this->sections[$this->currSection]["size"] = $itemLength;
$tmpDataArr = array();
/** Temporary Array */
$tmpStr = fread($fp, $itemLength - 2);
/*
$tmpDataArr[] = chr($lh);
$tmpDataArr[] = chr($ll);
$chars = preg_split('//', $tmpStr, -1, PREG_SPLIT_NO_EMPTY);
$tmpDataArr = array_merge($tmpDataArr,$chars);
$data = $tmpDataArr;
*/
$data = chr($lh) . chr($ll) . $tmpStr;
//$this->sections[$this->currSection]["data"] = $data;
$this->debug("<hr><h1>" . $this->currSection . ":</h1>");
//print_r($data);
$this->debug("<hr>");
//if(count($data) != $itemlen) {
if (strlen($data) != $itemLength)
{
$this->errno = 12;
$this->errstr = "Premature end of file?";
$this->debug($this->errstr, 1);
}
$this->currSection++;
/** */
switch ($marker)
{
case M_SOS:
$this->debug("<br>Found '" . M_SOS . "' Section, Prcessing it... <br>");;
// If reading entire image is requested, read the rest of the data.
if ($this->ImageReadMode & $this->ReadMode["READ_IMAGE"])
{
// Determine how much file is left.
$cp = ftell($fp);
fseek($fp, 0, SEEK_END);
$ep = ftell($fp);
fseek($fp, $cp, SEEK_SET);
$size = $ep - $cp;
$got = fread($fp, $size);
$this->sections[$this->currSection]["data"] = $got;
$this->sections[$this->currSection]["size"] = $size;
$this->sections[$this->currSection]["type"] = PSEUDO_IMAGE_MARKER;
$this->currSection++;
$HaveAll = 1;
$exitAll = 1;
}
$this->debug("<br>'" . M_SOS . "' Section, PROCESSED<br>");
break;
case M_COM: // Comment section
$this->debug("<br>Found '" . M_COM . "'(Comment) Section, Processing<br>");
$this->process_COM($data, $itemLength);
$this->debug("<br>'" . M_COM . "'(Comment) Section, PROCESSED<br>");
$tmpTestLevel++;
break;
case M_SOI:
$this->debug(" <br> === START OF IMAGE =====<br>");
break;
case M_EOI:
$this->debug(" <br>=== END OF IMAGE =====<br> ");
break;
case M_JFIF:
// Regular jpegs always have this tag, exif images have the exif
// marker instead, althogh ACDsee will write images with both markers.
// this program will re-create this marker on absence of exif marker.
// hence no need to keep the copy from the file.
//echo " <br> === M_JFIF =====<br>";
$this->sections[--$this->currSection]["data"] = "";
break;
case M_EXIF:
// Seen files from some 'U-lead' software with Vivitar scanner
// that uses marker 31 for non exif stuff. Thus make sure
// it says 'Exif' in the section before treating it as exif.
$this->debug("<br>Found '" . M_EXIF . "'(Exif) Section, Proccessing<br>");
$this->exifSection = $this->currSection - 1;
if (($this->ImageReadMode & $this->ReadMode["READ_EXIF"]) && ($data[2] . $data[3] . $data[4] . $data[5]) == "Exif")
{
$this->process_EXIF($data, $itemLength);
}
else
{
// Discard this section.
$this->sections[--$this->currSection]["data"] = "";
}
$this->debug("<br>'" . M_EXIF . "'(Exif) Section, PROCESSED<br>");
$tmpTestLevel++;
break;
case M_SOF0:
case M_SOF1:
case M_SOF2:
case M_SOF3:
case M_SOF5:
case M_SOF6:
case M_SOF7:
case M_SOF9:
case M_SOF10:
case M_SOF11:
case M_SOF13:
case M_SOF14:
case M_SOF15:
$this->debug("<br>Found M_SOFn Section, Processing<br>");
$this->process_SOFn($data, $marker);
$this->debug("<br>M_SOFn Section, PROCESSED<br>");
break;
case M_EXIF_EXT: // 226 - Exif Extended Data
$this->debug("<br><b>Found 'Exif Extended Data' Section, Processing</b><br>-------------------------------<br>");
$this->process_EXT_EXIF($data, $itemLength);
$this->debug("<br>--------------------------PROCESSED<br>");
break;
case M_QUANTA: // 219 - Quantisation Table Definition
$this->debug("<br><b>Found 'Quantisation Table Definition' Section, Processing</b><br>-------------------------------<br>");
$this->debug("<br>--------------------------PROCESSED<br>");
break;
case M_HUFF: // Huffman Table
$this->debug("<br><b>Found 'Huffman Table' Section, Processing</b><br>-------------------------------<br>");
$this->debug("<br>--------------------------PROCESSED<br>");
break;
default:
$this->debug("DEFAULT: Jpeg section marker 0x$marker x size $itemLength\n");
}
$i++;
if ($exitAll == 1)
{
break;
}
//if($tmpTestLevel == 2) break;
}
fclose($fp);
$this->newFile = 0;
return null;
} | [
"public",
"function",
"processFile",
"(",
")",
"{",
"/** don't reparse the whole file. */",
"if",
"(",
"!",
"$",
"this",
"->",
"newFile",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"this",
"->",
"file",
")",
")",
"{",
... | Processes the whole file. | [
"Processes",
"the",
"whole",
"file",
"."
] | train | https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/ext-3rd/tinymce/plugins/images/connector/php/exifReader.php#L447-L670 |
Eresus/EresusCMS | src/ext-3rd/tinymce/plugins/images/connector/php/exifReader.php | phpExifReader.assign | function assign($file)
{
if (!empty($file))
{
$this->file = $file;
}
/** check for existance of file! */
if (!file_exists($this->file))
{
$this->errorno = 1;
$this->errorstr = "File '" . $this->file . "' does not exists!";
}
$this->newFile = 1;
} | php | function assign($file)
{
if (!empty($file))
{
$this->file = $file;
}
/** check for existance of file! */
if (!file_exists($this->file))
{
$this->errorno = 1;
$this->errorstr = "File '" . $this->file . "' does not exists!";
}
$this->newFile = 1;
} | [
"function",
"assign",
"(",
"$",
"file",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"file",
")",
")",
"{",
"$",
"this",
"->",
"file",
"=",
"$",
"file",
";",
"}",
"/** check for existance of file! */",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"this",... | Changing / Assiging new file
@param string $file JPEG file to process | [
"Changing",
"/",
"Assiging",
"new",
"file",
"@param",
"string",
"$file",
"JPEG",
"file",
"to",
"process"
] | train | https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/ext-3rd/tinymce/plugins/images/connector/php/exifReader.php#L677-L692 |
Eresus/EresusCMS | src/ext-3rd/tinymce/plugins/images/connector/php/exifReader.php | phpExifReader.process_SOFn | function process_SOFn($data, $marker)
{
$data_precision = 0;
$num_components = 0;
$data_precision = ord($data[2]);
if ($this->debug)
{
print("Image Dimension Calculation:");
print("((ord($data[3]) << 8) | ord($data[4]));");
}
$this->ImageInfo["h"]["Height"] = ((ord($data[3]) << 8) | ord($data[4]));
$this->ImageInfo["h"]["Width"] = ((ord($data[5]) << 8) | ord($data[6]));
$num_components = ord($data[7]);
if ($num_components == 3)
{
$this->ImageInfo["h"]["IsColor"] = 1;
}
else
{
$this->ImageInfo["h"]["IsColor"] = 0;
}
$this->ImageInfo["h"]["Process"] = $marker;
$this->debug("JPEG image is " . $this->ImageInfo["h"]["Width"] . " * " . $this->ImageInfo["h"]["Height"] . ", $num_components color components, $data_precision bits per sample\n");
} | php | function process_SOFn($data, $marker)
{
$data_precision = 0;
$num_components = 0;
$data_precision = ord($data[2]);
if ($this->debug)
{
print("Image Dimension Calculation:");
print("((ord($data[3]) << 8) | ord($data[4]));");
}
$this->ImageInfo["h"]["Height"] = ((ord($data[3]) << 8) | ord($data[4]));
$this->ImageInfo["h"]["Width"] = ((ord($data[5]) << 8) | ord($data[6]));
$num_components = ord($data[7]);
if ($num_components == 3)
{
$this->ImageInfo["h"]["IsColor"] = 1;
}
else
{
$this->ImageInfo["h"]["IsColor"] = 0;
}
$this->ImageInfo["h"]["Process"] = $marker;
$this->debug("JPEG image is " . $this->ImageInfo["h"]["Width"] . " * " . $this->ImageInfo["h"]["Height"] . ", $num_components color components, $data_precision bits per sample\n");
} | [
"function",
"process_SOFn",
"(",
"$",
"data",
",",
"$",
"marker",
")",
"{",
"$",
"data_precision",
"=",
"0",
";",
"$",
"num_components",
"=",
"0",
";",
"$",
"data_precision",
"=",
"ord",
"(",
"$",
"data",
"[",
"2",
"]",
")",
";",
"if",
"(",
"$",
... | Process SOFn section of Image
@param array $data An array containing whole section.
@param string $marker Marker to specify the type of section. | [
"Process",
"SOFn",
"section",
"of",
"Image",
"@param",
"array",
"$data",
"An",
"array",
"containing",
"whole",
"section",
".",
"@param",
"string",
"$marker",
"Marker",
"to",
"specify",
"the",
"type",
"of",
"section",
"."
] | train | https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/ext-3rd/tinymce/plugins/images/connector/php/exifReader.php#L700-L728 |
Eresus/EresusCMS | src/ext-3rd/tinymce/plugins/images/connector/php/exifReader.php | phpExifReader.process_COM | function process_COM($data, $length)
{
if ($length > MAX_COMMENT)
{
$length = MAX_COMMENT;
}
/** Truncate if it won't fit in our structure. */
$nch = 0;
$Comment = "";
for ($a = 2; $a < $length; $a++)
{
$ch = $data[$a];
if ($ch == '\r' && $data[$a + 1] == '\n')
{
continue;
} // Remove cr followed by lf.
$Comment .= $ch;
}
//$this->ImageInfo[M_COM] = $Comment;
$this->ImageInfo["h"]["imageComment"] = $this->string_format($Comment);
$this->debug("COM marker comment: $Comment\n");
} | php | function process_COM($data, $length)
{
if ($length > MAX_COMMENT)
{
$length = MAX_COMMENT;
}
/** Truncate if it won't fit in our structure. */
$nch = 0;
$Comment = "";
for ($a = 2; $a < $length; $a++)
{
$ch = $data[$a];
if ($ch == '\r' && $data[$a + 1] == '\n')
{
continue;
} // Remove cr followed by lf.
$Comment .= $ch;
}
//$this->ImageInfo[M_COM] = $Comment;
$this->ImageInfo["h"]["imageComment"] = $this->string_format($Comment);
$this->debug("COM marker comment: $Comment\n");
} | [
"function",
"process_COM",
"(",
"$",
"data",
",",
"$",
"length",
")",
"{",
"if",
"(",
"$",
"length",
">",
"MAX_COMMENT",
")",
"{",
"$",
"length",
"=",
"MAX_COMMENT",
";",
"}",
"/** Truncate if it won't fit in our structure. */",
"$",
"nch",
"=",
"0",
";",
... | Process Comments
@param array $data Section data
@param int $length Length of the section | [
"Process",
"Comments",
"@param",
"array",
"$data",
"Section",
"data",
"@param",
"int",
"$length",
"Length",
"of",
"the",
"section"
] | train | https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/ext-3rd/tinymce/plugins/images/connector/php/exifReader.php#L736-L759 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.