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_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
bennybi/yii2-cza-base | models/traits/TreeTrait.php | TreeTrait.getBreadcrumbs | public function getBreadcrumbs($depth = 1, $glue = ' » ', $currCss = 'kv-crumb-active', $new = 'Untitled') {
/**
* @var Tree $this
*/
if ($this->isNewRecord || empty($this)) {
return $currCss ? Html::tag('span', $new, ['class' => $currCss]) : $new;
}
$depth = empty($depth) ? null : intval($depth);
$module = Yii::$app->controller->module;
$nameAttribute = ArrayHelper::getValue($module->dataStructure, 'nameAttribute', 'name');
$crumbNodes = $depth === null ? $this->parents()->all() : $this->parents($depth - 1)->all();
$crumbNodes[] = $this;
$i = 1;
$len = count($crumbNodes);
$crumbs = [];
foreach ($crumbNodes as $node) {
$name = $node->$nameAttribute;
if ($i === $len && $currCss) {
$name = Html::tag('span', $name, ['class' => $currCss]);
}
$crumbs[] = $name;
$i++;
}
return implode($glue, $crumbs);
} | php | public function getBreadcrumbs($depth = 1, $glue = ' » ', $currCss = 'kv-crumb-active', $new = 'Untitled') {
/**
* @var Tree $this
*/
if ($this->isNewRecord || empty($this)) {
return $currCss ? Html::tag('span', $new, ['class' => $currCss]) : $new;
}
$depth = empty($depth) ? null : intval($depth);
$module = Yii::$app->controller->module;
$nameAttribute = ArrayHelper::getValue($module->dataStructure, 'nameAttribute', 'name');
$crumbNodes = $depth === null ? $this->parents()->all() : $this->parents($depth - 1)->all();
$crumbNodes[] = $this;
$i = 1;
$len = count($crumbNodes);
$crumbs = [];
foreach ($crumbNodes as $node) {
$name = $node->$nameAttribute;
if ($i === $len && $currCss) {
$name = Html::tag('span', $name, ['class' => $currCss]);
}
$crumbs[] = $name;
$i++;
}
return implode($glue, $crumbs);
} | Generate and return the breadcrumbs for the node.
@param integer $depth the breadcrumbs parent depth
@param string $glue the pattern to separate the breadcrumbs
@param string $currCss the CSS class to be set for current node
@param string $new the name to be displayed for a new node
@return string the parsed breadcrumbs | https://github.com/bennybi/yii2-cza-base/blob/8257db8034bd948712fa469062921f210f0ba8da/models/traits/TreeTrait.php#L393-L417 |
silvercommerce/contact-admin | src/bulkhandler/AddRelatedHandler.php | AddRelatedHandler.Link | public function Link($action = null)
{
return Controller::join_links(
parent::Link(),
$this->config()->url_segment,
$action
);
} | php | public function Link($action = null)
{
return Controller::join_links(
parent::Link(),
$this->config()->url_segment,
$action
);
} | Return URL to this RequestHandler
@param string $action Action to append to URL
@return string URL | https://github.com/silvercommerce/contact-admin/blob/32cbc2ef2589f93f9dd1796e5db2f11ad15d888c/src/bulkhandler/AddRelatedHandler.php#L44-L51 |
silvercommerce/contact-admin | src/bulkhandler/AddRelatedHandler.php | AddRelatedHandler.Breadcrumbs | public function Breadcrumbs($unlinked = false)
{
if (!Controller::curr()->hasMethod('Breadcrumbs')) {
return;
}
$items = Controller::curr()->Breadcrumbs($unlinked);
$items->push(ArrayData::create([
'Title' => $this->getI18nLabel(),
'Link' => false,
]));
return $items;
} | php | public function Breadcrumbs($unlinked = false)
{
if (!Controller::curr()->hasMethod('Breadcrumbs')) {
return;
}
$items = Controller::curr()->Breadcrumbs($unlinked);
$items->push(ArrayData::create([
'Title' => $this->getI18nLabel(),
'Link' => false,
]));
return $items;
} | Edited version of the GridFieldEditForm function
adds the 'Bulk Upload' at the end of the crums.
CMS-specific functionality: Passes through navigation breadcrumbs
to the template, and includes the currently edited record (if any).
see {@link LeftAndMain->Breadcrumbs()} for details.
@author SilverStripe original Breadcrumbs() method
@see GridFieldDetailForm_ItemRequest
@param bool $unlinked
@return ArrayData | https://github.com/silvercommerce/contact-admin/blob/32cbc2ef2589f93f9dd1796e5db2f11ad15d888c/src/bulkhandler/AddRelatedHandler.php#L86-L99 |
mmeyer2k/temper | src/Temper.php | Temper.rename | public function rename($name)
{
$newPath = sys_get_temp_dir() . "/$name";
$ret = rename($this->path(), $newPath);
$this->path = $newPath;
return $ret;
} | php | public function rename($name)
{
$newPath = sys_get_temp_dir() . "/$name";
$ret = rename($this->path(), $newPath);
$this->path = $newPath;
return $ret;
} | /*
Rename the file in the same directory. Overwrite if existing.
@return boolean Return true on success, false of failure. | https://github.com/mmeyer2k/temper/blob/f3f4b726a0ad332030538f728c40bd064cecf97d/src/Temper.php#L54-L61 |
atelierspierrot/templatengine | src/TemplateEngine/TemplateObject/TitleTag.php | TitleTag.set | public function set(array $strs)
{
if (!empty($strs)) {
foreach ($strs as $_str) {
$this->add($_str);
}
}
return $this;
} | php | public function set(array $strs)
{
if (!empty($strs)) {
foreach ($strs as $_str) {
$this->add($_str);
}
}
return $this;
} | Set a strings stack to build page header title
@param array $strs An array of title strings
@return self
@see self::add() | https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/TemplateEngine/TemplateObject/TitleTag.php#L79-L87 |
atelierspierrot/templatengine | src/TemplateEngine/TemplateObject/TitleTag.php | TitleTag.write | public function write($mask = '%s')
{
$str='';
foreach ($this->cleanStack($this->get()) as $entry) {
$str .= (strlen($str)>0 ? $this->separator : '').$entry;
}
$title_str = Html::writeHtmlTag('title', strip_tags($str));
return sprintf($mask, $title_str);
} | php | public function write($mask = '%s')
{
$str='';
foreach ($this->cleanStack($this->get()) as $entry) {
$str .= (strlen($str)>0 ? $this->separator : '').$entry;
}
$title_str = Html::writeHtmlTag('title', strip_tags($str));
return sprintf($mask, $title_str);
} | Write the Template Object strings ready for template display
@param string $mask A mask to write each line via "sprintf()"
@return string The string to display fot this template object | https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/TemplateEngine/TemplateObject/TitleTag.php#L105-L113 |
OpenResourceManager/client-laravel | src/ORMServiceProvider.php | ORMServiceProvider.register | public function register()
{
$this->mergeConfigFrom(__DIR__ . '/../config/orm.php', 'orm');
$this->app->singleton('orm', function ($app) {
$config = $app->make('config');
$host = $config->get('orm.host');
$version = $config->get('orm.version') ?: 1;
$port = $config->get('orm.port') ?: 80;
$secret = $config->get('orm.secret');
$useSSL = $config->get('orm.use_ssl') ?: false;
return new ORMService($secret, $host, $version, $port, $useSSL);
});
} | php | public function register()
{
$this->mergeConfigFrom(__DIR__ . '/../config/orm.php', 'orm');
$this->app->singleton('orm', function ($app) {
$config = $app->make('config');
$host = $config->get('orm.host');
$version = $config->get('orm.version') ?: 1;
$port = $config->get('orm.port') ?: 80;
$secret = $config->get('orm.secret');
$useSSL = $config->get('orm.use_ssl') ?: false;
return new ORMService($secret, $host, $version, $port, $useSSL);
});
} | Register the application services.
@return void | https://github.com/OpenResourceManager/client-laravel/blob/2c33acff8439fe9bdc620b3059d5a0d7d8caefe9/src/ORMServiceProvider.php#L26-L39 |
luoxiaojun1992/lb_framework | controllers/web/WebController.php | WebController.injectDebugBar | protected function injectDebugBar($output)
{
if (!($debugBarConfig = Lb::app()->getConfigByName('debugbar'))) {
return $output;
}
if (empty($debugBarConfig['enabled'])) {
return $output;
}
if (empty($debugBarConfig['baseUrl'])) {
return $output;
}
if (empty($debugBarConfig['basePath'])) {
return $output;
}
/**
* @var StandardDebugBar $debugBar
*/
$debugBar = DebugBar::getInstance();
$debugBarRenderer = $debugBar->getJavascriptRenderer($debugBarConfig['baseUrl'], $debugBarConfig['basePath']);
$debugBarComponent = $debugBarRenderer->renderHead() . $debugBarRenderer->render();
$replace = <<<EOF
{$debugBarComponent}
</body>
EOF;
return str_replace('</body>', $replace, $output);
} | php | protected function injectDebugBar($output)
{
if (!($debugBarConfig = Lb::app()->getConfigByName('debugbar'))) {
return $output;
}
if (empty($debugBarConfig['enabled'])) {
return $output;
}
if (empty($debugBarConfig['baseUrl'])) {
return $output;
}
if (empty($debugBarConfig['basePath'])) {
return $output;
}
/**
* @var StandardDebugBar $debugBar
*/
$debugBar = DebugBar::getInstance();
$debugBarRenderer = $debugBar->getJavascriptRenderer($debugBarConfig['baseUrl'], $debugBarConfig['basePath']);
$debugBarComponent = $debugBarRenderer->renderHead() . $debugBarRenderer->render();
$replace = <<<EOF
{$debugBarComponent}
</body>
EOF;
return str_replace('</body>', $replace, $output);
} | Inject debug bar to html output
@param $output
@return mixed | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/controllers/web/WebController.php#L169-L195 |
luoxiaojun1992/lb_framework | controllers/web/WebController.php | WebController.api | public function api()
{
$scan = Lb::app()->getRootDir() . DIRECTORY_SEPARATOR . 'controllers';
$exclude = [];
$api_doc_config = Lb::app()->getApiDocConfig();
if ($api_doc_config) {
if (isset($api_doc_config['scan']) && $api_doc_config['scan']) {
$scan = $api_doc_config['scan'];
}
if (isset($api_doc_config['exclude']) && $api_doc_config['exclude']) {
$exclude = $api_doc_config['exclude'];
}
}
header('Content-Type: application/json');
$swagger = \Swagger\scan(
$scan, [
'exclude' => $exclude,
]
);
echo $swagger;
} | php | public function api()
{
$scan = Lb::app()->getRootDir() . DIRECTORY_SEPARATOR . 'controllers';
$exclude = [];
$api_doc_config = Lb::app()->getApiDocConfig();
if ($api_doc_config) {
if (isset($api_doc_config['scan']) && $api_doc_config['scan']) {
$scan = $api_doc_config['scan'];
}
if (isset($api_doc_config['exclude']) && $api_doc_config['exclude']) {
$exclude = $api_doc_config['exclude'];
}
}
header('Content-Type: application/json');
$swagger = \Swagger\scan(
$scan, [
'exclude' => $exclude,
]
);
echo $swagger;
} | API文档 | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/controllers/web/WebController.php#L262-L282 |
wearesho-team/cpa-integration | src/Postback/PostbackService.php | PostbackService.send | public function send(ConversionInterface $conversion): ResponseInterface
{
foreach ($this->services as $service) {
if (is_null($service->getConfig())) {
$config = $this->config->getConfiguredConfigInstance($service);
if ($config instanceof PostbackServiceConfigInterface) {
$service->setConfig($config);
} else {
continue;
}
}
try {
return $service->send($conversion);
} catch (UnsupportedConversionTypeException $exception) {
continue;
}
}
throw new UnsupportedConversionTypeException($this, $conversion);
} | php | public function send(ConversionInterface $conversion): ResponseInterface
{
foreach ($this->services as $service) {
if (is_null($service->getConfig())) {
$config = $this->config->getConfiguredConfigInstance($service);
if ($config instanceof PostbackServiceConfigInterface) {
$service->setConfig($config);
} else {
continue;
}
}
try {
return $service->send($conversion);
} catch (UnsupportedConversionTypeException $exception) {
continue;
}
}
throw new UnsupportedConversionTypeException($this, $conversion);
} | Try each service to send conversion, while getting UnsupportedConversionException
@param ConversionInterface $conversion
@throws UnsupportedConversionTypeException
@throws DuplicatedConversionException
@throws RequestException
@return ResponseInterface | https://github.com/wearesho-team/cpa-integration/blob/6b78d2315e893ecf09132ae3e9d8e8c1b5ae6291/src/Postback/PostbackService.php#L113-L132 |
ekyna/AdminBundle | Install/AdminInstaller.php | AdminInstaller.install | public function install(Command $command, InputInterface $input, OutputInterface $output)
{
$output->writeln('<info>[Admin] Creating users groups:</info>');
$this->createGroups($output);
$output->writeln('');
$output->writeln('<info>[Admin] Generating Acl rules:</info>');
$this->createAclRules($output);
$output->writeln('');
if (!$input->getOption('no-interaction')) {
$output->writeln('<info>[Admin] Creating Super Admin:</info>');
$this->createSuperAdmin($command, $output);
$output->writeln('');
}
} | php | public function install(Command $command, InputInterface $input, OutputInterface $output)
{
$output->writeln('<info>[Admin] Creating users groups:</info>');
$this->createGroups($output);
$output->writeln('');
$output->writeln('<info>[Admin] Generating Acl rules:</info>');
$this->createAclRules($output);
$output->writeln('');
if (!$input->getOption('no-interaction')) {
$output->writeln('<info>[Admin] Creating Super Admin:</info>');
$this->createSuperAdmin($command, $output);
$output->writeln('');
}
} | {@inheritdoc} | https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Install/AdminInstaller.php#L48-L63 |
ekyna/AdminBundle | Install/AdminInstaller.php | AdminInstaller.createGroups | private function createGroups(OutputInterface $output)
{
$em = $this->container->get('ekyna_user.group.manager');
$repository = $this->container->get('ekyna_user.group.repository');
foreach ($this->defaultGroups as $name => $options) {
$output->write(sprintf(
'- <comment>%s</comment> %s ',
$name,
str_pad('.', 44 - mb_strlen($name), '.', STR_PAD_LEFT)
));
if (null !== $group = $repository->findOneBy(['name' => $name])) {
$output->writeln('already exists.');
continue;
}
/** @var \Ekyna\Bundle\UserBundle\Model\GroupInterface $group */
$group = $repository->createNew();
$group
->setDefault($options[2])
->setName($name)
->setRoles($options[0])
;
$em->persist($group);
$output->writeln('created.');
}
$em->flush();
} | php | private function createGroups(OutputInterface $output)
{
$em = $this->container->get('ekyna_user.group.manager');
$repository = $this->container->get('ekyna_user.group.repository');
foreach ($this->defaultGroups as $name => $options) {
$output->write(sprintf(
'- <comment>%s</comment> %s ',
$name,
str_pad('.', 44 - mb_strlen($name), '.', STR_PAD_LEFT)
));
if (null !== $group = $repository->findOneBy(['name' => $name])) {
$output->writeln('already exists.');
continue;
}
/** @var \Ekyna\Bundle\UserBundle\Model\GroupInterface $group */
$group = $repository->createNew();
$group
->setDefault($options[2])
->setName($name)
->setRoles($options[0])
;
$em->persist($group);
$output->writeln('created.');
}
$em->flush();
} | Creates default groups entities
@param OutputInterface $output | https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Install/AdminInstaller.php#L70-L96 |
ekyna/AdminBundle | Install/AdminInstaller.php | AdminInstaller.createAclRules | private function createAclRules(OutputInterface $output)
{
$registry = $this->container->get('ekyna_admin.pool_registry');
$aclOperator = $this->container->get('ekyna_admin.acl_operator');
$groups = $this->container->get('ekyna_user.group.repository')->findAll();
// TODO disallow on ekyna_user.group for non super admin.
/** @var \Ekyna\Bundle\UserBundle\Entity\Group $group */
foreach ($groups as $group) {
if (isset($this->defaultGroups[$group->getName()])) {
$permission = $this->defaultGroups[$group->getName()][1];
} else {
continue;
}
$datas = [];
foreach ($registry->getConfigurations() as $id => $config) {
$datas[$id] = [$permission => true];
}
$aclOperator->updateGroup($group, $datas);
}
$output->writeln('Acl rules have been successfully generated.');
} | php | private function createAclRules(OutputInterface $output)
{
$registry = $this->container->get('ekyna_admin.pool_registry');
$aclOperator = $this->container->get('ekyna_admin.acl_operator');
$groups = $this->container->get('ekyna_user.group.repository')->findAll();
// TODO disallow on ekyna_user.group for non super admin.
/** @var \Ekyna\Bundle\UserBundle\Entity\Group $group */
foreach ($groups as $group) {
if (isset($this->defaultGroups[$group->getName()])) {
$permission = $this->defaultGroups[$group->getName()][1];
} else {
continue;
}
$datas = [];
foreach ($registry->getConfigurations() as $id => $config) {
$datas[$id] = [$permission => true];
}
$aclOperator->updateGroup($group, $datas);
}
$output->writeln('Acl rules have been successfully generated.');
} | Creates default groups permissions for each admin pool configurations (if available)
@param OutputInterface $output
@return number | https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Install/AdminInstaller.php#L105-L128 |
ekyna/AdminBundle | Install/AdminInstaller.php | AdminInstaller.createSuperAdmin | private function createSuperAdmin(Command $command, OutputInterface $output)
{
$groupRepository = $this->container->get('ekyna_user.group.repository');
$userRepository = $this->container->get('ekyna_user.user.repository');
/** @var \Ekyna\Bundle\UserBundle\Model\GroupInterface $group */
if (null === $group = $groupRepository->findOneBy(['name' => array_keys($this->defaultGroups)[0]])) {
$output->writeln('Super admin group not found, aborting.');
return;
}
/** @var \Ekyna\Bundle\UserBundle\Model\UserInterface $superAdmin */
if (null !== $superAdmin = $userRepository->findOneBy(['group' => $group])) {
$output->writeln(sprintf('Super admin already exists (<comment>%s</comment>).', $superAdmin->getEmail()));
return;
}
$output->writeln('<question>Please provide initial informations ...</question>');
/** @var \Symfony\Component\Console\Helper\DialogHelper $dialog */
$dialog = $command->getHelperSet()->get('dialog');
$email = $dialog->askAndValidate($output, 'Email: ', function ($answer) use ($userRepository) {
if (!filter_var($answer, FILTER_VALIDATE_EMAIL)) {
throw new \RuntimeException('This is not a valid email address.');
}
if (null !== $userRepository->findOneBy(['email' => $answer])) {
throw new \RuntimeException('This email address is already used.');
}
return $answer;
}, 3);
$password = $dialog->askAndValidate($output, 'Password: ', function ($answer) {
if (!(preg_match('#^[a-zA-Z0-9]+$#', $answer) && strlen($answer) > 5)) {
throw new \RuntimeException('Password should be composed of at least 6 letters and numbers.');
}
return $answer;
}, 3);
$notBlankValidator = function ($answer) {
if (0 === strlen($answer)) {
throw new \RuntimeException('This cannot be blank.');
}
return $answer;
};
$firstName = $dialog->askAndValidate($output, 'First name: ', $notBlankValidator, 3);
$lastName = $dialog->askAndValidate($output, 'Last name: ', $notBlankValidator, 3);
$userManager = $this->container->get('fos_user.user_manager');
/** @var \Ekyna\Bundle\UserBundle\Model\UserInterface $user */
$user = $userManager->createUser();
$user
->setGroup($group)
->setGender('mr')
->setFirstName($firstName)
->setLastName($lastName)
->setPlainPassword($password)
->setEmail($email)
->setEnabled(true);
$userManager->updateUser($user);
$output->writeln('Super Admin has been successfully created.');
} | php | private function createSuperAdmin(Command $command, OutputInterface $output)
{
$groupRepository = $this->container->get('ekyna_user.group.repository');
$userRepository = $this->container->get('ekyna_user.user.repository');
/** @var \Ekyna\Bundle\UserBundle\Model\GroupInterface $group */
if (null === $group = $groupRepository->findOneBy(['name' => array_keys($this->defaultGroups)[0]])) {
$output->writeln('Super admin group not found, aborting.');
return;
}
/** @var \Ekyna\Bundle\UserBundle\Model\UserInterface $superAdmin */
if (null !== $superAdmin = $userRepository->findOneBy(['group' => $group])) {
$output->writeln(sprintf('Super admin already exists (<comment>%s</comment>).', $superAdmin->getEmail()));
return;
}
$output->writeln('<question>Please provide initial informations ...</question>');
/** @var \Symfony\Component\Console\Helper\DialogHelper $dialog */
$dialog = $command->getHelperSet()->get('dialog');
$email = $dialog->askAndValidate($output, 'Email: ', function ($answer) use ($userRepository) {
if (!filter_var($answer, FILTER_VALIDATE_EMAIL)) {
throw new \RuntimeException('This is not a valid email address.');
}
if (null !== $userRepository->findOneBy(['email' => $answer])) {
throw new \RuntimeException('This email address is already used.');
}
return $answer;
}, 3);
$password = $dialog->askAndValidate($output, 'Password: ', function ($answer) {
if (!(preg_match('#^[a-zA-Z0-9]+$#', $answer) && strlen($answer) > 5)) {
throw new \RuntimeException('Password should be composed of at least 6 letters and numbers.');
}
return $answer;
}, 3);
$notBlankValidator = function ($answer) {
if (0 === strlen($answer)) {
throw new \RuntimeException('This cannot be blank.');
}
return $answer;
};
$firstName = $dialog->askAndValidate($output, 'First name: ', $notBlankValidator, 3);
$lastName = $dialog->askAndValidate($output, 'Last name: ', $notBlankValidator, 3);
$userManager = $this->container->get('fos_user.user_manager');
/** @var \Ekyna\Bundle\UserBundle\Model\UserInterface $user */
$user = $userManager->createUser();
$user
->setGroup($group)
->setGender('mr')
->setFirstName($firstName)
->setLastName($lastName)
->setPlainPassword($password)
->setEmail($email)
->setEnabled(true);
$userManager->updateUser($user);
$output->writeln('Super Admin has been successfully created.');
} | Creates the super admin user.
@param Command $command
@param OutputInterface $output | https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Install/AdminInstaller.php#L136-L199 |
phpalchemy/phpalchemy | Alchemy/Annotation/Reader/Adapter/NotojReader.php | NotojReader.setCacheDir | public function setCacheDir($cacheDir)
{
parent::setCacheDir($cacheDir);
\Notoj\Notoj::enableCache($cacheDir . DIRECTORY_SEPARATOR . "_annotations.php");
} | php | public function setCacheDir($cacheDir)
{
parent::setCacheDir($cacheDir);
\Notoj\Notoj::enableCache($cacheDir . DIRECTORY_SEPARATOR . "_annotations.php");
} | {@inheritdoc} | https://github.com/phpalchemy/phpalchemy/blob/5b7e9b13acfda38c61b2da2639e8a56f298dc32e/Alchemy/Annotation/Reader/Adapter/NotojReader.php#L16-L20 |
phpalchemy/phpalchemy | Alchemy/Annotation/Reader/Adapter/NotojReader.php | NotojReader.getMethodAnnotationsObjects | public function getMethodAnnotationsObjects($class, $method)
{
$objects = $this->createAnnotationObjects($this->getMethodAnnotations($class, $method));
foreach ($objects as $object) {
$object->prepare();
}
return $objects;
} | php | public function getMethodAnnotationsObjects($class, $method)
{
$objects = $this->createAnnotationObjects($this->getMethodAnnotations($class, $method));
foreach ($objects as $object) {
$object->prepare();
}
return $objects;
} | {@inheritdoc} | https://github.com/phpalchemy/phpalchemy/blob/5b7e9b13acfda38c61b2da2639e8a56f298dc32e/Alchemy/Annotation/Reader/Adapter/NotojReader.php#L49-L58 |
phpalchemy/phpalchemy | Alchemy/Annotation/Reader/Adapter/NotojReader.php | NotojReader.createAnnotationObjects | protected function createAnnotationObjects(array $annotations)
{
$objects = array();
//var_dump($annotations);
foreach ($annotations as $name => $args) {
$name = ucfirst($name);
$class = $this->defaultNamespace . $name . 'Annotation';
if (in_array(strtolower($name), self::getExcludeAnnotationList())) {
continue;
}
if (! array_key_exists($class, $objects)) {
if (!class_exists($class)) {
if ($this->strict) {
throw new \Exception(sprintf('Annotation Class Not Found: %s', $class));
} else {
continue;
}
}
$objects[$name] = new $class();
}
//var_dump($args);
foreach ($args as $key => $value) {
$objects[$name]->set($key, $value);
}
}
return $objects;
} | php | protected function createAnnotationObjects(array $annotations)
{
$objects = array();
//var_dump($annotations);
foreach ($annotations as $name => $args) {
$name = ucfirst($name);
$class = $this->defaultNamespace . $name . 'Annotation';
if (in_array(strtolower($name), self::getExcludeAnnotationList())) {
continue;
}
if (! array_key_exists($class, $objects)) {
if (!class_exists($class)) {
if ($this->strict) {
throw new \Exception(sprintf('Annotation Class Not Found: %s', $class));
} else {
continue;
}
}
$objects[$name] = new $class();
}
//var_dump($args);
foreach ($args as $key => $value) {
$objects[$name]->set($key, $value);
}
}
return $objects;
} | Create annotations object
@param array $annotations annotated elements
@return array array of annoatated objects | https://github.com/phpalchemy/phpalchemy/blob/5b7e9b13acfda38c61b2da2639e8a56f298dc32e/Alchemy/Annotation/Reader/Adapter/NotojReader.php#L66-L98 |
phpalchemy/phpalchemy | Alchemy/Annotation/Reader/Adapter/NotojReader.php | NotojReader.convertAnnotationObj | protected function convertAnnotationObj($reflection)
{
$annotations = (array) $reflection->getAnnotations();
$result = array();
foreach ($annotations as $annotation) {
if (! array_key_exists($annotation['method'], $result)) {
$result[$annotation['method']] = array();
}
foreach ($annotation['args'] as $key => $value) {
if (is_numeric($key)) {
$result[$annotation['method']][] = $value;
} else {
$result[$annotation['method']][$key] = $value;
}
}
}
return $result;
} | php | protected function convertAnnotationObj($reflection)
{
$annotations = (array) $reflection->getAnnotations();
$result = array();
foreach ($annotations as $annotation) {
if (! array_key_exists($annotation['method'], $result)) {
$result[$annotation['method']] = array();
}
foreach ($annotation['args'] as $key => $value) {
if (is_numeric($key)) {
$result[$annotation['method']][] = $value;
} else {
$result[$annotation['method']][$key] = $value;
}
}
}
return $result;
} | This method converts Notoj returned array to reader data
@param Mixed/Reflection $reflection a Notoj reflection object
@return array annoations array | https://github.com/phpalchemy/phpalchemy/blob/5b7e9b13acfda38c61b2da2639e8a56f298dc32e/Alchemy/Annotation/Reader/Adapter/NotojReader.php#L106-L126 |
BenGorFile/FileBundle | src/BenGorFile/FileBundle/DependencyInjection/Compiler/Application/Query/QueryBuilder.php | QueryBuilder.build | public function build($file)
{
$this->register($file);
$this->container->setAlias(
$this->aliasDefinitionName($file),
$this->definitionName($file)
);
return $this->container;
} | php | public function build($file)
{
$this->register($file);
$this->container->setAlias(
$this->aliasDefinitionName($file),
$this->definitionName($file)
);
return $this->container;
} | {@inheritdoc} | https://github.com/BenGorFile/FileBundle/blob/82c1fa952e7e7b7a188141a34053ab612b699a21/src/BenGorFile/FileBundle/DependencyInjection/Compiler/Application/Query/QueryBuilder.php#L54-L64 |
valu-digital/valuso | src/ValuSo/Annotation/AnnotationBuilderFactory.php | AnnotationBuilderFactory.createService | public function createService(ServiceLocatorInterface $serviceLocator)
{
$config = $serviceLocator->get('Config');
$config = empty($config['valu_so']) ? [] : $config['valu_so'];
$annotationBuilder = new AnnotationBuilder();
// Attach custom annotations
if (!empty($config['annotations'])) {
$parser = new Parser\DoctrineAnnotationParser();
foreach($config['annotations'] as $name => $class){
$parser->registerAnnotation($class);
}
$annotationBuilder->getAnnotationManager()->attach($parser);
}
// Attach listeners for custom annotations
if (!empty($config['annotation_listeners'])) {
EventManagerConfigurator::configure(
$annotationBuilder->getEventManager(),
$serviceLocator,
$config['annotation_listeners']);
}
return $annotationBuilder;
} | php | public function createService(ServiceLocatorInterface $serviceLocator)
{
$config = $serviceLocator->get('Config');
$config = empty($config['valu_so']) ? [] : $config['valu_so'];
$annotationBuilder = new AnnotationBuilder();
// Attach custom annotations
if (!empty($config['annotations'])) {
$parser = new Parser\DoctrineAnnotationParser();
foreach($config['annotations'] as $name => $class){
$parser->registerAnnotation($class);
}
$annotationBuilder->getAnnotationManager()->attach($parser);
}
// Attach listeners for custom annotations
if (!empty($config['annotation_listeners'])) {
EventManagerConfigurator::configure(
$annotationBuilder->getEventManager(),
$serviceLocator,
$config['annotation_listeners']);
}
return $annotationBuilder;
} | Create an annotation builder for service broker
{@see ValuSo\Broker\ServiceBroker} uses {@see Zend\ServiceManager\ServiceManager} internally to initialize service
instances. {@see Zend\Mvc\Service\ServiceManagerConfig} for how to configure service manager.
This factory uses following configuration scheme:
<code>
[
'valu_so' => [
'annotations' => [
'<id>' => '',
],
'annotation_listeners' => [
'<ServiceID>'
]
]
]
</code>
@see \Zend\ServiceManager\FactoryInterface::createService()
@return ServiceBroker | https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Annotation/AnnotationBuilderFactory.php#L40-L67 |
makinacorpus/drupal-umenu | src/CachedItemStorageProxy.php | CachedItemStorageProxy.insert | public function insert(int $menuId, int $nodeId, string $title, $description = null): int
{
$ret = $this->nested->insert($menuId, $nodeId, $title, $description);
$this->cache->delete($this->getCacheId($menuId));
return $ret;
} | php | public function insert(int $menuId, int $nodeId, string $title, $description = null): int
{
$ret = $this->nested->insert($menuId, $nodeId, $title, $description);
$this->cache->delete($this->getCacheId($menuId));
return $ret;
} | {@inheritdoc} | https://github.com/makinacorpus/drupal-umenu/blob/346574eb0f5982857c64144e99ad2eacc8c52c5b/src/CachedItemStorageProxy.php#L54-L60 |
makinacorpus/drupal-umenu | src/CachedItemStorageProxy.php | CachedItemStorageProxy.insertAfter | public function insertAfter(int $otherItemId, int $nodeId, string $title, $description = null): int
{
$ret = $this->nested->insertAfter($otherItemId, $nodeId, $title, $description);
$this->cache->delete($this->getCacheIdFrom($otherItemId));
return $ret;
} | php | public function insertAfter(int $otherItemId, int $nodeId, string $title, $description = null): int
{
$ret = $this->nested->insertAfter($otherItemId, $nodeId, $title, $description);
$this->cache->delete($this->getCacheIdFrom($otherItemId));
return $ret;
} | {@inheritdoc} | https://github.com/makinacorpus/drupal-umenu/blob/346574eb0f5982857c64144e99ad2eacc8c52c5b/src/CachedItemStorageProxy.php#L76-L82 |
makinacorpus/drupal-umenu | src/CachedItemStorageProxy.php | CachedItemStorageProxy.update | public function update(int $itemId, $nodeId = null, $title = null, $description = null)
{
$ret = $this->nested->update($itemId, $nodeId, $title, $description);
$this->cache->delete($this->getCacheIdFrom($itemId));
return $ret;
} | php | public function update(int $itemId, $nodeId = null, $title = null, $description = null)
{
$ret = $this->nested->update($itemId, $nodeId, $title, $description);
$this->cache->delete($this->getCacheIdFrom($itemId));
return $ret;
} | {@inheritdoc} | https://github.com/makinacorpus/drupal-umenu/blob/346574eb0f5982857c64144e99ad2eacc8c52c5b/src/CachedItemStorageProxy.php#L98-L104 |
makinacorpus/drupal-umenu | src/CachedItemStorageProxy.php | CachedItemStorageProxy.moveAsChild | public function moveAsChild(int $itemId, int $otherItemId)
{
$ret = $this->nested->moveAsChild($itemId, $otherItemId);
$this->cache->delete($this->getCacheIdFrom($itemId));
return $ret;
} | php | public function moveAsChild(int $itemId, int $otherItemId)
{
$ret = $this->nested->moveAsChild($itemId, $otherItemId);
$this->cache->delete($this->getCacheIdFrom($itemId));
return $ret;
} | {@inheritdoc} | https://github.com/makinacorpus/drupal-umenu/blob/346574eb0f5982857c64144e99ad2eacc8c52c5b/src/CachedItemStorageProxy.php#L109-L115 |
makinacorpus/drupal-umenu | src/CachedItemStorageProxy.php | CachedItemStorageProxy.moveToRoot | public function moveToRoot(int $itemId)
{
$ret = $this->nested->moveToRoot($itemId);
$this->cache->delete($this->getCacheIdFrom($itemId));
return $ret;
} | php | public function moveToRoot(int $itemId)
{
$ret = $this->nested->moveToRoot($itemId);
$this->cache->delete($this->getCacheIdFrom($itemId));
return $ret;
} | {@inheritdoc} | https://github.com/makinacorpus/drupal-umenu/blob/346574eb0f5982857c64144e99ad2eacc8c52c5b/src/CachedItemStorageProxy.php#L120-L126 |
makinacorpus/drupal-umenu | src/CachedItemStorageProxy.php | CachedItemStorageProxy.delete | public function delete(int $itemId)
{
// For deletion, fetch cache identifier first
$cacheId = $this->getCacheIdFrom($itemId);
$ret = $this->nested->delete($itemId);
$this->cache->delete($cacheId);
return $ret;
} | php | public function delete(int $itemId)
{
// For deletion, fetch cache identifier first
$cacheId = $this->getCacheIdFrom($itemId);
$ret = $this->nested->delete($itemId);
$this->cache->delete($cacheId);
return $ret;
} | {@inheritdoc} | https://github.com/makinacorpus/drupal-umenu/blob/346574eb0f5982857c64144e99ad2eacc8c52c5b/src/CachedItemStorageProxy.php#L153-L161 |
luoxiaojun1992/lb_framework | components/algos/data_structure/Uf.php | Uf.union | public function union($p, $q)
{
/*
$pid = $this->id[$p];
$qid = $this->id[$q];
foreach($this->id as $k => $v) {
if ($v == $pid) {
$this->id[$k] = $qid;
}
}
*/
$i = $this->root($p);
$j = $this->root($q);
if ($i == $j) {
return;
}
if ($this->size[$i] < $this->size[$j]) {
$this->id[$i] = $j;
$this->size[$j] += $this->size[$i];
} else {
$this->id[$j] = $i;
$this->size[$i] += $this->size[$j];
}
} | php | public function union($p, $q)
{
/*
$pid = $this->id[$p];
$qid = $this->id[$q];
foreach($this->id as $k => $v) {
if ($v == $pid) {
$this->id[$k] = $qid;
}
}
*/
$i = $this->root($p);
$j = $this->root($q);
if ($i == $j) {
return;
}
if ($this->size[$i] < $this->size[$j]) {
$this->id[$i] = $j;
$this->size[$j] += $this->size[$i];
} else {
$this->id[$j] = $i;
$this->size[$i] += $this->size[$j];
}
} | 时间复杂度,单个O(n),多个O(n2)
@param $p
@param $q | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/algos/data_structure/Uf.php#L46-L72 |
luoxiaojun1992/lb_framework | components/algos/data_structure/Uf.php | Uf.root | private function root($i)
{
while($i != $this->id[$i]) {
$this->id[$i] = $this->id[$this->id[$i]]; //path compression
$i = $this->id[$i];
}
return $i;
} | php | private function root($i)
{
while($i != $this->id[$i]) {
$this->id[$i] = $this->id[$this->id[$i]]; //path compression
$i = $this->id[$i];
}
return $i;
} | 避免递归
@param $i
@return mixed | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/algos/data_structure/Uf.php#L80-L88 |
brainexe/core | src/Console/CreateUserCommand.php | CreateUserCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$username = $input->getArgument('username');
$password = $input->getArgument('password');
$roles = explode(',', $input->getArgument('roles'));
$user = new UserVO();
$user->username = $username;
$user->password = $password;
$user->roles = $roles;
$session = new Session(new MockArraySessionStorage());
$userId = $this->register->registerUser($user, $session, null);
$output->writeln(sprintf('New user-id: <info>%d</info>', $userId));
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$username = $input->getArgument('username');
$password = $input->getArgument('password');
$roles = explode(',', $input->getArgument('roles'));
$user = new UserVO();
$user->username = $username;
$user->password = $password;
$user->roles = $roles;
$session = new Session(new MockArraySessionStorage());
$userId = $this->register->registerUser($user, $session, null);
$output->writeln(sprintf('New user-id: <info>%d</info>', $userId));
} | {@inheritdoc} | https://github.com/brainexe/core/blob/9ef69c6f045306abd20e271572386970db9b3e54/src/Console/CreateUserCommand.php#L51-L66 |
ekyna/AdminBundle | Form/Type/PermissionType.php | PermissionType.buildForm | public function buildForm(FormBuilderInterface $builder, array $options)
{
foreach($this->permissions as $permission) {
$builder
->add($permission, 'checkbox', [
'label' => ucfirst($permission),
'required' => false
])
;
}
} | php | public function buildForm(FormBuilderInterface $builder, array $options)
{
foreach($this->permissions as $permission) {
$builder
->add($permission, 'checkbox', [
'label' => ucfirst($permission),
'required' => false
])
;
}
} | {@inheritdoc} | https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Form/Type/PermissionType.php#L33-L43 |
OpenClassrooms/FrontDesk | src/Repository/PersonRepository.php | PersonRepository.find | public function find($personId)
{
$jsonResult = $this->coreApiClient->get(self::RESOURCE_NAME.$personId);
$result = json_decode($jsonResult, true);
return $this->buildPeople($result['people'])[0];
} | php | public function find($personId)
{
$jsonResult = $this->coreApiClient->get(self::RESOURCE_NAME.$personId);
$result = json_decode($jsonResult, true);
return $this->buildPeople($result['people'])[0];
} | {@inheritdoc} | https://github.com/OpenClassrooms/FrontDesk/blob/1d221ff96fa0a3948b8bd210dec77542074ed988/src/Repository/PersonRepository.php#L26-L32 |
OpenClassrooms/FrontDesk | src/Repository/PersonRepository.php | PersonRepository.buildPeople | private function buildPeople($result)
{
$people = [];
foreach ($result as $person) {
$people[] = $this->personBuilder
->create()
->withAddress($person['address'])
->withBirthdate($person['birthdate'] !== null ? new \DateTime($person['birthdate']) : null)
->withCustomFields($person['custom_fields'])
->withEmail($person['email'])
->withFirstName($person['first_name'])
->withGuardianEmail($person['guardian_email'])
->withGuardianName($person['guardian_name'])
->withId($person['id'])
->withJoinedAt($person['joined_at'] !== null ? new \DateTime($person['joined_at']) : null)
->withLastName($person['last_name'])
->withLocationId($person['location_id'])
->withMiddleName($person['middle_name'])
->withPhone($person['phone'])
->withPrimaryStaffMember(
isset($person['primary_staff_member']) ? $person['primary_staff_member'] : null
)
->withStaffContactId(
isset($person['staff_contact_id']) ? $person['staff_contact_id'] : null
)
->build();
}
return $people;
} | php | private function buildPeople($result)
{
$people = [];
foreach ($result as $person) {
$people[] = $this->personBuilder
->create()
->withAddress($person['address'])
->withBirthdate($person['birthdate'] !== null ? new \DateTime($person['birthdate']) : null)
->withCustomFields($person['custom_fields'])
->withEmail($person['email'])
->withFirstName($person['first_name'])
->withGuardianEmail($person['guardian_email'])
->withGuardianName($person['guardian_name'])
->withId($person['id'])
->withJoinedAt($person['joined_at'] !== null ? new \DateTime($person['joined_at']) : null)
->withLastName($person['last_name'])
->withLocationId($person['location_id'])
->withMiddleName($person['middle_name'])
->withPhone($person['phone'])
->withPrimaryStaffMember(
isset($person['primary_staff_member']) ? $person['primary_staff_member'] : null
)
->withStaffContactId(
isset($person['staff_contact_id']) ? $person['staff_contact_id'] : null
)
->build();
}
return $people;
} | @param array $result
@return Person[] | https://github.com/OpenClassrooms/FrontDesk/blob/1d221ff96fa0a3948b8bd210dec77542074ed988/src/Repository/PersonRepository.php#L39-L69 |
OpenClassrooms/FrontDesk | src/Repository/PersonRepository.php | PersonRepository.findAllByQuery | public function findAllByQuery($query = null)
{
if (null === $query) {
return $this->findAll();
}
$parameters = ['q' => $query];
$jsonResult = $this->coreApiClient->get(
self::RESOURCE_NAME.self::SEARCH.urldecode('?'.http_build_query($parameters))
);
$results = json_decode($jsonResult, true);
$arrayPeople = $this->getArrayPerson($results);
return $this->buildPeople($arrayPeople);
} | php | public function findAllByQuery($query = null)
{
if (null === $query) {
return $this->findAll();
}
$parameters = ['q' => $query];
$jsonResult = $this->coreApiClient->get(
self::RESOURCE_NAME.self::SEARCH.urldecode('?'.http_build_query($parameters))
);
$results = json_decode($jsonResult, true);
$arrayPeople = $this->getArrayPerson($results);
return $this->buildPeople($arrayPeople);
} | {@inheritdoc} | https://github.com/OpenClassrooms/FrontDesk/blob/1d221ff96fa0a3948b8bd210dec77542074ed988/src/Repository/PersonRepository.php#L74-L88 |
OpenClassrooms/FrontDesk | src/Repository/PersonRepository.php | PersonRepository.findAll | public function findAll($page = null)
{
$parameters = ['page' => $page];
$jsonResult = $this->coreApiClient->get(self::RESOURCE_NAME.urldecode('?'.http_build_query($parameters)));
$result = json_decode($jsonResult, true);
return $this->buildPeople($result['people']);
} | php | public function findAll($page = null)
{
$parameters = ['page' => $page];
$jsonResult = $this->coreApiClient->get(self::RESOURCE_NAME.urldecode('?'.http_build_query($parameters)));
$result = json_decode($jsonResult, true);
return $this->buildPeople($result['people']);
} | {@inheritdoc} | https://github.com/OpenClassrooms/FrontDesk/blob/1d221ff96fa0a3948b8bd210dec77542074ed988/src/Repository/PersonRepository.php#L93-L100 |
OpenClassrooms/FrontDesk | src/Repository/PersonRepository.php | PersonRepository.getArrayPerson | private function getArrayPerson(array $results)
{
$results = reset($results);
$people = [];
foreach ($results as $result) {
$people[] = $result['person'];
}
return $people;
} | php | private function getArrayPerson(array $results)
{
$results = reset($results);
$people = [];
foreach ($results as $result) {
$people[] = $result['person'];
}
return $people;
} | @param array $results
@return array | https://github.com/OpenClassrooms/FrontDesk/blob/1d221ff96fa0a3948b8bd210dec77542074ed988/src/Repository/PersonRepository.php#L107-L117 |
OpenClassrooms/FrontDesk | src/Repository/PersonRepository.php | PersonRepository.insert | public function insert(Person $person)
{
$jsonResult = $this->coreApiClient->post(self::RESOURCE_NAME, ['person' => $person]);
$result = json_decode($jsonResult, true);
return $result['people'][0]['id'];
} | php | public function insert(Person $person)
{
$jsonResult = $this->coreApiClient->post(self::RESOURCE_NAME, ['person' => $person]);
$result = json_decode($jsonResult, true);
return $result['people'][0]['id'];
} | {@inheritdoc} | https://github.com/OpenClassrooms/FrontDesk/blob/1d221ff96fa0a3948b8bd210dec77542074ed988/src/Repository/PersonRepository.php#L122-L128 |
OpenClassrooms/FrontDesk | src/Repository/PersonRepository.php | PersonRepository.update | public function update(Person $person)
{
$jsonResult = $this->coreApiClient->put(self::RESOURCE_NAME.$person->getId(), ['person' => $person]);
$result = json_decode($jsonResult, true);
return $result['people'][0]['id'];
} | php | public function update(Person $person)
{
$jsonResult = $this->coreApiClient->put(self::RESOURCE_NAME.$person->getId(), ['person' => $person]);
$result = json_decode($jsonResult, true);
return $result['people'][0]['id'];
} | {@inheritdoc} | https://github.com/OpenClassrooms/FrontDesk/blob/1d221ff96fa0a3948b8bd210dec77542074ed988/src/Repository/PersonRepository.php#L133-L139 |
vincenttouzet/BootstrapFormBundle | Form/Type/MoneyType.php | MoneyType.buildView | public function buildView(FormView $view, FormInterface $form, array $options)
{
$currency = $options['currency'];
$view->vars['input_prepend'] = null;
$view->vars['input_append'] = null;
$locale = \Locale::getDefault();
$format = new \NumberFormatter($locale, \NumberFormatter::CURRENCY);
$pattern = $format->formatCurrency('123', $currency);
// the spacings between currency symbol and number are ignored, because
// a single space leads to better readability in combination with input
// fields
// the regex also considers non-break spaces (0xC2 or 0xA0 in UTF-8)
preg_match('/^([^\s\xc2\xa0]*)[\s\xc2\xa0]*123(?:[,.]0+)?[\s\xc2\xa0]*([^\s\xc2\xa0]*)$/u', $pattern, $matches);
if (!empty($matches[1])) {
$view->vars['input_prepend'] = $matches[1];
} elseif (!empty($matches[2])) {
$view->vars['input_append'] = $matches[2];
}
} | php | public function buildView(FormView $view, FormInterface $form, array $options)
{
$currency = $options['currency'];
$view->vars['input_prepend'] = null;
$view->vars['input_append'] = null;
$locale = \Locale::getDefault();
$format = new \NumberFormatter($locale, \NumberFormatter::CURRENCY);
$pattern = $format->formatCurrency('123', $currency);
// the spacings between currency symbol and number are ignored, because
// a single space leads to better readability in combination with input
// fields
// the regex also considers non-break spaces (0xC2 or 0xA0 in UTF-8)
preg_match('/^([^\s\xc2\xa0]*)[\s\xc2\xa0]*123(?:[,.]0+)?[\s\xc2\xa0]*([^\s\xc2\xa0]*)$/u', $pattern, $matches);
if (!empty($matches[1])) {
$view->vars['input_prepend'] = $matches[1];
} elseif (!empty($matches[2])) {
$view->vars['input_append'] = $matches[2];
}
} | {@inheritdoc} | https://github.com/vincenttouzet/BootstrapFormBundle/blob/d648c825ca9f7020336023e82a1059fc070727ac/Form/Type/MoneyType.php#L36-L60 |
Phpillip/phpillip | src/Provider/ParsedownServiceProvider.php | ParsedownServiceProvider.register | public function register(Application $app)
{
$app['parsedown'] = $app->share(function ($app) {
return new $app['parsedown_class'](isset($app['pygments']) ? $app['pygments'] : null);
});
} | php | public function register(Application $app)
{
$app['parsedown'] = $app->share(function ($app) {
return new $app['parsedown_class'](isset($app['pygments']) ? $app['pygments'] : null);
});
} | {@inheritdoc} | https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/Provider/ParsedownServiceProvider.php#L16-L21 |
PopSugar/php-yesmail-api | src/Yesmail/YesmailListload.php | YesmailListload.is_valid | public function is_valid() {
$ret = false;
if (is_null($this->division) === false && is_null($this->datafileURI) === false &&
is_null($this->subscribe) === false && is_null($this->profileUpdate) === false &&
is_null($this->listLoadName) === false && is_null($this->loadMode) === false &&
is_null($this->headers) === false && is_null($this->maxErrors) === false &&
is_null($this->errorType) === false
) {
$ret = true;
}
return $ret;
} | php | public function is_valid() {
$ret = false;
if (is_null($this->division) === false && is_null($this->datafileURI) === false &&
is_null($this->subscribe) === false && is_null($this->profileUpdate) === false &&
is_null($this->listLoadName) === false && is_null($this->loadMode) === false &&
is_null($this->headers) === false && is_null($this->maxErrors) === false &&
is_null($this->errorType) === false
) {
$ret = true;
}
return $ret;
} | Validates a listload
@return bool True if the listload is valid, false otherwise
@access public | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/YesmailListload.php#L134-L147 |
PopSugar/php-yesmail-api | src/Yesmail/YesmailListload.php | YesmailListload.jsonSerialize | public function jsonSerialize() {
$ret = new \stdClass();
$ret->division = $this->division;
$ret->datafileURI = $this->datafileURI;
$ret->subscribe = $this->subscribe;
$ret->profileUpdate = $this->profileUpdate;
$ret->listLoadName = $this->listLoadName;
$options = array();
$options['loadMode'] = $this->loadMode;
$options['headers'] = $this->headers;
$options['maxErrors'] = $this->maxErrors;
$options['errorType'] = $this->errorType;
$ret->options = $options;
return $ret;
} | php | public function jsonSerialize() {
$ret = new \stdClass();
$ret->division = $this->division;
$ret->datafileURI = $this->datafileURI;
$ret->subscribe = $this->subscribe;
$ret->profileUpdate = $this->profileUpdate;
$ret->listLoadName = $this->listLoadName;
$options = array();
$options['loadMode'] = $this->loadMode;
$options['headers'] = $this->headers;
$options['maxErrors'] = $this->maxErrors;
$options['errorType'] = $this->errorType;
$ret->options = $options;
return $ret;
} | Return a json_encode able version of the object
@return object A version of the object that is ready for json_encode
@access public | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/YesmailListload.php#L155-L171 |
igorwanbarros/autenticacao-laravel | src/Migrations/2016_10_15_185039_autenticacao_create_users_table.php | AutenticacaoCreateUsersTable.up | public function up()
{
Schema::create('autenticacao_users', function (Blueprint $tb) {
$tb->increments('id');
$tb->string('name');
$tb->string('email');
$tb->string('password', 60);
$tb->integer('login_count')->default(0);
$tb->integer('login_attempt')->default(0);
$tb->rememberToken();
$tb->timestamps();
$tb->softDeletes();
});
} | php | public function up()
{
Schema::create('autenticacao_users', function (Blueprint $tb) {
$tb->increments('id');
$tb->string('name');
$tb->string('email');
$tb->string('password', 60);
$tb->integer('login_count')->default(0);
$tb->integer('login_attempt')->default(0);
$tb->rememberToken();
$tb->timestamps();
$tb->softDeletes();
});
} | Run the migrations.
@return void | https://github.com/igorwanbarros/autenticacao-laravel/blob/e7e8217dae433934fe46c34516fb2f6f5f932fc1/src/Migrations/2016_10_15_185039_autenticacao_create_users_table.php#L13-L26 |
Synapse-Cmf/synapse-cmf | src/Synapse/Cmf/Framework/Media/File/Action/Dal/CreateAction.php | CreateAction.resolve | public function resolve()
{
$this->file = (new $this->fileClass())
->setName(
$this->physicalFile->getBasename()
)
// calculate original name (keep it for user data display)
->setOriginalName($this->originalName
?: $this->physicalFile->getBasename()
)
// calculate storage path (we only need path from config)
->setStorePath(str_replace(// trim base path
realpath($this->storePath),
'',
str_replace(// trim filename
$this->physicalFile->getBasename(),
'',
$this->physicalFile->getRealpath()
)
))
;
$this->assertEntityIsValid($this->file, array('File', 'creation'));
$this->fireEvent(
FileEvents::FILE_CREATED,
new FileEvent($this->file, $this)
);
return $this->file;
} | php | public function resolve()
{
$this->file = (new $this->fileClass())
->setName(
$this->physicalFile->getBasename()
)
// calculate original name (keep it for user data display)
->setOriginalName($this->originalName
?: $this->physicalFile->getBasename()
)
// calculate storage path (we only need path from config)
->setStorePath(str_replace(// trim base path
realpath($this->storePath),
'',
str_replace(// trim filename
$this->physicalFile->getBasename(),
'',
$this->physicalFile->getRealpath()
)
))
;
$this->assertEntityIsValid($this->file, array('File', 'creation'));
$this->fireEvent(
FileEvents::FILE_CREATED,
new FileEvent($this->file, $this)
);
return $this->file;
} | File creation method.
@return File | https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Framework/Media/File/Action/Dal/CreateAction.php#L30-L60 |
aryelgois/medools-router | src/Router.php | Router.authenticate | public function authenticate(string $auth, string $type)
{
$config = $this->authentication ?? null;
if ($config === null) {
return;
} elseif (!is_array($config)) {
$config = ['secret' => $config];
}
$config = array_merge(
[
'secret' => null,
'algorithm' => 'HS256',
'claims' => [],
'expiration' => null,
'verify' => false,
],
$config
);
if ($auth === '') {
switch ($type) {
case 'Basic':
$this->sendError(
static::ERROR_INVALID_CREDENTIALS,
'Authorization Header is empty'
);
break;
case 'Bearer':
return false;
break;
}
$this->sendError(
static::ERROR_INTERNAL_SERVER,
"Invalid Authorization type: '$type'"
);
}
$stamp = time();
if ($config['secret'] === null) {
$this->sendError(
static::ERROR_INTERNAL_SERVER,
'Missing authentication secret'
);
}
$secret_path = realpath($config['secret']);
$secret_exp = null;
if (is_dir($secret_path)) {
$files = array_diff(scandir($secret_path), ['.', '..']);
if (empty($files)) {
$this->sendError(
static::ERROR_INTERNAL_SERVER,
'No secret file found'
);
}
foreach ($files as $file) {
$expiration = basename($file);
if ($expiration > $stamp) {
$secret_exp = (int) $expiration;
break;
}
}
if ($secret_exp === null) {
$this->sendError(
static::ERROR_INTERNAL_SERVER,
'All secret files expired'
);
}
$secret_file = "$secret_path/$file";
} elseif (is_file($secret_path)) {
$secret_file = $secret_path;
} else {
$this->sendError(
static::ERROR_INTERNAL_SERVER,
'Secret file does not exist'
);
}
$secret = file_get_contents($secret_file);
list($type_h, $credentials) = array_pad(explode(' ', $auth, 2), 2, '');
if ($type !== $type_h) {
$this->sendError(
static::ERROR_INVALID_CREDENTIALS,
"Invalid Authorization type in header: '$type_h'"
);
}
switch ($type) {
case 'Basic':
$credentials = explode(':', base64_decode($credentials), 2);
list($username, $password) = array_pad($credentials, 2, '');
$authentication = Authentication::getInstance([
'username' => $username,
]);
if ($authentication === null
|| !$authentication->checkPassword($password)
) {
$this->sendError(
static::ERROR_INVALID_CREDENTIALS,
'Invalid credentials'
);
}
if ($authentication->isDeleted()) {
$this->sendError(
static::ERROR_UNAUTHENTICATED,
'Account is disabled'
);
}
if ($config['verify'] && !$authentication->verified) {
$this->sendError(
static::ERROR_UNAUTHENTICATED,
'Email is not verified'
);
}
$token = array_merge(
$config['claims'],
[
'iss' => $this->url,
'iat' => $stamp,
'user' => $authentication->id,
]
);
$expiration = $config['expiration'];
if ($expiration === null) {
if ($secret_exp !== null) {
$token['exp'] = $secret_exp;
}
} else {
$expiration += $stamp;
$token['exp'] = ($secret_exp !== null)
? min($expiration, $secret_exp)
: $expiration;
}
$response = $this->prepareResponse();
$response->headers['Content-Type'] = 'application/jwt';
try {
$response->body = JWT::encode(
$token,
$secret,
$config['algorithm']
);
} catch (\Exception $e) {
$this->sendError(
static::ERROR_INTERNAL_SERVER,
'Could not generate token: ' . $e->getMessage()
);
}
return $response;
break;
case 'Bearer':
try {
$token = JWT::decode(
$credentials,
$secret,
[$config['algorithm']]
);
} catch (\Exception $e) {
$this->sendError(
static::ERROR_INVALID_TOKEN,
'Could not verify token: ' . $e->getMessage()
);
}
$authentication = Authentication::getInstance([
'id' => $token->user,
]);
if ($authentication === null) {
$this->sendError(
static::ERROR_UNAUTHENTICATED,
'Account not found'
);
}
if ($authentication->isDeleted()) {
$this->sendError(
static::ERROR_UNAUTHENTICATED,
'Account is disabled'
);
}
return $authentication;
break;
}
$this->sendError(
static::ERROR_INTERNAL_SERVER,
"Invalid Authorization type: '$type'"
);
} | php | public function authenticate(string $auth, string $type)
{
$config = $this->authentication ?? null;
if ($config === null) {
return;
} elseif (!is_array($config)) {
$config = ['secret' => $config];
}
$config = array_merge(
[
'secret' => null,
'algorithm' => 'HS256',
'claims' => [],
'expiration' => null,
'verify' => false,
],
$config
);
if ($auth === '') {
switch ($type) {
case 'Basic':
$this->sendError(
static::ERROR_INVALID_CREDENTIALS,
'Authorization Header is empty'
);
break;
case 'Bearer':
return false;
break;
}
$this->sendError(
static::ERROR_INTERNAL_SERVER,
"Invalid Authorization type: '$type'"
);
}
$stamp = time();
if ($config['secret'] === null) {
$this->sendError(
static::ERROR_INTERNAL_SERVER,
'Missing authentication secret'
);
}
$secret_path = realpath($config['secret']);
$secret_exp = null;
if (is_dir($secret_path)) {
$files = array_diff(scandir($secret_path), ['.', '..']);
if (empty($files)) {
$this->sendError(
static::ERROR_INTERNAL_SERVER,
'No secret file found'
);
}
foreach ($files as $file) {
$expiration = basename($file);
if ($expiration > $stamp) {
$secret_exp = (int) $expiration;
break;
}
}
if ($secret_exp === null) {
$this->sendError(
static::ERROR_INTERNAL_SERVER,
'All secret files expired'
);
}
$secret_file = "$secret_path/$file";
} elseif (is_file($secret_path)) {
$secret_file = $secret_path;
} else {
$this->sendError(
static::ERROR_INTERNAL_SERVER,
'Secret file does not exist'
);
}
$secret = file_get_contents($secret_file);
list($type_h, $credentials) = array_pad(explode(' ', $auth, 2), 2, '');
if ($type !== $type_h) {
$this->sendError(
static::ERROR_INVALID_CREDENTIALS,
"Invalid Authorization type in header: '$type_h'"
);
}
switch ($type) {
case 'Basic':
$credentials = explode(':', base64_decode($credentials), 2);
list($username, $password) = array_pad($credentials, 2, '');
$authentication = Authentication::getInstance([
'username' => $username,
]);
if ($authentication === null
|| !$authentication->checkPassword($password)
) {
$this->sendError(
static::ERROR_INVALID_CREDENTIALS,
'Invalid credentials'
);
}
if ($authentication->isDeleted()) {
$this->sendError(
static::ERROR_UNAUTHENTICATED,
'Account is disabled'
);
}
if ($config['verify'] && !$authentication->verified) {
$this->sendError(
static::ERROR_UNAUTHENTICATED,
'Email is not verified'
);
}
$token = array_merge(
$config['claims'],
[
'iss' => $this->url,
'iat' => $stamp,
'user' => $authentication->id,
]
);
$expiration = $config['expiration'];
if ($expiration === null) {
if ($secret_exp !== null) {
$token['exp'] = $secret_exp;
}
} else {
$expiration += $stamp;
$token['exp'] = ($secret_exp !== null)
? min($expiration, $secret_exp)
: $expiration;
}
$response = $this->prepareResponse();
$response->headers['Content-Type'] = 'application/jwt';
try {
$response->body = JWT::encode(
$token,
$secret,
$config['algorithm']
);
} catch (\Exception $e) {
$this->sendError(
static::ERROR_INTERNAL_SERVER,
'Could not generate token: ' . $e->getMessage()
);
}
return $response;
break;
case 'Bearer':
try {
$token = JWT::decode(
$credentials,
$secret,
[$config['algorithm']]
);
} catch (\Exception $e) {
$this->sendError(
static::ERROR_INVALID_TOKEN,
'Could not verify token: ' . $e->getMessage()
);
}
$authentication = Authentication::getInstance([
'id' => $token->user,
]);
if ($authentication === null) {
$this->sendError(
static::ERROR_UNAUTHENTICATED,
'Account not found'
);
}
if ($authentication->isDeleted()) {
$this->sendError(
static::ERROR_UNAUTHENTICATED,
'Account is disabled'
);
}
return $authentication;
break;
}
$this->sendError(
static::ERROR_INTERNAL_SERVER,
"Invalid Authorization type: '$type'"
);
} | Authenticates an Authorization Header
@param string $auth Request Authorization Header
@param string $type Expected Authentication type
@return null If Authentication is disabled
@return false If Authorization is empty (Bearer $type)
@return Response If Basic Authentication was successful
@return Authentication If Bearer Authentication was successful
@throws RouterException If Authorization is empty (Basic $type)
@throws RouterException If there is any problem with the secret
@throws RouterException If could not authenticate
@throws RouterException If could not generate the token
@throws RouterException If Authorization type is invalid | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L428-L629 |
aryelgois/medools-router | src/Router.php | Router.run | public function run(
string $method,
string $uri,
array $headers,
string $body
) {
$this->auth = $this->authenticate(
$headers['Authorization'] ?? '',
'Bearer'
);
if (static::ENABLE_METHOD_OVERRIDE
&& strcasecmp($method, 'POST') === 0
) {
$actual_method = $headers['X-Http-Method-Override'] ?? 'POST';
}
$this->method = strtoupper($actual_method ?? $method);
$this->safe_method = in_array($this->method, static::SAFE_METHODS);
$allow = $this->implemented_methods;
if (!in_array($this->method, $allow)) {
$message = "Method '$this->method' is not implemented"
. (in_array('OPTIONS', $allow)
? '. Please use '
. Format::naturalLanguageJoin($allow, 'or')
: '');
$this->sendError(
static::ERROR_METHOD_NOT_IMPLEMENTED,
$message,
$allow
);
}
$resource = $this->parseRoute($uri);
$response = null;
if ($resource === null) {
if ($this->method !== 'OPTIONS') {
$response = $this->requestRoot($headers, $body);
}
} else {
$resource_name = $resource['name'];
$resource_data = $this->resources[$resource_name];
$resource_extension = $resource['extension'];
$prefered_type = $this->extensions[$resource_extension] ?? null;
$methods = (array) ($resource_data['methods'] ?? null);
if (!empty($methods)) {
$allow = array_intersect(
$allow,
array_merge($methods, ['OPTIONS'])
);
if (!in_array($this->method, $allow)) {
$message = "Method '$this->method' is not allowed"
. (in_array('OPTIONS', $allow)
? '. Please use '
. Format::naturalLanguageJoin($allow, 'or')
: '');
$this->sendError(
static::ERROR_METHOD_NOT_ALLOWED,
$message,
$allow
);
}
}
parse_str(parse_url($uri, PHP_URL_QUERY), $query);
$resource['query'] = $query;
$payload = $this->parseBody(
$resource_name,
$headers['Content-Type'] ?? '',
$body
);
if (array_key_exists('body', $payload)) {
$resource['payload'] = $payload;
$resource['data'] = null;
} else {
$resource['data'] = $payload['data'] ?? [];
}
if ($this->safe_method) {
$available = $this->getAvailableTypes($resource_name);
if ($prefered_type === null) {
$accepted = (empty($available))
? null
: $accepted = $this->getAcceptedResourceType(
$resource_name,
$headers['Accept'] ?? '*/*'
);
} else {
if (!array_key_exists($prefered_type, $available)) {
$message = "Resource '$resource_name' can not generate "
. "content for '$resource_extension' extension";
$this->sendError(
static::ERROR_NOT_ACCEPTABLE,
$message
);
}
$accepted = $prefered_type;
}
$resource['content_type'] = $accepted;
if (!empty($available)) {
$handler = $available[$accepted];
if (is_array($handler)
&& ($handler[$resource['kind']] ?? null) === null
) {
$message = "Resource '$resource_name' can not generate "
. $accepted . ' ' . $resource['kind'];
$this->sendError(
static::ERROR_NOT_ACCEPTABLE,
$message
);
}
}
if (($resource['content_location'] ?? null) !== null) {
$extension = $resource_extension ?? array_search(
$accepted,
$this->extensions
);
if (is_string($extension)) {
$resource['content_location'] .= ".$extension";
}
$query = http_build_query($query);
if ($query !== '') {
$resource['content_location'] .= '?' . $query;
}
}
}
if ($this->method !== 'OPTIONS') {
$resource_obj = new Resource;
foreach ($resource as $key => $value) {
$resource_obj->$key = $value;
}
try {
$response = ($resource_obj->kind === 'collection')
? $this->requestCollection($resource_obj)
: $this->requestResource($resource_obj);
} catch (RouterException $e) {
throw $e;
} catch (ForeignConstraintException $e) {
$code = static::ERROR_FOREIGN_CONSTRAINT;
} catch (MissingColumnException $e) {
$code = static::ERROR_INVALID_PAYLOAD;
} catch (ReadOnlyModelException $e) {
$code = static::ERROR_READONLY_RESOURCE;
} catch (UnknownColumnException $e) {
$code = static::ERROR_UNKNOWN_FIELDS;
} catch (\Exception $e) {
$code = static::ERROR_INTERNAL_SERVER;
} finally {
if (isset($code)) {
$this->sendError($code, $e->getMessage());
}
}
$content_location = $resource_obj->content_location;
if ($content_location !== null) {
$response->headers['Content-Location'] = $content_location;
}
if (headers_sent()) {
return;
}
}
}
if ($response === null) {
$response = $this->prepareResponse();
if ($this->method === 'OPTIONS') {
$response->headers['Allow'] = $allow;
}
}
if ($this->method !== 'HEAD' && !empty($response->body)
&& ($resource_data['cache'] ?? $this->always_cache)
) {
$response = $this->checkCache(
$response,
$headers['If-None-Match'] ?? '',
$resource_data['max_age'] ?? 0
);
}
return $response;
} | php | public function run(
string $method,
string $uri,
array $headers,
string $body
) {
$this->auth = $this->authenticate(
$headers['Authorization'] ?? '',
'Bearer'
);
if (static::ENABLE_METHOD_OVERRIDE
&& strcasecmp($method, 'POST') === 0
) {
$actual_method = $headers['X-Http-Method-Override'] ?? 'POST';
}
$this->method = strtoupper($actual_method ?? $method);
$this->safe_method = in_array($this->method, static::SAFE_METHODS);
$allow = $this->implemented_methods;
if (!in_array($this->method, $allow)) {
$message = "Method '$this->method' is not implemented"
. (in_array('OPTIONS', $allow)
? '. Please use '
. Format::naturalLanguageJoin($allow, 'or')
: '');
$this->sendError(
static::ERROR_METHOD_NOT_IMPLEMENTED,
$message,
$allow
);
}
$resource = $this->parseRoute($uri);
$response = null;
if ($resource === null) {
if ($this->method !== 'OPTIONS') {
$response = $this->requestRoot($headers, $body);
}
} else {
$resource_name = $resource['name'];
$resource_data = $this->resources[$resource_name];
$resource_extension = $resource['extension'];
$prefered_type = $this->extensions[$resource_extension] ?? null;
$methods = (array) ($resource_data['methods'] ?? null);
if (!empty($methods)) {
$allow = array_intersect(
$allow,
array_merge($methods, ['OPTIONS'])
);
if (!in_array($this->method, $allow)) {
$message = "Method '$this->method' is not allowed"
. (in_array('OPTIONS', $allow)
? '. Please use '
. Format::naturalLanguageJoin($allow, 'or')
: '');
$this->sendError(
static::ERROR_METHOD_NOT_ALLOWED,
$message,
$allow
);
}
}
parse_str(parse_url($uri, PHP_URL_QUERY), $query);
$resource['query'] = $query;
$payload = $this->parseBody(
$resource_name,
$headers['Content-Type'] ?? '',
$body
);
if (array_key_exists('body', $payload)) {
$resource['payload'] = $payload;
$resource['data'] = null;
} else {
$resource['data'] = $payload['data'] ?? [];
}
if ($this->safe_method) {
$available = $this->getAvailableTypes($resource_name);
if ($prefered_type === null) {
$accepted = (empty($available))
? null
: $accepted = $this->getAcceptedResourceType(
$resource_name,
$headers['Accept'] ?? '*/*'
);
} else {
if (!array_key_exists($prefered_type, $available)) {
$message = "Resource '$resource_name' can not generate "
. "content for '$resource_extension' extension";
$this->sendError(
static::ERROR_NOT_ACCEPTABLE,
$message
);
}
$accepted = $prefered_type;
}
$resource['content_type'] = $accepted;
if (!empty($available)) {
$handler = $available[$accepted];
if (is_array($handler)
&& ($handler[$resource['kind']] ?? null) === null
) {
$message = "Resource '$resource_name' can not generate "
. $accepted . ' ' . $resource['kind'];
$this->sendError(
static::ERROR_NOT_ACCEPTABLE,
$message
);
}
}
if (($resource['content_location'] ?? null) !== null) {
$extension = $resource_extension ?? array_search(
$accepted,
$this->extensions
);
if (is_string($extension)) {
$resource['content_location'] .= ".$extension";
}
$query = http_build_query($query);
if ($query !== '') {
$resource['content_location'] .= '?' . $query;
}
}
}
if ($this->method !== 'OPTIONS') {
$resource_obj = new Resource;
foreach ($resource as $key => $value) {
$resource_obj->$key = $value;
}
try {
$response = ($resource_obj->kind === 'collection')
? $this->requestCollection($resource_obj)
: $this->requestResource($resource_obj);
} catch (RouterException $e) {
throw $e;
} catch (ForeignConstraintException $e) {
$code = static::ERROR_FOREIGN_CONSTRAINT;
} catch (MissingColumnException $e) {
$code = static::ERROR_INVALID_PAYLOAD;
} catch (ReadOnlyModelException $e) {
$code = static::ERROR_READONLY_RESOURCE;
} catch (UnknownColumnException $e) {
$code = static::ERROR_UNKNOWN_FIELDS;
} catch (\Exception $e) {
$code = static::ERROR_INTERNAL_SERVER;
} finally {
if (isset($code)) {
$this->sendError($code, $e->getMessage());
}
}
$content_location = $resource_obj->content_location;
if ($content_location !== null) {
$response->headers['Content-Location'] = $content_location;
}
if (headers_sent()) {
return;
}
}
}
if ($response === null) {
$response = $this->prepareResponse();
if ($this->method === 'OPTIONS') {
$response->headers['Allow'] = $allow;
}
}
if ($this->method !== 'HEAD' && !empty($response->body)
&& ($resource_data['cache'] ?? $this->always_cache)
) {
$response = $this->checkCache(
$response,
$headers['If-None-Match'] ?? '',
$resource_data['max_age'] ?? 0
);
}
return $response;
} | Processes a $method request to $uri
@param string $method Requested HTTP method
@param string $uri Requested URI
@param array $headers Request Headers
@param string $body Request Body
@return Response
@return null If response was sent by external handler
@throws RouterException If $method is not implemented
@throws RouterException If $method is not allowed
@throws RouterException If $uri has invalid extension
@throws RouterException If Resource's Content-Type handler does not allow
requested kind
@throws RouterException If could not process the request | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L649-L839 |
aryelgois/medools-router | src/Router.php | Router.requestCollection | protected function requestCollection(Resource $resource)
{
$response = $this->prepareResponse();
$where = $resource->where;
$resource_query = $resource->query;
/*
* Filter query parameters
*/
$filters = $this->resources[$resource->name]['filters']
?? $this->default_filters
?? [];
if (is_string($filters)) {
if ($filters === 'ALL') {
$filters = $resource->model_class::getColumns();
} else {
$special = $resource->getSpecialFields();
if (array_key_exists($filters, $special)) {
$filters = $special[$filters];
} else {
$this->sendError(
static::ERROR_INTERNAL_SERVER,
"Resource '$resource->name' has invalid filters group"
);
}
}
}
$operators = static::FITLER_OPERATORS;
$operators_single = ['gt', 'ge', 'lt', 'le', 'rx'];
foreach ($filters as $filter) {
$q = $resource_query[$filter] ?? null;
$pack = [];
if (is_array($q)) {
foreach ($q as $key => $value) {
if (is_numeric($key)) {
$pack[''][] = $value;
} elseif (in_array($key, $operators_single)) {
if (is_array($value)) {
$this->sendError(
static::ERROR_INVALID_QUERY_PARAMETER,
"Filter operator '$key' can not be array"
);
}
$pack[$key] = $value;
} elseif (array_key_exists($key, $operators)) {
$pack[$key] = (is_array($value))
? $value
: explode(',', $value);
if (in_array($key, ['bw', 'nw'])
&& count($pack[$key]) !== 2
) {
$this->sendError(
static::ERROR_INVALID_QUERY_PARAMETER,
"Filter operator '$key' needs two values"
);
}
} else {
$this->sendError(
static::ERROR_INVALID_QUERY_PARAMETER,
"Invalid filter operator '$key' in '$filter'"
);
}
}
} elseif ($q !== null) {
$pack[''] = explode(',', $q);
}
foreach ($pack as $key => $value) {
if (is_array($value) && count($value) === 1) {
$value = $value[0];
}
if (in_array($key, ['', 'ne']) && $value === 'NULL') {
$value = null;
}
if ($key !== '') {
$key = '[' . static::FITLER_OPERATORS[$key] . ']';
}
$where[$filter . $key] = $value;
}
}
/*
* Authorization filter
*/
if ($resource->authorized !== null) {
$where = (empty($where))
? $resource->authorized
: [
'AND # Requested' => $where,
'AND # Authorized' => $resource->authorized,
];
}
/*
* Sort query parameter
*/
$sort = $resource_query['sort'] ?? '';
if ($sort !== '') {
$sort = explode(',', $sort);
$order = [];
foreach ($sort as $id => $value) {
if (strpos($value, '-') === 0) {
$sort[$id] = $value = substr($value, 1);
if ($value === '') {
unset($sort[$id]);
continue;
}
$order[$value] = 'DESC';
} elseif ($value === '') {
unset($sort[$id]);
continue;
} else {
$order[] = $value;
}
}
if (!empty($order)) {
$this->checkUnknownField($resource, $sort);
$where['ORDER'] = $order;
}
}
/*
* Per page and page query parameters
*/
$per_page = ($this->safe_method || isset($resource_query['page']))
? $this->per_page
: 0;
$per_page = $resource_query['per_page'] ?? $per_page;
if ($per_page === 'all') {
$per_page = 0;
}
if (!is_numeric($per_page) || $per_page < 0) {
$this->sendError(
static::ERROR_INVALID_QUERY_PARAMETER,
"Invalid 'per_page' parameter"
);
} elseif ($per_page > 0) {
$page = $resource_query['page'] ?? 1;
if (!is_numeric($page) || $page < 1) {
$this->sendError(
static::ERROR_INVALID_QUERY_PARAMETER,
"Invalid 'page' parameter"
);
}
if ($this->safe_method) {
$count = $this->countResource($resource->name, $where);
$pages = ceil($count / $per_page);
$routes = [];
$tmp = $resource_query;
$tmp['page'] = 1;
$routes['first'] = http_build_query($tmp);
if ($page > 1) {
$tmp['page'] = $page - 1;
$routes['previous'] = http_build_query($tmp);
}
if ($page < $pages) {
$tmp['page'] = $page + 1;
$routes['next'] = http_build_query($tmp);
}
$tmp['page'] = $pages;
$routes['last'] = http_build_query($tmp);
foreach ($routes as &$route) {
$route = $resource->route . '?' . $route;
}
unset($route);
$response->headers['Link'] = $this->headerLink($routes);
$response->headers['X-Total-Count'] = $count;
}
$where['LIMIT'] = [($page - 1) * $per_page, $per_page];
}
$resource->where = $where;
/*
* Process request
*/
if ($this->externalHandler($resource)) {
return;
}
$fields = $this->parseFields($resource);
$has_fields = ($resource->query['fields'] ?? '') !== '';
$body = null;
switch ($this->method) {
case 'GET':
case 'HEAD':
$body = $resource->model_class::dump($where, $fields);
break;
case 'DELETE':
$list = [];
foreach ($resource->getIterator() as $id => $model) {
$route = $resource->route . '/'
. (strrpos($resource->route, '/') == 0
? $this->getPrimaryKey($model)
: $id + 1);
$this->deleteModel($model, $resource, $route);
if ($model::SOFT_DELETE !== null) {
$tmp = $model->getData();
if (!empty($fields)) {
$tmp = Utils::arrayWhitelist($tmp, $fields);
} elseif ($has_fields) {
continue;
}
$list[] = $tmp;
}
}
if (!empty($list)) {
$body = $list;
}
break;
case 'PATCH':
$body = [];
foreach ($resource->getIterator() as $id => $model) {
$route = $resource->route . '/'
. (strrpos($resource->route, '/') == 0
? $this->getPrimaryKey($model)
: $id + 1);
$this->updateModel($model, $resource, $route);
$tmp = $model->getData();
if (!empty($fields)) {
$tmp = Utils::arrayWhitelist($tmp, $fields);
} elseif ($has_fields) {
continue;
}
$body[] = $tmp;
}
break;
case 'POST':
$this->checkMissingFields($resource);
$model = $this->createModel($resource);
$location = $this->getContentLocation($model, $resource);
$response->status = HttpResponse::HTTP_CREATED;
$response->headers['Location'] = $location;
break;
case 'PUT':
$this->sendError(
static::ERROR_METHOD_NOT_ALLOWED,
'Collections do not allow PUT Method'
);
break;
}
if ($body !== null) {
$response->headers['Content-Type'] = 'application/json';
$response->body = $body;
}
return $response;
} | php | protected function requestCollection(Resource $resource)
{
$response = $this->prepareResponse();
$where = $resource->where;
$resource_query = $resource->query;
/*
* Filter query parameters
*/
$filters = $this->resources[$resource->name]['filters']
?? $this->default_filters
?? [];
if (is_string($filters)) {
if ($filters === 'ALL') {
$filters = $resource->model_class::getColumns();
} else {
$special = $resource->getSpecialFields();
if (array_key_exists($filters, $special)) {
$filters = $special[$filters];
} else {
$this->sendError(
static::ERROR_INTERNAL_SERVER,
"Resource '$resource->name' has invalid filters group"
);
}
}
}
$operators = static::FITLER_OPERATORS;
$operators_single = ['gt', 'ge', 'lt', 'le', 'rx'];
foreach ($filters as $filter) {
$q = $resource_query[$filter] ?? null;
$pack = [];
if (is_array($q)) {
foreach ($q as $key => $value) {
if (is_numeric($key)) {
$pack[''][] = $value;
} elseif (in_array($key, $operators_single)) {
if (is_array($value)) {
$this->sendError(
static::ERROR_INVALID_QUERY_PARAMETER,
"Filter operator '$key' can not be array"
);
}
$pack[$key] = $value;
} elseif (array_key_exists($key, $operators)) {
$pack[$key] = (is_array($value))
? $value
: explode(',', $value);
if (in_array($key, ['bw', 'nw'])
&& count($pack[$key]) !== 2
) {
$this->sendError(
static::ERROR_INVALID_QUERY_PARAMETER,
"Filter operator '$key' needs two values"
);
}
} else {
$this->sendError(
static::ERROR_INVALID_QUERY_PARAMETER,
"Invalid filter operator '$key' in '$filter'"
);
}
}
} elseif ($q !== null) {
$pack[''] = explode(',', $q);
}
foreach ($pack as $key => $value) {
if (is_array($value) && count($value) === 1) {
$value = $value[0];
}
if (in_array($key, ['', 'ne']) && $value === 'NULL') {
$value = null;
}
if ($key !== '') {
$key = '[' . static::FITLER_OPERATORS[$key] . ']';
}
$where[$filter . $key] = $value;
}
}
/*
* Authorization filter
*/
if ($resource->authorized !== null) {
$where = (empty($where))
? $resource->authorized
: [
'AND # Requested' => $where,
'AND # Authorized' => $resource->authorized,
];
}
/*
* Sort query parameter
*/
$sort = $resource_query['sort'] ?? '';
if ($sort !== '') {
$sort = explode(',', $sort);
$order = [];
foreach ($sort as $id => $value) {
if (strpos($value, '-') === 0) {
$sort[$id] = $value = substr($value, 1);
if ($value === '') {
unset($sort[$id]);
continue;
}
$order[$value] = 'DESC';
} elseif ($value === '') {
unset($sort[$id]);
continue;
} else {
$order[] = $value;
}
}
if (!empty($order)) {
$this->checkUnknownField($resource, $sort);
$where['ORDER'] = $order;
}
}
/*
* Per page and page query parameters
*/
$per_page = ($this->safe_method || isset($resource_query['page']))
? $this->per_page
: 0;
$per_page = $resource_query['per_page'] ?? $per_page;
if ($per_page === 'all') {
$per_page = 0;
}
if (!is_numeric($per_page) || $per_page < 0) {
$this->sendError(
static::ERROR_INVALID_QUERY_PARAMETER,
"Invalid 'per_page' parameter"
);
} elseif ($per_page > 0) {
$page = $resource_query['page'] ?? 1;
if (!is_numeric($page) || $page < 1) {
$this->sendError(
static::ERROR_INVALID_QUERY_PARAMETER,
"Invalid 'page' parameter"
);
}
if ($this->safe_method) {
$count = $this->countResource($resource->name, $where);
$pages = ceil($count / $per_page);
$routes = [];
$tmp = $resource_query;
$tmp['page'] = 1;
$routes['first'] = http_build_query($tmp);
if ($page > 1) {
$tmp['page'] = $page - 1;
$routes['previous'] = http_build_query($tmp);
}
if ($page < $pages) {
$tmp['page'] = $page + 1;
$routes['next'] = http_build_query($tmp);
}
$tmp['page'] = $pages;
$routes['last'] = http_build_query($tmp);
foreach ($routes as &$route) {
$route = $resource->route . '?' . $route;
}
unset($route);
$response->headers['Link'] = $this->headerLink($routes);
$response->headers['X-Total-Count'] = $count;
}
$where['LIMIT'] = [($page - 1) * $per_page, $per_page];
}
$resource->where = $where;
/*
* Process request
*/
if ($this->externalHandler($resource)) {
return;
}
$fields = $this->parseFields($resource);
$has_fields = ($resource->query['fields'] ?? '') !== '';
$body = null;
switch ($this->method) {
case 'GET':
case 'HEAD':
$body = $resource->model_class::dump($where, $fields);
break;
case 'DELETE':
$list = [];
foreach ($resource->getIterator() as $id => $model) {
$route = $resource->route . '/'
. (strrpos($resource->route, '/') == 0
? $this->getPrimaryKey($model)
: $id + 1);
$this->deleteModel($model, $resource, $route);
if ($model::SOFT_DELETE !== null) {
$tmp = $model->getData();
if (!empty($fields)) {
$tmp = Utils::arrayWhitelist($tmp, $fields);
} elseif ($has_fields) {
continue;
}
$list[] = $tmp;
}
}
if (!empty($list)) {
$body = $list;
}
break;
case 'PATCH':
$body = [];
foreach ($resource->getIterator() as $id => $model) {
$route = $resource->route . '/'
. (strrpos($resource->route, '/') == 0
? $this->getPrimaryKey($model)
: $id + 1);
$this->updateModel($model, $resource, $route);
$tmp = $model->getData();
if (!empty($fields)) {
$tmp = Utils::arrayWhitelist($tmp, $fields);
} elseif ($has_fields) {
continue;
}
$body[] = $tmp;
}
break;
case 'POST':
$this->checkMissingFields($resource);
$model = $this->createModel($resource);
$location = $this->getContentLocation($model, $resource);
$response->status = HttpResponse::HTTP_CREATED;
$response->headers['Location'] = $location;
break;
case 'PUT':
$this->sendError(
static::ERROR_METHOD_NOT_ALLOWED,
'Collections do not allow PUT Method'
);
break;
}
if ($body !== null) {
$response->headers['Content-Type'] = 'application/json';
$response->body = $body;
}
return $response;
} | When requested route points to a collection
@param Resource $resource Processed route
@return Response
@return null If response was sent by external handler
@throws RouterException If Resource has invalid filters group
@throws RouterException If filter query parameter is invalid
@throws RouterException If per_page query parameter is invalid
@throws RouterException If page query parameter is invalid
@throws RouterException If Resource has invalid Content-Type handler
@throws RouterException If requesting with PUT method | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L856-L1122 |
aryelgois/medools-router | src/Router.php | Router.requestResource | protected function requestResource(Resource $resource)
{
if ($this->externalHandler($resource)) {
return;
}
$response = $this->prepareResponse();
$resource_class = $resource->model_class;
$fields = $this->parseFields($resource);
$has_fields = ($resource->query['fields'] ?? '') !== '';
if ($resource->exists) {
$model = $resource_class::getInstance($resource->where);
}
switch ($this->method) {
case 'GET':
case 'HEAD':
// default output
break;
case 'DELETE':
$this->deleteModel($model, $resource);
break;
case 'PATCH':
$this->updateModel($model, $resource);
$location = $this->getContentLocation($model, $resource);
$resource->content_location = $location;
break;
case 'POST':
$this->sendError(
static::ERROR_METHOD_NOT_ALLOWED,
'Resources do not allow POST Method'
);
break;
case 'PUT':
$resource->data = array_merge(
$resource->where,
$resource->data
);
$this->checkMissingFields($resource);
if ($resource->exists) {
/*
* Trying to clear optional columns
*
* It is better than deleting the model and re-creating it,
* because could trigger ForeignConstraintException
*/
$optional = array_filter(array_merge(
$model::OPTIONAL_COLUMNS,
[$model::AUTO_INCREMENT],
$model::getAutoStampColumns()
));
$optional = array_diff($optional, $model::PRIMARY_KEY);
foreach ($optional as $column) {
$model->$column = null;
}
if ($model::SOFT_DELETE !== null) {
$model->undelete();
}
$this->updateModel($model, $resource);
$location = $this->getContentLocation($model, $resource);
} else {
$model = $this->createModel($resource);
$location = $this->getContentLocation($model, $resource);
$response->status = HttpResponse::HTTP_CREATED;
$response->headers['Location'] = $location;
}
$resource->content_location = $location;
break;
}
if ($this->method !== 'DELETE' || $model::SOFT_DELETE !== null) {
$expand = $resource->query['expand'] ?? null;
if ($expand === 'false'
|| !$this->always_expand && $expand === null
) {
$body = $model->getData();
$foreigns = $this->getForeignRoutes($model, $fields);
if (!empty($foreigns)) {
$response->headers['Link'] = $this->headerLink($foreigns);
}
} else {
$body = $model->toArray();
}
if (!empty($fields)) {
$body = Utils::arrayWhitelist($body, $fields);
} elseif ($has_fields) {
$body = null;
}
$response->headers['Content-Type'] = 'application/json';
$response->body = $body;
}
return $response;
} | php | protected function requestResource(Resource $resource)
{
if ($this->externalHandler($resource)) {
return;
}
$response = $this->prepareResponse();
$resource_class = $resource->model_class;
$fields = $this->parseFields($resource);
$has_fields = ($resource->query['fields'] ?? '') !== '';
if ($resource->exists) {
$model = $resource_class::getInstance($resource->where);
}
switch ($this->method) {
case 'GET':
case 'HEAD':
// default output
break;
case 'DELETE':
$this->deleteModel($model, $resource);
break;
case 'PATCH':
$this->updateModel($model, $resource);
$location = $this->getContentLocation($model, $resource);
$resource->content_location = $location;
break;
case 'POST':
$this->sendError(
static::ERROR_METHOD_NOT_ALLOWED,
'Resources do not allow POST Method'
);
break;
case 'PUT':
$resource->data = array_merge(
$resource->where,
$resource->data
);
$this->checkMissingFields($resource);
if ($resource->exists) {
/*
* Trying to clear optional columns
*
* It is better than deleting the model and re-creating it,
* because could trigger ForeignConstraintException
*/
$optional = array_filter(array_merge(
$model::OPTIONAL_COLUMNS,
[$model::AUTO_INCREMENT],
$model::getAutoStampColumns()
));
$optional = array_diff($optional, $model::PRIMARY_KEY);
foreach ($optional as $column) {
$model->$column = null;
}
if ($model::SOFT_DELETE !== null) {
$model->undelete();
}
$this->updateModel($model, $resource);
$location = $this->getContentLocation($model, $resource);
} else {
$model = $this->createModel($resource);
$location = $this->getContentLocation($model, $resource);
$response->status = HttpResponse::HTTP_CREATED;
$response->headers['Location'] = $location;
}
$resource->content_location = $location;
break;
}
if ($this->method !== 'DELETE' || $model::SOFT_DELETE !== null) {
$expand = $resource->query['expand'] ?? null;
if ($expand === 'false'
|| !$this->always_expand && $expand === null
) {
$body = $model->getData();
$foreigns = $this->getForeignRoutes($model, $fields);
if (!empty($foreigns)) {
$response->headers['Link'] = $this->headerLink($foreigns);
}
} else {
$body = $model->toArray();
}
if (!empty($fields)) {
$body = Utils::arrayWhitelist($body, $fields);
} elseif ($has_fields) {
$body = null;
}
$response->headers['Content-Type'] = 'application/json';
$response->body = $body;
}
return $response;
} | When requested route points to a resource
@param Resource $resource Processed route
@return Response
@return null If response was sent by external handler
@throws RouterException If Resource has invalid Content-Type handler
@throws RouterException If requesting with POST method | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1135-L1242 |
aryelgois/medools-router | src/Router.php | Router.requestRoot | protected function requestRoot(array $headers, string $body)
{
$authorization = $this->getAuthorizedResources();
$resources = Utils::arrayWhitelist(
$this->resources,
array_keys($authorization)
);
if (empty($resources)) {
$this->sendError(
static::ERROR_UNAUTHORIZED,
'You can not access the index'
);
}
$count = [];
foreach (array_keys($resources) as $resource) {
$count[$resource] = $this->countResource(
$resource,
$authorization[$resource]
);
}
$response = $this->prepareResponse();
$response->headers['Content-Type'] = 'application/json';
$response->body = (empty($this->meta))
? $count
: array_merge($this->meta, ['resources' => $count]);
return $response;
} | php | protected function requestRoot(array $headers, string $body)
{
$authorization = $this->getAuthorizedResources();
$resources = Utils::arrayWhitelist(
$this->resources,
array_keys($authorization)
);
if (empty($resources)) {
$this->sendError(
static::ERROR_UNAUTHORIZED,
'You can not access the index'
);
}
$count = [];
foreach (array_keys($resources) as $resource) {
$count[$resource] = $this->countResource(
$resource,
$authorization[$resource]
);
}
$response = $this->prepareResponse();
$response->headers['Content-Type'] = 'application/json';
$response->body = (empty($this->meta))
? $count
: array_merge($this->meta, ['resources' => $count]);
return $response;
} | When requested route is '/'
NOTE:
- Parameters are ignored here. But they exist for children classes
@param array $headers Request Headers
@param string $body Request Body
@return Response With $meta and a row count for each resource. If $meta
is empty, only the resource count is included | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1256-L1287 |
aryelgois/medools-router | src/Router.php | Router.parseAccept | public static function parseAccept(string $accept)
{
$result = [];
foreach (explode(',', $accept) as $directive) {
$parts = explode(';', $directive, 2);
$type = trim($parts[0]);
$priority = ((float) filter_var(
$parts[1] ?? 1,
FILTER_SANITIZE_NUMBER_FLOAT,
FILTER_FLAG_ALLOW_FRACTION
));
$priority = Utils::numberLimit($priority, 0, 1);
if (strpos($type, '*') !== false) {
$priority -= 0.0001;
}
$result[$type] = $priority;
}
return $result;
} | php | public static function parseAccept(string $accept)
{
$result = [];
foreach (explode(',', $accept) as $directive) {
$parts = explode(';', $directive, 2);
$type = trim($parts[0]);
$priority = ((float) filter_var(
$parts[1] ?? 1,
FILTER_SANITIZE_NUMBER_FLOAT,
FILTER_FLAG_ALLOW_FRACTION
));
$priority = Utils::numberLimit($priority, 0, 1);
if (strpos($type, '*') !== false) {
$priority -= 0.0001;
}
$result[$type] = $priority;
}
return $result;
} | Parses Accept header
@param string $accept Accept header
@return float[] With 'type' => priority
Keys may contain '*' | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1302-L1325 |
aryelgois/medools-router | src/Router.php | Router.parseBody | protected function parseBody(string $resource, string $type, string $body)
{
$content_type = static::parseContentType($type);
$mime = $content_type['mime'] ?? $content_type;
if (($content_type['charset'] ?? null) !== null) {
$body = mb_convert_encoding(
$body,
'UTF-8',
$content_type['charset']
);
}
if ($mime === '') {
if ($body === '') {
return [];
}
} elseif ($mime === 'application/json') {
$data = json_decode($body, true);
if (!empty($data)) {
return [
'mime' => $mime,
'data' => $data,
];
}
} else {
if (!$this->safe_method) {
$handlers = $this->resources[$resource]['handlers'] ?? [];
if (!empty($handlers)) {
$handlers = $handlers[$this->method] ?? null;
if (is_array($handlers)
&& array_key_exists($mime, $handlers)
) {
return [
'mime' => $mime,
'body' => $body,
];
}
}
}
$this->sendError(
static::ERROR_UNSUPPORTED_MEDIA_TYPE,
"Media-Type '$mime' is not supported"
);
}
$this->sendError(
static::ERROR_INVALID_PAYLOAD,
"Body payload could not be parsed"
);
} | php | protected function parseBody(string $resource, string $type, string $body)
{
$content_type = static::parseContentType($type);
$mime = $content_type['mime'] ?? $content_type;
if (($content_type['charset'] ?? null) !== null) {
$body = mb_convert_encoding(
$body,
'UTF-8',
$content_type['charset']
);
}
if ($mime === '') {
if ($body === '') {
return [];
}
} elseif ($mime === 'application/json') {
$data = json_decode($body, true);
if (!empty($data)) {
return [
'mime' => $mime,
'data' => $data,
];
}
} else {
if (!$this->safe_method) {
$handlers = $this->resources[$resource]['handlers'] ?? [];
if (!empty($handlers)) {
$handlers = $handlers[$this->method] ?? null;
if (is_array($handlers)
&& array_key_exists($mime, $handlers)
) {
return [
'mime' => $mime,
'body' => $body,
];
}
}
}
$this->sendError(
static::ERROR_UNSUPPORTED_MEDIA_TYPE,
"Media-Type '$mime' is not supported"
);
}
$this->sendError(
static::ERROR_INVALID_PAYLOAD,
"Body payload could not be parsed"
);
} | Parses request body
@param string $resource Resource name
@param string $type Content-Type header
@param string $body Request Body
@return array
@throws RouterException If $type is not supported
@throws RouterException If $body could not be parsed | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1339-L1390 |
aryelgois/medools-router | src/Router.php | Router.parseContentType | public static function parseContentType(string $content_type)
{
$directives = array_map('trim', explode(';', $content_type));
$result = [
'mime' => array_shift($directives)
];
if (empty($directives)) {
return $result['mime'];
}
foreach ($directives as $directive) {
$parts = explode('=', $directive);
$result[$parts[0]] = $parts[1];
}
return $result;
} | php | public static function parseContentType(string $content_type)
{
$directives = array_map('trim', explode(';', $content_type));
$result = [
'mime' => array_shift($directives)
];
if (empty($directives)) {
return $result['mime'];
}
foreach ($directives as $directive) {
$parts = explode('=', $directive);
$result[$parts[0]] = $parts[1];
}
return $result;
} | Parses a Content-Type header
@param string $content_type Content-Type header to be parsed
@return string
@return string[] With keys 'mime', and 'charset' and/or 'boundary' | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1400-L1418 |
aryelgois/medools-router | src/Router.php | Router.parseFields | protected function parseFields(Resource $resource)
{
$fields = $resource->getFields();
if (!is_array($fields)) {
$this->sendError(static::ERROR_UNKNOWN_FIELDS, $fields);
}
return $fields;
} | php | protected function parseFields(Resource $resource)
{
$fields = $resource->getFields();
if (!is_array($fields)) {
$this->sendError(static::ERROR_UNKNOWN_FIELDS, $fields);
}
return $fields;
} | Parses fields query and validate against a resource
@param Resource $resource Resource
@return string[]
@throws RouterException If fields query parameter has invalid fields | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1429-L1436 |
aryelgois/medools-router | src/Router.php | Router.parseRoute | protected function parseRoute(string $uri)
{
$route = trim(urldecode(parse_url($uri, PHP_URL_PATH)), '/');
if ($route === '') {
return;
}
$extension = null;
if ($this->safe_method && !empty($this->extensions)) {
foreach (array_keys($this->extensions) as $ext) {
$ext = ".$ext";
$len = strlen($ext) * -1;
if (substr($route, $len) === $ext) {
$route = substr($route, 0, $len);
$extension = substr($ext, 1);
break;
}
}
}
$result = [
'route' => "/$route",
'extension' => $extension,
];
$route = explode('/', $route);
$model = $previous = null;
$length = count($route);
for ($i = 0; $i < $length; $i += 2) {
$resource = $route[$i];
$resource_data = $this->resources[$resource] ?? null;
if ($resource_data === null) {
$this->sendError(
static::ERROR_INVALID_RESOURCE,
"Invalid resource '$resource'"
);
}
$resource_class = $resource_data['model'];
$id = $route[$i + 1] ?? null;
$is_last = ($route[$i + 2] ?? null) === null;
if (!$this->isPublic(
$resource,
($is_last ? $this->method : static::SAFE_METHODS)
)
) {
$code = static::ERROR_UNAUTHORIZED;
if ($this->auth instanceof Authentication) {
$authorization = Authorization::getInstance([
'user' => $this->auth->id,
'resource' => $resource,
]);
if ($authorization !== null) {
$methods = $authorization->methods;
$allowed = $methods === null
|| in_array(
($is_last ? $this->method : 'GET'),
json_decode($methods, true)
);
if ($allowed) {
$code = null;
$filter = $authorization->filter;
$authorized = json_decode($filter, true);
}
}
}
if (isset($code)) {
$this->sendError($code, "You can not access '$resource'");
}
}
if ($id === null) {
$where = ($model !== null)
? static::reverseForeignKey($resource_class, $model)
: [];
if ($where === null) {
$message = "Resource '$resource' does not have foreign key "
. "for '$previous'";
$this->sendError(
static::ERROR_INVALID_RESOURCE_FOREIGN,
$message
);
}
return array_merge(
$result,
[
'name' => $resource,
'kind' => 'collection',
'model_class' => $resource_class,
'where' => $where,
'authorized' => $authorized ?? null,
]
);
} else {
if ($model === null) {
$where = @array_combine(
$resource_class::PRIMARY_KEY,
explode($this->primary_key_separator, $id)
);
if ($where === false) {
$this->sendError(
static::ERROR_INVALID_RESOURCE_ID,
"Invalid resource id for '$resource': '$id'"
);
}
if (isset($authorized)) {
$where = [
'AND # Requested' => $where,
'AND # Authorized' => $authorized,
];
}
} else {
$where = static::reverseForeignKey($resource_class, $model);
if ($where === null) {
$message = "Resource '$resource' does not have foreign "
. "key for '$previous'";
$this->sendError(
static::ERROR_INVALID_RESOURCE_FOREIGN,
$message
);
}
if (isset($authorized)) {
$where = [
'AND # Requested' => $where,
'AND # Authorized' => $authorized,
];
}
$collection = $resource_class::dump(
$where,
$resource_class::PRIMARY_KEY
);
$where = $collection[$id - 1] ?? null;
if ($where === null) {
if ($is_last && $this->method === 'PUT') {
$exists = false;
} else {
$message = 'Invalid collection offset for '
. "'$resource': '$id'";
$this->sendError(
static::ERROR_INVALID_RESOURCE_OFFSET,
$message
);
}
} else {
$content_location = "$this->url/$resource/" . implode(
$this->primary_key_separator,
$where
);
}
}
$model = ($where !== null)
? $resource_class::getInstance($where)
: null;
if ($model === null) {
if ($is_last && $this->method === 'PUT') {
$exists = false;
} else {
$this->sendError(
static::ERROR_RESOURCE_NOT_FOUND,
"Resource '$resource/$id' not found"
);
}
}
if ($is_last) {
return array_merge(
$result,
[
'name' => $resource,
'kind' => 'resource',
'model_class' => $resource_class,
'where' => $where,
'exists' => $exists ?? true,
'content_location' => $content_location ?? null,
]
);
}
}
$previous = $resource;
}
} | php | protected function parseRoute(string $uri)
{
$route = trim(urldecode(parse_url($uri, PHP_URL_PATH)), '/');
if ($route === '') {
return;
}
$extension = null;
if ($this->safe_method && !empty($this->extensions)) {
foreach (array_keys($this->extensions) as $ext) {
$ext = ".$ext";
$len = strlen($ext) * -1;
if (substr($route, $len) === $ext) {
$route = substr($route, 0, $len);
$extension = substr($ext, 1);
break;
}
}
}
$result = [
'route' => "/$route",
'extension' => $extension,
];
$route = explode('/', $route);
$model = $previous = null;
$length = count($route);
for ($i = 0; $i < $length; $i += 2) {
$resource = $route[$i];
$resource_data = $this->resources[$resource] ?? null;
if ($resource_data === null) {
$this->sendError(
static::ERROR_INVALID_RESOURCE,
"Invalid resource '$resource'"
);
}
$resource_class = $resource_data['model'];
$id = $route[$i + 1] ?? null;
$is_last = ($route[$i + 2] ?? null) === null;
if (!$this->isPublic(
$resource,
($is_last ? $this->method : static::SAFE_METHODS)
)
) {
$code = static::ERROR_UNAUTHORIZED;
if ($this->auth instanceof Authentication) {
$authorization = Authorization::getInstance([
'user' => $this->auth->id,
'resource' => $resource,
]);
if ($authorization !== null) {
$methods = $authorization->methods;
$allowed = $methods === null
|| in_array(
($is_last ? $this->method : 'GET'),
json_decode($methods, true)
);
if ($allowed) {
$code = null;
$filter = $authorization->filter;
$authorized = json_decode($filter, true);
}
}
}
if (isset($code)) {
$this->sendError($code, "You can not access '$resource'");
}
}
if ($id === null) {
$where = ($model !== null)
? static::reverseForeignKey($resource_class, $model)
: [];
if ($where === null) {
$message = "Resource '$resource' does not have foreign key "
. "for '$previous'";
$this->sendError(
static::ERROR_INVALID_RESOURCE_FOREIGN,
$message
);
}
return array_merge(
$result,
[
'name' => $resource,
'kind' => 'collection',
'model_class' => $resource_class,
'where' => $where,
'authorized' => $authorized ?? null,
]
);
} else {
if ($model === null) {
$where = @array_combine(
$resource_class::PRIMARY_KEY,
explode($this->primary_key_separator, $id)
);
if ($where === false) {
$this->sendError(
static::ERROR_INVALID_RESOURCE_ID,
"Invalid resource id for '$resource': '$id'"
);
}
if (isset($authorized)) {
$where = [
'AND # Requested' => $where,
'AND # Authorized' => $authorized,
];
}
} else {
$where = static::reverseForeignKey($resource_class, $model);
if ($where === null) {
$message = "Resource '$resource' does not have foreign "
. "key for '$previous'";
$this->sendError(
static::ERROR_INVALID_RESOURCE_FOREIGN,
$message
);
}
if (isset($authorized)) {
$where = [
'AND # Requested' => $where,
'AND # Authorized' => $authorized,
];
}
$collection = $resource_class::dump(
$where,
$resource_class::PRIMARY_KEY
);
$where = $collection[$id - 1] ?? null;
if ($where === null) {
if ($is_last && $this->method === 'PUT') {
$exists = false;
} else {
$message = 'Invalid collection offset for '
. "'$resource': '$id'";
$this->sendError(
static::ERROR_INVALID_RESOURCE_OFFSET,
$message
);
}
} else {
$content_location = "$this->url/$resource/" . implode(
$this->primary_key_separator,
$where
);
}
}
$model = ($where !== null)
? $resource_class::getInstance($where)
: null;
if ($model === null) {
if ($is_last && $this->method === 'PUT') {
$exists = false;
} else {
$this->sendError(
static::ERROR_RESOURCE_NOT_FOUND,
"Resource '$resource/$id' not found"
);
}
}
if ($is_last) {
return array_merge(
$result,
[
'name' => $resource,
'kind' => 'resource',
'model_class' => $resource_class,
'where' => $where,
'exists' => $exists ?? true,
'content_location' => $content_location ?? null,
]
);
}
}
$previous = $resource;
}
} | Parses a URI route
@param string $uri Route to be parsed
@return mixed[] On success
@return null On failure
@throws RouterException If requesting invalid resource
@throws RouterException If resource is incorrectly nested
@throws RouterException If route has invalid resource id
@throws RouterException If route has invalid collection offset
@throws RouterException If resource was not found. It may exist but the
user is not authorized to see it | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1453-L1642 |
aryelgois/medools-router | src/Router.php | Router.createModel | protected function createModel(Resource $resource)
{
$model = new $resource->model_class;
$model->fill($resource->data);
$result = $model->save();
if ($result === true) {
return $model;
}
$code = (empty($resource->data) || $result === null)
? static::ERROR_INVALID_PAYLOAD
: static::ERROR_INTERNAL_SERVER;
$message = "Resource '$resource->name' could not be created: ";
if (is_string($result)) {
$message .= "Database failure ($result)";
} elseif ($result === false) {
$message .= 'post-save failure';
} else {
$message .= 'pre-save failure';
}
$this->sendError($code, $message);
} | php | protected function createModel(Resource $resource)
{
$model = new $resource->model_class;
$model->fill($resource->data);
$result = $model->save();
if ($result === true) {
return $model;
}
$code = (empty($resource->data) || $result === null)
? static::ERROR_INVALID_PAYLOAD
: static::ERROR_INTERNAL_SERVER;
$message = "Resource '$resource->name' could not be created: ";
if (is_string($result)) {
$message .= "Database failure ($result)";
} elseif ($result === false) {
$message .= 'post-save failure';
} else {
$message .= 'pre-save failure';
}
$this->sendError($code, $message);
} | Creates a Model in the Database
@param Resource $resource Processed route
@return Model
@throws RouterException If could not save the new Model | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1658-L1683 |
aryelgois/medools-router | src/Router.php | Router.deleteModel | protected function deleteModel(
Model $model,
Resource $resource,
string $route = null
) {
if ($model->delete()) {
return;
}
$message = "Resource '" . ($route ?? $resource->route)
. "' could not be deleted";
$this->sendError(static::ERROR_INTERNAL_SERVER, $message);
} | php | protected function deleteModel(
Model $model,
Resource $resource,
string $route = null
) {
if ($model->delete()) {
return;
}
$message = "Resource '" . ($route ?? $resource->route)
. "' could not be deleted";
$this->sendError(static::ERROR_INTERNAL_SERVER, $message);
} | Deletes a Model
@param Model $model Model to be deleted
@param Resource $resource Resource that loaded $model
@param string $route Alternative route to $model
@throws RouterException If could not delete the Model | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1694-L1707 |
aryelgois/medools-router | src/Router.php | Router.updateModel | protected function updateModel(
Model $model,
Resource $resource,
string $route = null
) {
$model->fill($resource->data);
$result = $model->update(array_keys($resource->data));
if ($result === true) {
return;
}
$message = "Resource '" . ($route ?? $resource->route)
. "' could not be updated";
if (is_string($result)) {
$message .= ": Database failure ($result)";
}
$this->sendError(static::ERROR_INTERNAL_SERVER, $message);
} | php | protected function updateModel(
Model $model,
Resource $resource,
string $route = null
) {
$model->fill($resource->data);
$result = $model->update(array_keys($resource->data));
if ($result === true) {
return;
}
$message = "Resource '" . ($route ?? $resource->route)
. "' could not be updated";
if (is_string($result)) {
$message .= ": Database failure ($result)";
}
$this->sendError(static::ERROR_INTERNAL_SERVER, $message);
} | Updates a Model
@param Model $model Model to be updated
@param Resource $resource Resource that loaded $model
@param string $route Alternative route to $model
@throws RouterException If could not update the Model | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1718-L1738 |
aryelgois/medools-router | src/Router.php | Router.checkCache | protected function checkCache(
Response $response,
string $e_tags,
int $max_age
) {
$result = $response;
$cache_method = $this->cache_method;
if (is_callable($cache_method)) {
$hash = '"' . $cache_method(serialize($response->body)) . '"';
if (strpos($e_tags, $hash) !== false) {
$reuse_headers = Utils::arrayWhitelist(
$response->headers,
[
'Content-Location',
]
);
$result = $this->prepareResponse();
$result->status = HttpResponse::HTTP_NOT_MODIFIED;
$result->headers = $reuse_headers;
}
$result->headers['ETag'] = $hash;
$result->headers['Cache-Control'] = 'private, max-age=' . $max_age
. ', must-revalidate';
} else {
$this->sendError(
static::ERROR_INTERNAL_SERVER,
"Router config 'cache_method' is invalid"
);
}
return $result;
} | php | protected function checkCache(
Response $response,
string $e_tags,
int $max_age
) {
$result = $response;
$cache_method = $this->cache_method;
if (is_callable($cache_method)) {
$hash = '"' . $cache_method(serialize($response->body)) . '"';
if (strpos($e_tags, $hash) !== false) {
$reuse_headers = Utils::arrayWhitelist(
$response->headers,
[
'Content-Location',
]
);
$result = $this->prepareResponse();
$result->status = HttpResponse::HTTP_NOT_MODIFIED;
$result->headers = $reuse_headers;
}
$result->headers['ETag'] = $hash;
$result->headers['Cache-Control'] = 'private, max-age=' . $max_age
. ', must-revalidate';
} else {
$this->sendError(
static::ERROR_INTERNAL_SERVER,
"Router config 'cache_method' is invalid"
);
}
return $result;
} | Checks if Response is modified from Client's cache
It adds caching headers
@param Response $response Response to be checked
@param string $e_tags Request If-None-Match Header
@param integer $max_age Resource max_age
@return Response With caching headers or with Not Modified status
@throws RouterException If 'cache_method' config is invalid | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1758-L1793 |
aryelgois/medools-router | src/Router.php | Router.checkMissingFields | protected function checkMissingFields(Resource $resource)
{
$missing = array_diff(
$resource->model_class::getRequiredColumns(),
array_keys($resource->data)
);
if (!empty($missing)) {
$message = "Resource '$resource->name' requires the following "
. "missing fields: '" . implode("', '", $missing) . "'";
$this->sendError(static::ERROR_INVALID_PAYLOAD, $message);
}
} | php | protected function checkMissingFields(Resource $resource)
{
$missing = array_diff(
$resource->model_class::getRequiredColumns(),
array_keys($resource->data)
);
if (!empty($missing)) {
$message = "Resource '$resource->name' requires the following "
. "missing fields: '" . implode("', '", $missing) . "'";
$this->sendError(static::ERROR_INVALID_PAYLOAD, $message);
}
} | Checks if resource data fulfills the required columns
@param Resource $resource Resource
@throws RouterException If required fields are missing | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1802-L1814 |
aryelgois/medools-router | src/Router.php | Router.checkUnknownField | protected function checkUnknownField(Resource $resource, array $fields)
{
$message = $resource->hasFields($fields);
if ($message !== true) {
$this->sendError(static::ERROR_UNKNOWN_FIELDS, $message);
}
} | php | protected function checkUnknownField(Resource $resource, array $fields)
{
$message = $resource->hasFields($fields);
if ($message !== true) {
$this->sendError(static::ERROR_UNKNOWN_FIELDS, $message);
}
} | Checks if a resource has all fields passed
@param Resource $resource Resource
@param string[] $fields List of fields to test
@throws RouterException If there are unknown fields | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1824-L1830 |
aryelgois/medools-router | src/Router.php | Router.compareAccept | public static function compareAccept(string $accept, array $available)
{
$result = [];
foreach (static::parseAccept($accept) as $type => $priority) {
if (strpos($type, '*') === false) {
if (in_array($type, $available)) {
$result[$type] = max($result[$type] ?? 0, $priority);
}
} else {
foreach ($available as $available_type) {
if (fnmatch($type, $available_type)) {
$result[$available_type] = max(
$result[$available_type] ?? 0,
$priority
);
}
}
}
}
return $result;
} | php | public static function compareAccept(string $accept, array $available)
{
$result = [];
foreach (static::parseAccept($accept) as $type => $priority) {
if (strpos($type, '*') === false) {
if (in_array($type, $available)) {
$result[$type] = max($result[$type] ?? 0, $priority);
}
} else {
foreach ($available as $available_type) {
if (fnmatch($type, $available_type)) {
$result[$available_type] = max(
$result[$available_type] ?? 0,
$priority
);
}
}
}
}
return $result;
} | Compares content types in an Accept header with a list of available types
@param string $accept Accept header
@param string[] $available Available content types
@return float[] With 'type' => priority | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1840-L1860 |
aryelgois/medools-router | src/Router.php | Router.countResource | protected function countResource(string $resource, array $where = null)
{
$model = $this->resources[$resource]['model'];
$database = $model::getDatabase();
return $database->count($model::TABLE, $where ?? []);
} | php | protected function countResource(string $resource, array $where = null)
{
$model = $this->resources[$resource]['model'];
$database = $model::getDatabase();
return $database->count($model::TABLE, $where ?? []);
} | Counts rows in Resource's table
@param string $resource Resource name
@param mixed[] $where \Medoo\Medoo $where clause
@return integer | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1870-L1875 |
aryelgois/medools-router | src/Router.php | Router.externalHandler | protected function externalHandler(Resource $resource)
{
$handlers = $this->resources[$resource->name]['handlers'] ?? [];
if (!empty($handlers)) {
if ($this->safe_method) {
$handlers = $handlers['GET'] ?? null;
if (is_array($handlers)) {
$handlers = $this->getAvailableTypes($resource->name);
$type = $resource->content_type;
}
} else {
$handlers = $handlers[$this->method] ?? null;
if (is_array($handlers)) {
$type = $resource->payload['mime'];
}
}
if (isset($type)) {
$handler = $handlers[$type];
if (is_array($handler)) {
$handler = $handler[$resource->kind];
}
if ($type === 'application/json' && $handler == '__DEFAULT__') {
$handler = null;
}
} else {
$handler = $handlers;
}
if ($handler !== null) {
if (is_callable($handler)) {
if ($this->method === 'HEAD') {
ob_start();
$handler($resource);
ob_end_clean();
} else {
$handler($resource);
flush();
}
return true;
}
$this->sendError(static::ERROR_INTERNAL_SERVER, sprintf(
"Resource '%s' has invalid %s handler: '%s' (%s request)",
$resource->name,
$this->method,
$handler,
$resource->kind
));
}
}
return false;
} | php | protected function externalHandler(Resource $resource)
{
$handlers = $this->resources[$resource->name]['handlers'] ?? [];
if (!empty($handlers)) {
if ($this->safe_method) {
$handlers = $handlers['GET'] ?? null;
if (is_array($handlers)) {
$handlers = $this->getAvailableTypes($resource->name);
$type = $resource->content_type;
}
} else {
$handlers = $handlers[$this->method] ?? null;
if (is_array($handlers)) {
$type = $resource->payload['mime'];
}
}
if (isset($type)) {
$handler = $handlers[$type];
if (is_array($handler)) {
$handler = $handler[$resource->kind];
}
if ($type === 'application/json' && $handler == '__DEFAULT__') {
$handler = null;
}
} else {
$handler = $handlers;
}
if ($handler !== null) {
if (is_callable($handler)) {
if ($this->method === 'HEAD') {
ob_start();
$handler($resource);
ob_end_clean();
} else {
$handler($resource);
flush();
}
return true;
}
$this->sendError(static::ERROR_INTERNAL_SERVER, sprintf(
"Resource '%s' has invalid %s handler: '%s' (%s request)",
$resource->name,
$this->method,
$handler,
$resource->kind
));
}
}
return false;
} | Determines external handler for a Resource and executes it
@param Resource $resource Resource to be sent to handler
@return boolean For success or failure
@throws RouterException If handler is invalid | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1886-L1939 |
aryelgois/medools-router | src/Router.php | Router.firstHigher | public static function firstHigher(
array $list,
float $min = null,
float $max = null
) {
$bounded_list = array_merge([$min ?? 0, $max ?? 1], $list);
$min = min($bounded_list);
$max = max($bounded_list);
$result = null;
$higher = $min;
foreach ($list as $key => $value) {
$value = Utils::numberLimit($value, $min, $max);
if ($value == $max) {
return $key;
} elseif ($value > $higher) {
$result = $key;
$higher = $value;
}
}
return $result;
} | php | public static function firstHigher(
array $list,
float $min = null,
float $max = null
) {
$bounded_list = array_merge([$min ?? 0, $max ?? 1], $list);
$min = min($bounded_list);
$max = max($bounded_list);
$result = null;
$higher = $min;
foreach ($list as $key => $value) {
$value = Utils::numberLimit($value, $min, $max);
if ($value == $max) {
return $key;
} elseif ($value > $higher) {
$result = $key;
$higher = $value;
}
}
return $result;
} | Returns key for first highest value
@param float[] $list List of numbers between min and max
@param float $min Min value to test (default is 0)
@param float $max Max value to test (default is 1)
@return mixed $list key
@return null If no value was higher than $min | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1951-L1975 |
aryelgois/medools-router | src/Router.php | Router.getAcceptedResourceType | protected function getAcceptedResourceType(string $resource, string $accept)
{
$available = array_keys($this->getAvailableTypes($resource));
if (empty($available)) {
$this->sendError(
static::ERROR_INTERNAL_SERVER,
"Resource '$resource' has invalid GET handlers"
);
}
$accepted = static::getAcceptedType($accept, $available);
if ($accepted === false) {
$message = "Resource '$resource' can not generate content"
. ' complying to Accept header';
$this->sendError(static::ERROR_NOT_ACCEPTABLE, $message);
}
return $accepted;
} | php | protected function getAcceptedResourceType(string $resource, string $accept)
{
$available = array_keys($this->getAvailableTypes($resource));
if (empty($available)) {
$this->sendError(
static::ERROR_INTERNAL_SERVER,
"Resource '$resource' has invalid GET handlers"
);
}
$accepted = static::getAcceptedType($accept, $available);
if ($accepted === false) {
$message = "Resource '$resource' can not generate content"
. ' complying to Accept header';
$this->sendError(static::ERROR_NOT_ACCEPTABLE, $message);
}
return $accepted;
} | Determines an accepted Content-Type for a Resource
@see getAcceptedType()
@param string $resource Resource name
@param string $accept Accept header
@return string
@throws RouterException If $resource has invalid Content-Type
@throws RouterException If no content type is acceptable | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L1990-L2008 |
aryelgois/medools-router | src/Router.php | Router.getAcceptedType | public static function getAcceptedType(string $accept, array $available)
{
$list = static::compareAccept($accept, $available);
if (empty($list)) {
return array_values($available)[0];
}
$result = static::firstHigher($list);
if ($result !== null) {
return $result;
}
$forbidden = array_filter($list, function ($value) {
return $value === 0;
});
$allowed = array_diff($available, array_keys($forbidden));
if (empty($allowed)) {
return false;
}
return array_values($allowed)[0];
} | php | public static function getAcceptedType(string $accept, array $available)
{
$list = static::compareAccept($accept, $available);
if (empty($list)) {
return array_values($available)[0];
}
$result = static::firstHigher($list);
if ($result !== null) {
return $result;
}
$forbidden = array_filter($list, function ($value) {
return $value === 0;
});
$allowed = array_diff($available, array_keys($forbidden));
if (empty($allowed)) {
return false;
}
return array_values($allowed)[0];
} | Determines an accepted Content-Type from a list
NOTE:
- If no $available content types match $accept, but at least one of them
is not forbidden by $accept (i.e. ';q=0'), it is returned. It is better
to respond something the client doesn't complain about than a useless
error message
@param string $accept Accept header
@param string[] $available List of available content types
@return string
@return false If no content type is acceptable | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L2025-L2047 |
aryelgois/medools-router | src/Router.php | Router.getAllowedMethods | protected function getAllowedMethods(string $resource)
{
$cached = $this->cache['allowed_methods'][$resource] ?? null;
if ($cached !== null) {
return $cached;
}
$resource_data = $this->resources[$resource] ?? null;
if ($resource_data === null) {
throw new \DomainException("Invalid resource '$resource'");
}
$allow = $this->implemented_methods;
$methods = (array) ($resource_data['methods'] ?? null);
if (!empty($methods)) {
$allow = array_intersect(
$allow,
array_merge($methods, ['OPTIONS'])
);
}
$this->cache['allowed_methods'][$resource] = $allow;
return $allow;
} | php | protected function getAllowedMethods(string $resource)
{
$cached = $this->cache['allowed_methods'][$resource] ?? null;
if ($cached !== null) {
return $cached;
}
$resource_data = $this->resources[$resource] ?? null;
if ($resource_data === null) {
throw new \DomainException("Invalid resource '$resource'");
}
$allow = $this->implemented_methods;
$methods = (array) ($resource_data['methods'] ?? null);
if (!empty($methods)) {
$allow = array_intersect(
$allow,
array_merge($methods, ['OPTIONS'])
);
}
$this->cache['allowed_methods'][$resource] = $allow;
return $allow;
} | Returns a list of allowed methods for a resource
NOTE:
- It caches results
@param string $resource Resource name
@return string[]
@throws \DomainException If $resource is invalid | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L2061-L2085 |
aryelgois/medools-router | src/Router.php | Router.getAvailableTypes | protected function getAvailableTypes(string $resource)
{
$cached = $this->cache['available_types'][$resource] ?? null;
if ($cached !== null) {
return $cached;
}
$types = $this->resources[$resource]['handlers']['GET'] ?? [];
$types = (is_array($types))
? array_filter(array_replace($this->default_content_type, $types))
: [];
$this->cache['available_types'][$resource] = $types;
return $types;
} | php | protected function getAvailableTypes(string $resource)
{
$cached = $this->cache['available_types'][$resource] ?? null;
if ($cached !== null) {
return $cached;
}
$types = $this->resources[$resource]['handlers']['GET'] ?? [];
$types = (is_array($types))
? array_filter(array_replace($this->default_content_type, $types))
: [];
$this->cache['available_types'][$resource] = $types;
return $types;
} | Computes GET Resource's content types
NOTE:
- It caches results
@param string $resource Resource name
@return mixed[] | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L2097-L2111 |
aryelgois/medools-router | src/Router.php | Router.getAuthorizedResources | protected function getAuthorizedResources($methods = null)
{
$resources = [];
if ($this->auth instanceof Authentication) {
$allow = (array) ($methods ?? $this->method);
$authorizations = Authorization::dump(
[
'user' => $this->auth->id,
],
[
'resource',
'methods',
'filter',
]
);
foreach ($authorizations as $authorization) {
$resource = $authorization['resource'];
if (array_key_exists($resource, $this->resources)) {
if ($this->isPublic($resource, $methods)) {
$resources[$resource] = null;
} elseif (!empty(array_intersect(
$this->getAllowedMethods($resource),
array_merge(
$authorization['methods'] ?? [],
$allow
)
))) {
$resources[$resource] = $authorization['filter'];
}
}
}
} else {
$resources = array_keys($this->resources);
if ($this->auth === false) {
foreach ($resources as $id => $resource) {
if (!$this->isPublic($resource, $methods)) {
unset($resources[$id]);
}
}
}
$resources = array_fill_keys(array_values($resources), null);
}
return $resources;
} | php | protected function getAuthorizedResources($methods = null)
{
$resources = [];
if ($this->auth instanceof Authentication) {
$allow = (array) ($methods ?? $this->method);
$authorizations = Authorization::dump(
[
'user' => $this->auth->id,
],
[
'resource',
'methods',
'filter',
]
);
foreach ($authorizations as $authorization) {
$resource = $authorization['resource'];
if (array_key_exists($resource, $this->resources)) {
if ($this->isPublic($resource, $methods)) {
$resources[$resource] = null;
} elseif (!empty(array_intersect(
$this->getAllowedMethods($resource),
array_merge(
$authorization['methods'] ?? [],
$allow
)
))) {
$resources[$resource] = $authorization['filter'];
}
}
}
} else {
$resources = array_keys($this->resources);
if ($this->auth === false) {
foreach ($resources as $id => $resource) {
if (!$this->isPublic($resource, $methods)) {
unset($resources[$id]);
}
}
}
$resources = array_fill_keys(array_values($resources), null);
}
return $resources;
} | Returns authorized resources for the authenticated user and their filters
@param string|string[] $methods Which methods to test
Default is requested method
@return mixed[] With 'resource' => filter | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L2121-L2170 |
aryelgois/medools-router | src/Router.php | Router.getContentLocation | protected function getContentLocation(Model $model, Resource $resource)
{
$query = http_build_query($resource->query);
$content_location = "$this->url/$resource->name/"
. $this->getPrimaryKey($model)
. ($query !== '' ? '?' . $query : '');
return $content_location;
} | php | protected function getContentLocation(Model $model, Resource $resource)
{
$query = http_build_query($resource->query);
$content_location = "$this->url/$resource->name/"
. $this->getPrimaryKey($model)
. ($query !== '' ? '?' . $query : '');
return $content_location;
} | Returns Content-Location for a Model in a Resource
@param Model $model Model to get Location
@param Resource $resource Resource that loaded $model
@return string | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L2180-L2189 |
aryelgois/medools-router | src/Router.php | Router.getForeignRoutes | protected function getForeignRoutes(Model $model, array $filter = null)
{
$routes = [];
$foreigns = $model::FOREIGN_KEYS;
if (!empty($filter)) {
$foreigns = Utils::arrayWhitelist($foreigns, $filter);
}
foreach ($foreigns as $column => $fk) {
foreach ($this->resources as $resource_name => $resource_data) {
if ($resource_data['model'] === $fk[0]) {
$foreign = $model->$column;
if ($foreign !== null) {
$routes[$column] = "/$resource_name/"
. $this->getPrimaryKey($foreign);
}
break;
}
}
}
return $routes;
} | php | protected function getForeignRoutes(Model $model, array $filter = null)
{
$routes = [];
$foreigns = $model::FOREIGN_KEYS;
if (!empty($filter)) {
$foreigns = Utils::arrayWhitelist($foreigns, $filter);
}
foreach ($foreigns as $column => $fk) {
foreach ($this->resources as $resource_name => $resource_data) {
if ($resource_data['model'] === $fk[0]) {
$foreign = $model->$column;
if ($foreign !== null) {
$routes[$column] = "/$resource_name/"
. $this->getPrimaryKey($foreign);
}
break;
}
}
}
return $routes;
} | Returns list of routes to Model's Foreigns
@param Model $model Model whose Foreigns' routes will be returned
@param string[] $filter Only returns routes for foreigns listed here
Invalid columns are silently ignored
@return string[] | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L2200-L2223 |
aryelgois/medools-router | src/Router.php | Router.headerLink | protected function headerLink(array $routes)
{
$links = [];
foreach ($routes as $rel => $route) {
$links[] = '<' . $this->url . $route . '>; rel="' . $rel . '"';
}
return implode(', ', $links);
} | php | protected function headerLink(array $routes)
{
$links = [];
foreach ($routes as $rel => $route) {
$links[] = '<' . $this->url . $route . '>; rel="' . $rel . '"';
}
return implode(', ', $links);
} | Generates content for Link header
@param string[] $routes List of routes
@return string | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L2244-L2251 |
aryelgois/medools-router | src/Router.php | Router.isPublic | protected function isPublic(string $resource, $methods = null)
{
if (($this->authentication ?? null) === null) {
return true;
}
$resource_data = $this->resources[$resource] ?? null;
if ($resource_data === null) {
return false;
}
$public = $resource_data['public'] ?? $this->default_publicity;
if (is_string($public)) {
$public = [$public];
}
$methods = (array) ($methods ?? $this->method);
return (is_array($public))
? !empty(array_intersect($public, $methods))
: (bool) $public;
} | php | protected function isPublic(string $resource, $methods = null)
{
if (($this->authentication ?? null) === null) {
return true;
}
$resource_data = $this->resources[$resource] ?? null;
if ($resource_data === null) {
return false;
}
$public = $resource_data['public'] ?? $this->default_publicity;
if (is_string($public)) {
$public = [$public];
}
$methods = (array) ($methods ?? $this->method);
return (is_array($public))
? !empty(array_intersect($public, $methods))
: (bool) $public;
} | Tells if a resource's method has public access
@param string $resource Resource name
@param string|string[] $methods Which methods to test
Default is requested method
@return boolean For success or failure | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L2262-L2283 |
aryelgois/medools-router | src/Router.php | Router.prepareResponse | protected function prepareResponse()
{
$response = new Response;
$response->method = $this->method;
$response->zlib_compression = $this->zlib_compression;
return $response;
} | php | protected function prepareResponse()
{
$response = new Response;
$response->method = $this->method;
$response->zlib_compression = $this->zlib_compression;
return $response;
} | Creates a new Response object with some properties filled
@return Response | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L2290-L2296 |
aryelgois/medools-router | src/Router.php | Router.reverseForeignKey | public static function reverseForeignKey(
string $model_class,
Model $target
) {
$target_class = get_class($target);
$column = null;
$found = false;
foreach ($model_class::FOREIGN_KEYS as $column => $fk) {
if ($target_class === $fk[0]) {
$found = true;
break;
}
}
if ($column === null || $found === false) {
return;
}
return [$column => $target->__get($fk[1])];
} | php | public static function reverseForeignKey(
string $model_class,
Model $target
) {
$target_class = get_class($target);
$column = null;
$found = false;
foreach ($model_class::FOREIGN_KEYS as $column => $fk) {
if ($target_class === $fk[0]) {
$found = true;
break;
}
}
if ($column === null || $found === false) {
return;
}
return [$column => $target->__get($fk[1])];
} | Finds the Foreign Key for a Model instance from a Model class
NOTE:
- If $model_class has multiple foreign keys for $target, only the first
one is used. You should redesign your database, duplicate the target
class with a new name or create a new class that extends target, if you
want to match later $model_class foreign keys
@param string $model_class Model with Foreign Key pointing to $target
@param Model $target Model pointed by $model_class
@return mixed[] \Medoo\Medoo $where clause for $target, using a Foreign
Key in $model_class
@return null On failure | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L2314-L2333 |
aryelgois/medools-router | src/Router.php | Router.sendError | protected function sendError(
int $code,
string $message,
$data = null
) {
$response = $this->prepareResponse();
switch ($code) {
case static::ERROR_INTERNAL_SERVER:
$status = HttpResponse::HTTP_INTERNAL_SERVER_ERROR;
break;
case static::ERROR_INVALID_CREDENTIALS:
case static::ERROR_UNAUTHENTICATED:
$status = HttpResponse::HTTP_UNAUTHORIZED;
$realm = $this->authentication['realm'] ?? null;
$auth = 'Basic'
. ($realm !== null ? ' realm="' . $realm . '"' : '')
. ' charset="UTF-8"';
$response->headers['WWW-Authenticate'] = $auth;
break;
case static::ERROR_INVALID_TOKEN:
$status = HttpResponse::HTTP_UNAUTHORIZED;
$realm = $this->authentication['realm'] ?? null;
$auth = 'Bearer'
. ($realm !== null ? ' realm="' . $realm . '"' : '');
$response->headers['WWW-Authenticate'] = $auth;
break;
case static::ERROR_METHOD_NOT_IMPLEMENTED:
$status = HttpResponse::HTTP_NOT_IMPLEMENTED;
$response->headers['Allow'] = $data;
break;
case static::ERROR_UNAUTHORIZED:
$status = HttpResponse::HTTP_FORBIDDEN;
break;
case static::ERROR_INVALID_RESOURCE:
case static::ERROR_INVALID_RESOURCE_ID:
case static::ERROR_INVALID_RESOURCE_OFFSET:
case static::ERROR_INVALID_RESOURCE_FOREIGN:
case static::ERROR_INVALID_PAYLOAD:
case static::ERROR_INVALID_QUERY_PARAMETER:
case static::ERROR_UNKNOWN_FIELDS:
case static::ERROR_READONLY_RESOURCE:
case static::ERROR_FOREIGN_CONSTRAINT:
$status = HttpResponse::HTTP_BAD_REQUEST;
break;
case static::ERROR_RESOURCE_NOT_FOUND:
$status = HttpResponse::HTTP_NOT_FOUND;
break;
case static::ERROR_UNSUPPORTED_MEDIA_TYPE:
$status = HttpResponse::HTTP_UNSUPPORTED_MEDIA_TYPE;
break;
case static::ERROR_METHOD_NOT_ALLOWED:
$status = HttpResponse::HTTP_METHOD_NOT_ALLOWED;
if ($data !== null) {
$response->headers['Allow'] = $data;
}
break;
case static::ERROR_NOT_ACCEPTABLE:
$status = HttpResponse::HTTP_NOT_ACCEPTABLE;
break;
case static::ERROR_UNKNOWN_ERROR:
default:
$actual_code = static::ERROR_UNKNOWN_ERROR;
$status = HttpResponse::HTTP_INTERNAL_SERVER_ERROR;
$message = 'Unknown error'
. (strlen($message) > 0 ? ': ' . $message : '');
break;
}
$response->status = $status;
$response->headers['Content-Type'] = 'application/json';
$response->body = [
'code' => $code,
'message' => $message,
];
throw new RouterException($response, $actual_code ?? $code);
} | php | protected function sendError(
int $code,
string $message,
$data = null
) {
$response = $this->prepareResponse();
switch ($code) {
case static::ERROR_INTERNAL_SERVER:
$status = HttpResponse::HTTP_INTERNAL_SERVER_ERROR;
break;
case static::ERROR_INVALID_CREDENTIALS:
case static::ERROR_UNAUTHENTICATED:
$status = HttpResponse::HTTP_UNAUTHORIZED;
$realm = $this->authentication['realm'] ?? null;
$auth = 'Basic'
. ($realm !== null ? ' realm="' . $realm . '"' : '')
. ' charset="UTF-8"';
$response->headers['WWW-Authenticate'] = $auth;
break;
case static::ERROR_INVALID_TOKEN:
$status = HttpResponse::HTTP_UNAUTHORIZED;
$realm = $this->authentication['realm'] ?? null;
$auth = 'Bearer'
. ($realm !== null ? ' realm="' . $realm . '"' : '');
$response->headers['WWW-Authenticate'] = $auth;
break;
case static::ERROR_METHOD_NOT_IMPLEMENTED:
$status = HttpResponse::HTTP_NOT_IMPLEMENTED;
$response->headers['Allow'] = $data;
break;
case static::ERROR_UNAUTHORIZED:
$status = HttpResponse::HTTP_FORBIDDEN;
break;
case static::ERROR_INVALID_RESOURCE:
case static::ERROR_INVALID_RESOURCE_ID:
case static::ERROR_INVALID_RESOURCE_OFFSET:
case static::ERROR_INVALID_RESOURCE_FOREIGN:
case static::ERROR_INVALID_PAYLOAD:
case static::ERROR_INVALID_QUERY_PARAMETER:
case static::ERROR_UNKNOWN_FIELDS:
case static::ERROR_READONLY_RESOURCE:
case static::ERROR_FOREIGN_CONSTRAINT:
$status = HttpResponse::HTTP_BAD_REQUEST;
break;
case static::ERROR_RESOURCE_NOT_FOUND:
$status = HttpResponse::HTTP_NOT_FOUND;
break;
case static::ERROR_UNSUPPORTED_MEDIA_TYPE:
$status = HttpResponse::HTTP_UNSUPPORTED_MEDIA_TYPE;
break;
case static::ERROR_METHOD_NOT_ALLOWED:
$status = HttpResponse::HTTP_METHOD_NOT_ALLOWED;
if ($data !== null) {
$response->headers['Allow'] = $data;
}
break;
case static::ERROR_NOT_ACCEPTABLE:
$status = HttpResponse::HTTP_NOT_ACCEPTABLE;
break;
case static::ERROR_UNKNOWN_ERROR:
default:
$actual_code = static::ERROR_UNKNOWN_ERROR;
$status = HttpResponse::HTTP_INTERNAL_SERVER_ERROR;
$message = 'Unknown error'
. (strlen($message) > 0 ? ': ' . $message : '');
break;
}
$response->status = $status;
$response->headers['Content-Type'] = 'application/json';
$response->body = [
'code' => $code,
'message' => $message,
];
throw new RouterException($response, $actual_code ?? $code);
} | Sends HTTP header and body (if requested) for an Error
@param int $code Error code
@param string $message Error message
@param mixed $data Additional data used by some error codes
@throws RouterException With error Response | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Router.php#L2344-L2431 |
old-town/workflow-zf2 | src/Options/ConfigurationServiceOptions.php | ConfigurationServiceOptions.getName | public function getName()
{
if (!null === $this->name) {
$errMsg = 'service name not exists';
throw new Exception\InvalidServiceConfigException($errMsg);
}
return $this->name;
} | php | public function getName()
{
if (!null === $this->name) {
$errMsg = 'service name not exists';
throw new Exception\InvalidServiceConfigException($errMsg);
}
return $this->name;
} | Возвращает имя сервиса
@return string
@throws Exception\InvalidServiceConfigException | https://github.com/old-town/workflow-zf2/blob/b63910bd0f4c05855e19cfa29e3376eee7c16c77/src/Options/ConfigurationServiceOptions.php#L38-L45 |
cawaphp/module-clockwork | src/Storage/Session.php | Session.get | public function get(string $id) : array
{
$sessionData = self::session()->get(self::SESSION_VAR);
if (isset($sessionData[$id])) {
$return = $sessionData[$id];
unset($sessionData[$id]);
if (sizeof($sessionData) === 0) {
self::session()->set(self::SESSION_VAR, $sessionData);
} else {
self::session()->remove(self::SESSION_VAR);
}
return $return;
}
return [];
} | php | public function get(string $id) : array
{
$sessionData = self::session()->get(self::SESSION_VAR);
if (isset($sessionData[$id])) {
$return = $sessionData[$id];
unset($sessionData[$id]);
if (sizeof($sessionData) === 0) {
self::session()->set(self::SESSION_VAR, $sessionData);
} else {
self::session()->remove(self::SESSION_VAR);
}
return $return;
}
return [];
} | {@inheritdoc} | https://github.com/cawaphp/module-clockwork/blob/a5f2a3f7811cb435bb4b22af6bb3a5712a1566d1/src/Storage/Session.php#L34-L52 |
cawaphp/module-clockwork | src/Storage/Session.php | Session.set | public function set(string $id, array $data)
{
$sessionData = self::session()->get(self::SESSION_VAR);
if (!$sessionData) {
$sessionData = [];
}
$sessionData[$id] = $data;
self::session()->set(self::SESSION_VAR, $sessionData);
} | php | public function set(string $id, array $data)
{
$sessionData = self::session()->get(self::SESSION_VAR);
if (!$sessionData) {
$sessionData = [];
}
$sessionData[$id] = $data;
self::session()->set(self::SESSION_VAR, $sessionData);
} | {@inheritdoc} | https://github.com/cawaphp/module-clockwork/blob/a5f2a3f7811cb435bb4b22af6bb3a5712a1566d1/src/Storage/Session.php#L57-L65 |
ZhukV/LanguageDetector | src/Ideea/LanguageDetector/Dictionary/PhpFileDictionary.php | PhpFileDictionary.getLanguagesByWord | public function getLanguagesByWord($word)
{
$this->loadDictionaries();
$word = mb_strtolower($word, mb_detect_encoding($word));
if (isset($this->words[$word])) {
return $this->words[$word];
}
return null;
} | php | public function getLanguagesByWord($word)
{
$this->loadDictionaries();
$word = mb_strtolower($word, mb_detect_encoding($word));
if (isset($this->words[$word])) {
return $this->words[$word];
}
return null;
} | {@inheritDoc} | https://github.com/ZhukV/LanguageDetector/blob/e5138f4c789e899801e098ce1e719337b015af7c/src/Ideea/LanguageDetector/Dictionary/PhpFileDictionary.php#L58-L69 |
ZhukV/LanguageDetector | src/Ideea/LanguageDetector/Dictionary/PhpFileDictionary.php | PhpFileDictionary.addWord | public function addWord($language, $word)
{
$this->loadDictionaries();
$word = mb_strtolower($word, mb_detect_encoding($word));
if (!isset($this->words[$word])) {
$this->words[$word] = array();
}
if (!in_array($language, $this->words[$word])) {
$this->words[$word][] = $language;
}
$this->updated[$language] = true;
return $this;
} | php | public function addWord($language, $word)
{
$this->loadDictionaries();
$word = mb_strtolower($word, mb_detect_encoding($word));
if (!isset($this->words[$word])) {
$this->words[$word] = array();
}
if (!in_array($language, $this->words[$word])) {
$this->words[$word][] = $language;
}
$this->updated[$language] = true;
return $this;
} | {@inheritDoc} | https://github.com/ZhukV/LanguageDetector/blob/e5138f4c789e899801e098ce1e719337b015af7c/src/Ideea/LanguageDetector/Dictionary/PhpFileDictionary.php#L74-L91 |
ZhukV/LanguageDetector | src/Ideea/LanguageDetector/Dictionary/PhpFileDictionary.php | PhpFileDictionary.removeWord | public function removeWord($language, $word)
{
$this->loadDictionaries();
$word = mb_strtolower($word, mb_detect_encoding($word));
if (isset($this->words[$word])) {
if (false !== $index = array_search($language, $this->words[$word])) {
unset ($this->words[$word][$index]);
}
}
} | php | public function removeWord($language, $word)
{
$this->loadDictionaries();
$word = mb_strtolower($word, mb_detect_encoding($word));
if (isset($this->words[$word])) {
if (false !== $index = array_search($language, $this->words[$word])) {
unset ($this->words[$word][$index]);
}
}
} | {@inheritDoc} | https://github.com/ZhukV/LanguageDetector/blob/e5138f4c789e899801e098ce1e719337b015af7c/src/Ideea/LanguageDetector/Dictionary/PhpFileDictionary.php#L96-L107 |
ZhukV/LanguageDetector | src/Ideea/LanguageDetector/Dictionary/PhpFileDictionary.php | PhpFileDictionary.flush | public function flush()
{
if (!count($this->updated)) {
// Not updated words
return;
}
foreach ($this->updated as $lang => $true) {
// Grouping all words by language
$words = array();
foreach ($this->words as $word => $wordLanguages) {
if (in_array($lang, $wordLanguages)) {
$words[] = $word;
}
}
$file = $this->dictionaryDir . '/' . $lang . '.php';
file_put_contents($file, '<?php return ' . var_export($words, 1) . ';');
}
} | php | public function flush()
{
if (!count($this->updated)) {
// Not updated words
return;
}
foreach ($this->updated as $lang => $true) {
// Grouping all words by language
$words = array();
foreach ($this->words as $word => $wordLanguages) {
if (in_array($lang, $wordLanguages)) {
$words[] = $word;
}
}
$file = $this->dictionaryDir . '/' . $lang . '.php';
file_put_contents($file, '<?php return ' . var_export($words, 1) . ';');
}
} | Flush updated dictionaries | https://github.com/ZhukV/LanguageDetector/blob/e5138f4c789e899801e098ce1e719337b015af7c/src/Ideea/LanguageDetector/Dictionary/PhpFileDictionary.php#L112-L132 |
ZhukV/LanguageDetector | src/Ideea/LanguageDetector/Dictionary/PhpFileDictionary.php | PhpFileDictionary.loadDictionaries | private function loadDictionaries()
{
if (null !== $this->words) {
// Dictionaries already loaded
return;
}
$this->words = array();
$dictionaryFiles = glob($this->dictionaryDir . '/*');
foreach ($dictionaryFiles as $dictionaryFile) {
$fileName = substr($dictionaryFile, strlen($this->dictionaryDir) + 1);
preg_match('/^(.+)\./', $fileName, $parts);
$lang = $parts[1];
$words = include $dictionaryFile;
foreach ($words as $word) {
if (!isset($this->words[$word])) {
$this->words[$word] = array();
}
if (!in_array($lang, $this->words[$word])) {
$this->words[$word][] = $lang;
}
}
}
} | php | private function loadDictionaries()
{
if (null !== $this->words) {
// Dictionaries already loaded
return;
}
$this->words = array();
$dictionaryFiles = glob($this->dictionaryDir . '/*');
foreach ($dictionaryFiles as $dictionaryFile) {
$fileName = substr($dictionaryFile, strlen($this->dictionaryDir) + 1);
preg_match('/^(.+)\./', $fileName, $parts);
$lang = $parts[1];
$words = include $dictionaryFile;
foreach ($words as $word) {
if (!isset($this->words[$word])) {
$this->words[$word] = array();
}
if (!in_array($lang, $this->words[$word])) {
$this->words[$word][] = $lang;
}
}
}
} | Load dictionaries from directory | https://github.com/ZhukV/LanguageDetector/blob/e5138f4c789e899801e098ce1e719337b015af7c/src/Ideea/LanguageDetector/Dictionary/PhpFileDictionary.php#L137-L166 |
pmdevelopment/tool-bundle | Command/FOSUserCommand.php | FOSUserCommand.executeChoice | private function executeChoice(SymfonyStyle $helper, $choice)
{
if (self::ACTION_PASSWORD_REPLACE === $choice) {
return $this->actionPasswordReplace($helper);
}
throw new \RuntimeException(sprintf('Unknown choice %s', $choice));
} | php | private function executeChoice(SymfonyStyle $helper, $choice)
{
if (self::ACTION_PASSWORD_REPLACE === $choice) {
return $this->actionPasswordReplace($helper);
}
throw new \RuntimeException(sprintf('Unknown choice %s', $choice));
} | Execute Choice
@param SymfonyStyle $helper
@param string $choice
@return null | https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Command/FOSUserCommand.php#L75-L82 |
pmdevelopment/tool-bundle | Command/FOSUserCommand.php | FOSUserCommand.actionPasswordReplace | private function actionPasswordReplace(SymfonyStyle $helper)
{
if (false === $helper->confirm('Are you sure? Only use this for development purposes!', false)) {
return null;
}
$userClass = $this->getUserEntityClass();
if (null === $userClass) {
throw new \RuntimeException('User entity not found');
}
$password = $helper->ask('New password', 'login123');
$userManager = $this->getContainer()->get('fos_user.user_manager');
/** @var User $user */
foreach ($this->getDoctrine()->getRepository($userClass)->findAll() as $user) {
$user->setPlainPassword($password);
$userManager->updateUser($user);
}
return null;
} | php | private function actionPasswordReplace(SymfonyStyle $helper)
{
if (false === $helper->confirm('Are you sure? Only use this for development purposes!', false)) {
return null;
}
$userClass = $this->getUserEntityClass();
if (null === $userClass) {
throw new \RuntimeException('User entity not found');
}
$password = $helper->ask('New password', 'login123');
$userManager = $this->getContainer()->get('fos_user.user_manager');
/** @var User $user */
foreach ($this->getDoctrine()->getRepository($userClass)->findAll() as $user) {
$user->setPlainPassword($password);
$userManager->updateUser($user);
}
return null;
} | Password Replace action
@param SymfonyStyle $helper
@return null | https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Command/FOSUserCommand.php#L91-L112 |
pmdevelopment/tool-bundle | Command/FOSUserCommand.php | FOSUserCommand.getUserEntityClass | private function getUserEntityClass()
{
/** @var ClassMetadata $meta */
foreach ($this->getDoctrine()->getManager()->getMetadataFactory()->getAllMetadata() as $meta) {
$reflectionClass = $meta->getReflectionClass();
if (true === $this->hasAbstractParent($reflectionClass, User::class)) {
return $meta->getName();
}
}
return null;
} | php | private function getUserEntityClass()
{
/** @var ClassMetadata $meta */
foreach ($this->getDoctrine()->getManager()->getMetadataFactory()->getAllMetadata() as $meta) {
$reflectionClass = $meta->getReflectionClass();
if (true === $this->hasAbstractParent($reflectionClass, User::class)) {
return $meta->getName();
}
}
return null;
} | Get User Entity Class
@return null|string | https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Command/FOSUserCommand.php#L119-L131 |
pmdevelopment/tool-bundle | Command/FOSUserCommand.php | FOSUserCommand.hasAbstractParent | private function hasAbstractParent($reflectionClass, $abstractClassName)
{
if (true === $reflectionClass->isAbstract() && $reflectionClass->getName() === $abstractClassName) {
return true;
}
if (false !== $reflectionClass->getParentClass()) {
return $this->hasAbstractParent($reflectionClass->getParentClass(), $abstractClassName);
}
return false;
} | php | private function hasAbstractParent($reflectionClass, $abstractClassName)
{
if (true === $reflectionClass->isAbstract() && $reflectionClass->getName() === $abstractClassName) {
return true;
}
if (false !== $reflectionClass->getParentClass()) {
return $this->hasAbstractParent($reflectionClass->getParentClass(), $abstractClassName);
}
return false;
} | @param ReflectionClass $reflectionClass
@param string $abstractClassName
@return bool | https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Command/FOSUserCommand.php#L139-L150 |
syzygypl/remote-media-bundle | src/DependencyInjection/Configuration.php | Configuration.getConfigTreeBuilder | public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$root = $treeBuilder->root('remote_media');
$cdnNode = $root->children()->arrayNode('cdn');
$cdnNode->isRequired();
$cdnNode->children()->scalarNode('media_url')->defaultNull();
$cdnNode->children()->scalarNode('cache_prefix')->defaultNull();
$cdnNode->children()->scalarNode('cache_provider')->defaultNull();
$s3 = $cdnNode->children()->arrayNode('s3');
$s3->isRequired();
$s3->children()->scalarNode('bucket')->isRequired();
$s3->children()->scalarNode('access_key')->isRequired();
$s3->children()->scalarNode('access_secret')->isRequired();
$s3->children()->scalarNode('region')->defaultValue('eu-west-1');
return $treeBuilder;
} | php | public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$root = $treeBuilder->root('remote_media');
$cdnNode = $root->children()->arrayNode('cdn');
$cdnNode->isRequired();
$cdnNode->children()->scalarNode('media_url')->defaultNull();
$cdnNode->children()->scalarNode('cache_prefix')->defaultNull();
$cdnNode->children()->scalarNode('cache_provider')->defaultNull();
$s3 = $cdnNode->children()->arrayNode('s3');
$s3->isRequired();
$s3->children()->scalarNode('bucket')->isRequired();
$s3->children()->scalarNode('access_key')->isRequired();
$s3->children()->scalarNode('access_secret')->isRequired();
$s3->children()->scalarNode('region')->defaultValue('eu-west-1');
return $treeBuilder;
} | {@inheritDoc} | https://github.com/syzygypl/remote-media-bundle/blob/2be3284d5baf8a12220ecbaf63043eb105eb87ef/src/DependencyInjection/Configuration.php#L19-L38 |
tarsana/syntax | src/OptionalSyntax.php | OptionalSyntax.parse | public function parse(string $text)
{
try {
$result = $this->syntax->parse($text);
$this->success = true;
} catch (ParseException $e) {
$result = $this->default;
$this->success = false;
}
return $result;
} | php | public function parse(string $text)
{
try {
$result = $this->syntax->parse($text);
$this->success = true;
} catch (ParseException $e) {
$result = $this->default;
$this->success = false;
}
return $result;
} | Tries to parse the string using the syntax and return
the result. If the parse failed, `success` flag is
set to false and the default value is returned.
@param string $text the string to parse
@return mixed | https://github.com/tarsana/syntax/blob/fd3f8a25e3be0e391c8fd486ccfcffe913ade534/src/OptionalSyntax.php#L110-L121 |
3ev/wordpress-core | src/Tev/Plugin/Loader.php | Loader.load | public function load($basePath)
{
$this->basePath = $basePath;
$this->renderer = new Renderer($this->getViewsPath());
return
$this
->loadCustomTables()
->loadPostTypes()
->loadFieldGroups()
->loadAcfJson()
->loadActions()
->loadShortCodes()
->loadOptionScreens()
->loadCliCommands();
} | php | public function load($basePath)
{
$this->basePath = $basePath;
$this->renderer = new Renderer($this->getViewsPath());
return
$this
->loadCustomTables()
->loadPostTypes()
->loadFieldGroups()
->loadAcfJson()
->loadActions()
->loadShortCodes()
->loadOptionScreens()
->loadCliCommands();
} | Load all plugin configuration.
@param string $basePath Plugin path
@return \Tev\Plugin\Loader This, for chaining | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Plugin/Loader.php#L96-L111 |
3ev/wordpress-core | src/Tev/Plugin/Loader.php | Loader.loadCustomTables | protected function loadCustomTables()
{
if ($config = $this->loadConfigFile('tables.php')) {
$app = $this->app;
foreach ($config as $installerClass) {
if (is_string($installerClass) && is_subclass_of($installerClass, 'Tev\Database\CustomTables\AbstractInstaller')) {
register_activation_hook($this->getPluginFile(), function () use ($installerClass, $app) {
global $wpdb;
$installer = new $installerClass($wpdb, $app);
$installer->install();
});
add_action('plugins_loaded', function () use ($installerClass, $app) {
global $wpdb;
$installer = new $installerClass($wpdb, $app);
$installer->update();
});
}
}
}
return $this;
} | php | protected function loadCustomTables()
{
if ($config = $this->loadConfigFile('tables.php')) {
$app = $this->app;
foreach ($config as $installerClass) {
if (is_string($installerClass) && is_subclass_of($installerClass, 'Tev\Database\CustomTables\AbstractInstaller')) {
register_activation_hook($this->getPluginFile(), function () use ($installerClass, $app) {
global $wpdb;
$installer = new $installerClass($wpdb, $app);
$installer->install();
});
add_action('plugins_loaded', function () use ($installerClass, $app) {
global $wpdb;
$installer = new $installerClass($wpdb, $app);
$installer->update();
});
}
}
}
return $this;
} | Load custom database table installers from configuration files.
@return \Tev\Plugin\Loader This, for chaining | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Plugin/Loader.php#L118-L141 |
3ev/wordpress-core | src/Tev/Plugin/Loader.php | Loader.loadPostTypes | protected function loadPostTypes()
{
if ($config = $this->loadConfigFile('post_types.php')) {
$callbacks = array();
// Create one callback for each post type, and register in
// init action
foreach ($config as $postTypeName => $args) {
$callbacks[] = $cb = function () use ($postTypeName, $args) {
register_post_type($postTypeName, $args);
};
add_action('init', $cb, 0);
}
// Flush URL caches for (you need to register custom post types
// first)
register_activation_hook($this->getPluginFile(), function () use ($callbacks) {
foreach ($callbacks as $cb) {
$cb();
}
flush_rewrite_rules();
});
}
return $this;
} | php | protected function loadPostTypes()
{
if ($config = $this->loadConfigFile('post_types.php')) {
$callbacks = array();
// Create one callback for each post type, and register in
// init action
foreach ($config as $postTypeName => $args) {
$callbacks[] = $cb = function () use ($postTypeName, $args) {
register_post_type($postTypeName, $args);
};
add_action('init', $cb, 0);
}
// Flush URL caches for (you need to register custom post types
// first)
register_activation_hook($this->getPluginFile(), function () use ($callbacks) {
foreach ($callbacks as $cb) {
$cb();
}
flush_rewrite_rules();
});
}
return $this;
} | Load custom post types from configuration files.
@return \Tev\Plugin\Loader This, for chaining | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Plugin/Loader.php#L148-L177 |
3ev/wordpress-core | src/Tev/Plugin/Loader.php | Loader.loadFieldGroups | protected function loadFieldGroups()
{
if (function_exists('register_field_group') && ($config = $this->loadConfigFile('field_groups.php'))) {
foreach ($config as $fieldGroupConfig) {
register_field_group($fieldGroupConfig);
}
}
return $this;
} | php | protected function loadFieldGroups()
{
if (function_exists('register_field_group') && ($config = $this->loadConfigFile('field_groups.php'))) {
foreach ($config as $fieldGroupConfig) {
register_field_group($fieldGroupConfig);
}
}
return $this;
} | Load custom field groups from configuration files.
@return \Tev\Plugin\Loader This, for chaining | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Plugin/Loader.php#L184-L193 |
3ev/wordpress-core | src/Tev/Plugin/Loader.php | Loader.loadActions | protected function loadActions()
{
if ($config = $this->loadConfigFile('actions.php')) {
$app = $this->app;
$renderer = $this->renderer;
foreach ($config as $actionName => $provider) {
if (is_string($provider) && is_subclass_of($provider, 'Tev\Plugin\Action\AbstractProvider')) {
$ap = new $provider($this->app, $this->renderer);
add_action($actionName, function () use ($ap) {
return call_user_func_array(array($ap, 'action'), func_get_args());
}, $ap->priority(), $ap->numArgs());
} elseif ($provider instanceof Closure) {
add_action($actionName, function () use ($provider)
{
return call_user_func($provider, func_get_args());
});
}
}
}
return $this;
} | php | protected function loadActions()
{
if ($config = $this->loadConfigFile('actions.php')) {
$app = $this->app;
$renderer = $this->renderer;
foreach ($config as $actionName => $provider) {
if (is_string($provider) && is_subclass_of($provider, 'Tev\Plugin\Action\AbstractProvider')) {
$ap = new $provider($this->app, $this->renderer);
add_action($actionName, function () use ($ap) {
return call_user_func_array(array($ap, 'action'), func_get_args());
}, $ap->priority(), $ap->numArgs());
} elseif ($provider instanceof Closure) {
add_action($actionName, function () use ($provider)
{
return call_user_func($provider, func_get_args());
});
}
}
}
return $this;
} | Load actions from configuration providers.
@return \Tev\Plugin\Loader This, for chaining | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Plugin/Loader.php#L200-L223 |
3ev/wordpress-core | src/Tev/Plugin/Loader.php | Loader.loadAcfJson | protected function loadAcfJson()
{
$config = $this->getConfigPath() . '/acf-json';
if (file_exists($config)) {
add_filter('acf/settings/load_json', function ($paths) use ($config) {
$paths[] = $config;
return $paths;
});
}
return $this;
} | php | protected function loadAcfJson()
{
$config = $this->getConfigPath() . '/acf-json';
if (file_exists($config)) {
add_filter('acf/settings/load_json', function ($paths) use ($config) {
$paths[] = $config;
return $paths;
});
}
return $this;
} | Load ACF JSON config if supplied.
@return \Tev\Plugin\Loader This, for chaining | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Plugin/Loader.php#L230-L242 |
3ev/wordpress-core | src/Tev/Plugin/Loader.php | Loader.loadShortCodes | protected function loadShortCodes()
{
if ($config = $this->loadConfigFile('shortcodes.php')) {
$renderer = $this->renderer;
$app = $this->app;
foreach ($config as $shortcode => $provider) {
add_shortcode($shortcode, function ($attrs, $content) use ($app, $provider, $renderer)
{
if (is_string($provider) && is_subclass_of($provider, 'Tev\Plugin\Shortcode\AbstractProvider')) {
$sp = new $provider($app, $renderer);
return $sp->shortcode($attrs, $content);
} elseif ($provider instanceof Closure) {
return $provider($attrs, $content, $renderer);
}
});
}
}
return $this;
} | php | protected function loadShortCodes()
{
if ($config = $this->loadConfigFile('shortcodes.php')) {
$renderer = $this->renderer;
$app = $this->app;
foreach ($config as $shortcode => $provider) {
add_shortcode($shortcode, function ($attrs, $content) use ($app, $provider, $renderer)
{
if (is_string($provider) && is_subclass_of($provider, 'Tev\Plugin\Shortcode\AbstractProvider')) {
$sp = new $provider($app, $renderer);
return $sp->shortcode($attrs, $content);
} elseif ($provider instanceof Closure) {
return $provider($attrs, $content, $renderer);
}
});
}
}
return $this;
} | Load shortcodes from configuration files.
@return \Tev\Plugin\Loader This, for chaining | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Plugin/Loader.php#L249-L269 |
3ev/wordpress-core | src/Tev/Plugin/Loader.php | Loader.loadOptionScreens | protected function loadOptionScreens()
{
if (function_exists('acf_add_options_page') && ($config = $this->loadConfigFile('option_screens.php'))) {
foreach ($config as $optionScreenConfig) {
acf_add_options_page($optionScreenConfig);
}
}
return $this;
} | php | protected function loadOptionScreens()
{
if (function_exists('acf_add_options_page') && ($config = $this->loadConfigFile('option_screens.php'))) {
foreach ($config as $optionScreenConfig) {
acf_add_options_page($optionScreenConfig);
}
}
return $this;
} | Load custom option screens from configuration files.
@return \Tev\Plugin\Loader This, for chaining | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Plugin/Loader.php#L276-L285 |
3ev/wordpress-core | src/Tev/Plugin/Loader.php | Loader.loadCliCommands | protected function loadCliCommands()
{
if (defined('WP_CLI') && WP_CLI && ($config = $this->loadConfigFile('commands.php'))) {
foreach ($config as $command => $className) {
\WP_CLI::add_command($command, $className);
}
}
return $this;
} | php | protected function loadCliCommands()
{
if (defined('WP_CLI') && WP_CLI && ($config = $this->loadConfigFile('commands.php'))) {
foreach ($config as $command => $className) {
\WP_CLI::add_command($command, $className);
}
}
return $this;
} | Load custom WP CLI commands from configuration files.
@return \Tev\Plugin\Loader This, for chaining | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Plugin/Loader.php#L292-L301 |
3ev/wordpress-core | src/Tev/Plugin/Loader.php | Loader.loadConfigFile | protected function loadConfigFile($file)
{
$path = $this->getConfigPath() . '/' . $file;
if (file_exists($path)) {
$config = include $path;
return is_array($config) ? $config : null;
}
return null;
} | php | protected function loadConfigFile($file)
{
$path = $this->getConfigPath() . '/' . $file;
if (file_exists($path)) {
$config = include $path;
return is_array($config) ? $config : null;
}
return null;
} | Load a config file from the config directory.
@param string $file Filename
@return array|null Array config or null if not found | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Plugin/Loader.php#L349-L359 |
AntonyThorpe/consumer | src/Consumer.php | Consumer.isTimestamp | public static function isTimestamp($string)
{
if (substr($string, 0, 5) == "/Date") {
return true;
}
try {
new DateTime('@' . $string);
} catch (Exception $e) {
return false;
}
return true;
} | php | public static function isTimestamp($string)
{
if (substr($string, 0, 5) == "/Date") {
return true;
}
try {
new DateTime('@' . $string);
} catch (Exception $e) {
return false;
}
return true;
} | Determine if the string is a Unix Timestamp
@link(Stack Overflow, http://stackoverflow.com/questions/2524680/check-whether-the-string-is-a-unix-timestamp)
@param string $string
@return boolean | https://github.com/AntonyThorpe/consumer/blob/c9f464b901c09ab0bfbb62c94589637363af7bf0/src/Consumer.php#L49-L61 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.