repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
ekino/EkinoWordpressBundle | Twig/Extension/PostExtension.php | PostExtension.isPostPasswordRequired | public function isPostPasswordRequired(array $context, Post $post)
{
if (null === $this->cookieHash) {
$this->cookieHash = '';
if ($siteUrlOption = $this->optionExtension->getOption('siteurl')) {
$this->cookieHash = md5($siteUrlOption->getValue());
}
}
return $this->postManager->isPasswordRequired($post, $context['app']->getRequest(), $this->cookieHash);
} | php | public function isPostPasswordRequired(array $context, Post $post)
{
if (null === $this->cookieHash) {
$this->cookieHash = '';
if ($siteUrlOption = $this->optionExtension->getOption('siteurl')) {
$this->cookieHash = md5($siteUrlOption->getValue());
}
}
return $this->postManager->isPasswordRequired($post, $context['app']->getRequest(), $this->cookieHash);
} | [
"public",
"function",
"isPostPasswordRequired",
"(",
"array",
"$",
"context",
",",
"Post",
"$",
"post",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"cookieHash",
")",
"{",
"$",
"this",
"->",
"cookieHash",
"=",
"''",
";",
"if",
"(",
"$",
"s... | @param array $context
@param Post $post
@return bool | [
"@param",
"array",
"$context",
"@param",
"Post",
"$post"
] | train | https://github.com/ekino/EkinoWordpressBundle/blob/bf3f4cac10d62d7b57ebf1fb6a5cef1780752bb8/Twig/Extension/PostExtension.php#L126-L137 |
ekino/EkinoWordpressBundle | Wordpress/Wordpress.php | Wordpress.loadWordpress | public function loadWordpress()
{
if (!$this->alreadyInitialized) {
foreach ($this->globals as $globalVariable) {
global ${$globalVariable};
}
$loader = $this->getWordpressDirectory().'wp-blog-header.php';
if (!file_exists($loader)) {
throw new \InvalidArgumentException(
sprintf('Unable to find Wordpress loader in: "%s".', $loader)
);
}
require_once $loader;
$this->alreadyInitialized = true;
}
} | php | public function loadWordpress()
{
if (!$this->alreadyInitialized) {
foreach ($this->globals as $globalVariable) {
global ${$globalVariable};
}
$loader = $this->getWordpressDirectory().'wp-blog-header.php';
if (!file_exists($loader)) {
throw new \InvalidArgumentException(
sprintf('Unable to find Wordpress loader in: "%s".', $loader)
);
}
require_once $loader;
$this->alreadyInitialized = true;
}
} | [
"public",
"function",
"loadWordpress",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"alreadyInitialized",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"globals",
"as",
"$",
"globalVariable",
")",
"{",
"global",
"$",
"{",
"$",
"globalVariable",
"}",
... | Loads Wordpress. | [
"Loads",
"Wordpress",
"."
] | train | https://github.com/ekino/EkinoWordpressBundle/blob/bf3f4cac10d62d7b57ebf1fb6a5cef1780752bb8/Wordpress/Wordpress.php#L87-L106 |
ekino/EkinoWordpressBundle | Model/User.php | User.setRoles | public function setRoles($roles)
{
if (!is_array($roles)) {
$roles = [$roles];
}
$this->roles = $roles;
return $this;
} | php | public function setRoles($roles)
{
if (!is_array($roles)) {
$roles = [$roles];
}
$this->roles = $roles;
return $this;
} | [
"public",
"function",
"setRoles",
"(",
"$",
"roles",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"roles",
")",
")",
"{",
"$",
"roles",
"=",
"[",
"$",
"roles",
"]",
";",
"}",
"$",
"this",
"->",
"roles",
"=",
"$",
"roles",
";",
"return",
"$",... | Sets user roles.
@param array|string $roles
@return User | [
"Sets",
"user",
"roles",
"."
] | train | https://github.com/ekino/EkinoWordpressBundle/blob/bf3f4cac10d62d7b57ebf1fb6a5cef1780752bb8/Model/User.php#L326-L335 |
ekino/EkinoWordpressBundle | Model/User.php | User.setWordpressRoles | public function setWordpressRoles(array $roles, $prefix = 'ROLE_WP_')
{
foreach ($roles as $key => $role) {
$roles[$key] = $prefix.strtoupper($role);
}
$this->setRoles($roles);
return $this;
} | php | public function setWordpressRoles(array $roles, $prefix = 'ROLE_WP_')
{
foreach ($roles as $key => $role) {
$roles[$key] = $prefix.strtoupper($role);
}
$this->setRoles($roles);
return $this;
} | [
"public",
"function",
"setWordpressRoles",
"(",
"array",
"$",
"roles",
",",
"$",
"prefix",
"=",
"'ROLE_WP_'",
")",
"{",
"foreach",
"(",
"$",
"roles",
"as",
"$",
"key",
"=>",
"$",
"role",
")",
"{",
"$",
"roles",
"[",
"$",
"key",
"]",
"=",
"$",
"pref... | Sets Wordpress user roles by prefixing them.
@param array $roles An array of roles
@param string $prefix A role prefix
@return User | [
"Sets",
"Wordpress",
"user",
"roles",
"by",
"prefixing",
"them",
"."
] | train | https://github.com/ekino/EkinoWordpressBundle/blob/bf3f4cac10d62d7b57ebf1fb6a5cef1780752bb8/Model/User.php#L345-L354 |
ekino/EkinoWordpressBundle | DependencyInjection/EkinoWordpressExtension.php | EkinoWordpressExtension.load | public function load(array $configs, ContainerBuilder $container)
{
$config = $this->processConfiguration(new Configuration(), $configs);
$container->setParameter('ekino.wordpress.install_directory', $config['wordpress_directory'] ?: $container->getParameter('kernel.root_dir').'/../../');
$this->loadWordpressGlobals($container, $config['globals']);
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('manager.xml');
$loader->load('services.xml');
$loader->load('hooks.xml');
$container->setParameter('ekino.wordpress.repositories', $config['services']);
$this->loadEntities($container, $config['services']);
$this->loadManagers($container, $config['services']);
if (isset($config['table_prefix'])) {
$this->loadTablePrefix($container, $config['table_prefix']);
}
if (isset($config['entity_manager'])) {
$this->loadEntityManager($container, $config['entity_manager']);
}
if ($config['load_twig_extension']) {
$loader->load('twig.xml');
}
if ($config['i18n_cookie_name']) {
$container->setParameter('ekino.wordpress.i18n_cookie_name', $config['i18n_cookie_name']);
$loader->load('i18n.xml');
}
if ($config['enable_wordpress_listener']) {
$loader->load('listener.xml');
}
$container->setParameter('ekino.wordpress.cookie_hash', $config['cookie_hash']);
$container->setParameter('ekino.wordpress.firewall_name', $config['security']['firewall_name']);
$container->setParameter('ekino.wordpress.login_url', $config['security']['login_url']);
$container->setParameter($this->getAlias().'.backend_type_orm', true);
} | php | public function load(array $configs, ContainerBuilder $container)
{
$config = $this->processConfiguration(new Configuration(), $configs);
$container->setParameter('ekino.wordpress.install_directory', $config['wordpress_directory'] ?: $container->getParameter('kernel.root_dir').'/../../');
$this->loadWordpressGlobals($container, $config['globals']);
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('manager.xml');
$loader->load('services.xml');
$loader->load('hooks.xml');
$container->setParameter('ekino.wordpress.repositories', $config['services']);
$this->loadEntities($container, $config['services']);
$this->loadManagers($container, $config['services']);
if (isset($config['table_prefix'])) {
$this->loadTablePrefix($container, $config['table_prefix']);
}
if (isset($config['entity_manager'])) {
$this->loadEntityManager($container, $config['entity_manager']);
}
if ($config['load_twig_extension']) {
$loader->load('twig.xml');
}
if ($config['i18n_cookie_name']) {
$container->setParameter('ekino.wordpress.i18n_cookie_name', $config['i18n_cookie_name']);
$loader->load('i18n.xml');
}
if ($config['enable_wordpress_listener']) {
$loader->load('listener.xml');
}
$container->setParameter('ekino.wordpress.cookie_hash', $config['cookie_hash']);
$container->setParameter('ekino.wordpress.firewall_name', $config['security']['firewall_name']);
$container->setParameter('ekino.wordpress.login_url', $config['security']['login_url']);
$container->setParameter($this->getAlias().'.backend_type_orm', true);
} | [
"public",
"function",
"load",
"(",
"array",
"$",
"configs",
",",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"processConfiguration",
"(",
"new",
"Configuration",
"(",
")",
",",
"$",
"configs",
")",
";",
"$",
"co... | Loads configuration.
@param array $configs A configuration array
@param ContainerBuilder $container Symfony container builder | [
"Loads",
"configuration",
"."
] | train | https://github.com/ekino/EkinoWordpressBundle/blob/bf3f4cac10d62d7b57ebf1fb6a5cef1780752bb8/DependencyInjection/EkinoWordpressExtension.php#L52-L93 |
ekino/EkinoWordpressBundle | DependencyInjection/EkinoWordpressExtension.php | EkinoWordpressExtension.loadTablePrefix | protected function loadTablePrefix(ContainerBuilder $container, $prefix)
{
$identifier = 'ekino.wordpress.subscriber.table_prefix_subscriber';
$serviceDefinition = $container->getDefinition($identifier);
$serviceDefinition->setArguments([$prefix]);
$container->setDefinition($identifier, $serviceDefinition);
} | php | protected function loadTablePrefix(ContainerBuilder $container, $prefix)
{
$identifier = 'ekino.wordpress.subscriber.table_prefix_subscriber';
$serviceDefinition = $container->getDefinition($identifier);
$serviceDefinition->setArguments([$prefix]);
$container->setDefinition($identifier, $serviceDefinition);
} | [
"protected",
"function",
"loadTablePrefix",
"(",
"ContainerBuilder",
"$",
"container",
",",
"$",
"prefix",
")",
"{",
"$",
"identifier",
"=",
"'ekino.wordpress.subscriber.table_prefix_subscriber'",
";",
"$",
"serviceDefinition",
"=",
"$",
"container",
"->",
"getDefinitio... | Loads table prefix from configuration to doctrine table prefix subscriber event.
@param ContainerBuilder $container Symfony dependency injection container
@param string $prefix Wordpress table prefix | [
"Loads",
"table",
"prefix",
"from",
"configuration",
"to",
"doctrine",
"table",
"prefix",
"subscriber",
"event",
"."
] | train | https://github.com/ekino/EkinoWordpressBundle/blob/bf3f4cac10d62d7b57ebf1fb6a5cef1780752bb8/DependencyInjection/EkinoWordpressExtension.php#L123-L131 |
ekino/EkinoWordpressBundle | DependencyInjection/EkinoWordpressExtension.php | EkinoWordpressExtension.loadEntityManager | protected function loadEntityManager(ContainerBuilder $container, $em)
{
$container->setParameter('ekino_wordpress.model_manager_name', $em);
$reference = new Reference(sprintf('doctrine.orm.%s_entity_manager', $em));
foreach (static::$entities as $entityName) {
$container->findDefinition(sprintf('ekino.wordpress.manager.%s', $entityName))->replaceArgument(0, $reference);
}
} | php | protected function loadEntityManager(ContainerBuilder $container, $em)
{
$container->setParameter('ekino_wordpress.model_manager_name', $em);
$reference = new Reference(sprintf('doctrine.orm.%s_entity_manager', $em));
foreach (static::$entities as $entityName) {
$container->findDefinition(sprintf('ekino.wordpress.manager.%s', $entityName))->replaceArgument(0, $reference);
}
} | [
"protected",
"function",
"loadEntityManager",
"(",
"ContainerBuilder",
"$",
"container",
",",
"$",
"em",
")",
"{",
"$",
"container",
"->",
"setParameter",
"(",
"'ekino_wordpress.model_manager_name'",
",",
"$",
"em",
")",
";",
"$",
"reference",
"=",
"new",
"Refer... | Sets Doctrine entity manager for Wordpress.
@param ContainerBuilder $container
@param EntityManagerInterface $em | [
"Sets",
"Doctrine",
"entity",
"manager",
"for",
"Wordpress",
"."
] | train | https://github.com/ekino/EkinoWordpressBundle/blob/bf3f4cac10d62d7b57ebf1fb6a5cef1780752bb8/DependencyInjection/EkinoWordpressExtension.php#L139-L148 |
ekino/EkinoWordpressBundle | DependencyInjection/EkinoWordpressExtension.php | EkinoWordpressExtension.loadWordpressGlobals | protected function loadWordpressGlobals(ContainerBuilder $container, $globals)
{
$coreGlobals = ['wp', 'wp_the_query', 'wpdb', 'wp_query', 'allowedentitynames'];
$globals = array_merge($globals, $coreGlobals);
$container->setParameter('ekino.wordpress.globals', $globals);
} | php | protected function loadWordpressGlobals(ContainerBuilder $container, $globals)
{
$coreGlobals = ['wp', 'wp_the_query', 'wpdb', 'wp_query', 'allowedentitynames'];
$globals = array_merge($globals, $coreGlobals);
$container->setParameter('ekino.wordpress.globals', $globals);
} | [
"protected",
"function",
"loadWordpressGlobals",
"(",
"ContainerBuilder",
"$",
"container",
",",
"$",
"globals",
")",
"{",
"$",
"coreGlobals",
"=",
"[",
"'wp'",
",",
"'wp_the_query'",
",",
"'wpdb'",
",",
"'wp_query'",
",",
"'allowedentitynames'",
"]",
";",
"$",
... | Sets global variables array to load.
@param ContainerBuilder $container
@param array $globals | [
"Sets",
"global",
"variables",
"array",
"to",
"load",
"."
] | train | https://github.com/ekino/EkinoWordpressBundle/blob/bf3f4cac10d62d7b57ebf1fb6a5cef1780752bb8/DependencyInjection/EkinoWordpressExtension.php#L156-L162 |
ekino/EkinoWordpressBundle | Listener/WordpressRequestListener.php | WordpressRequestListener.onKernelRequest | public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
// Loads Wordpress source code in order to allow use of WordPress functions in Symfony.
if ('ekino_wordpress_catchall' !== $request->attributes->get('_route')) {
$this->wordpress->loadWordpress();
}
$this->checkAuthentication($request);
} | php | public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
// Loads Wordpress source code in order to allow use of WordPress functions in Symfony.
if ('ekino_wordpress_catchall' !== $request->attributes->get('_route')) {
$this->wordpress->loadWordpress();
}
$this->checkAuthentication($request);
} | [
"public",
"function",
"onKernelRequest",
"(",
"GetResponseEvent",
"$",
"event",
")",
"{",
"$",
"request",
"=",
"$",
"event",
"->",
"getRequest",
"(",
")",
";",
"// Loads Wordpress source code in order to allow use of WordPress functions in Symfony.",
"if",
"(",
"'ekino_wo... | On kernel request method.
@param GetResponseEvent $event | [
"On",
"kernel",
"request",
"method",
"."
] | train | https://github.com/ekino/EkinoWordpressBundle/blob/bf3f4cac10d62d7b57ebf1fb6a5cef1780752bb8/Listener/WordpressRequestListener.php#L54-L64 |
ekino/EkinoWordpressBundle | Listener/WordpressRequestListener.php | WordpressRequestListener.checkAuthentication | protected function checkAuthentication(Request $request)
{
if (!$request->hasPreviousSession()) {
return;
}
$session = $request->getSession();
if ($session->has('token')) {
$token = $session->get('token');
$this->tokenStorage->setToken($token);
}
} | php | protected function checkAuthentication(Request $request)
{
if (!$request->hasPreviousSession()) {
return;
}
$session = $request->getSession();
if ($session->has('token')) {
$token = $session->get('token');
$this->tokenStorage->setToken($token);
}
} | [
"protected",
"function",
"checkAuthentication",
"(",
"Request",
"$",
"request",
")",
"{",
"if",
"(",
"!",
"$",
"request",
"->",
"hasPreviousSession",
"(",
")",
")",
"{",
"return",
";",
"}",
"$",
"session",
"=",
"$",
"request",
"->",
"getSession",
"(",
")... | Checks if a Wordpress user is authenticated and authenticate him into Symfony security context.
@param Request $request | [
"Checks",
"if",
"a",
"Wordpress",
"user",
"is",
"authenticated",
"and",
"authenticate",
"him",
"into",
"Symfony",
"security",
"context",
"."
] | train | https://github.com/ekino/EkinoWordpressBundle/blob/bf3f4cac10d62d7b57ebf1fb6a5cef1780752bb8/Listener/WordpressRequestListener.php#L71-L83 |
ekino/EkinoWordpressBundle | Event/Subscriber/LoadMetadataSubscriber.php | LoadMetadataSubscriber.toEntity | private function toEntity(ClassMetadataInfo $metadata)
{
foreach ($this->classes as $name => $class) {
if (!is_array($class) || $class['class'] != $metadata->getName()) {
continue;
}
if (isset($class['class'])) {
$metadata->isMappedSuperclass = false;
}
if (isset($class['repository_class'])) {
$metadata->setCustomRepositoryClass($class['repository_class']);
}
}
} | php | private function toEntity(ClassMetadataInfo $metadata)
{
foreach ($this->classes as $name => $class) {
if (!is_array($class) || $class['class'] != $metadata->getName()) {
continue;
}
if (isset($class['class'])) {
$metadata->isMappedSuperclass = false;
}
if (isset($class['repository_class'])) {
$metadata->setCustomRepositoryClass($class['repository_class']);
}
}
} | [
"private",
"function",
"toEntity",
"(",
"ClassMetadataInfo",
"$",
"metadata",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"classes",
"as",
"$",
"name",
"=>",
"$",
"class",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"class",
")",
"||",
"$",
"cla... | Transform a mapped superclass into entity if needed.
@param ClassMetadataInfo $metadata | [
"Transform",
"a",
"mapped",
"superclass",
"into",
"entity",
"if",
"needed",
"."
] | train | https://github.com/ekino/EkinoWordpressBundle/blob/bf3f4cac10d62d7b57ebf1fb6a5cef1780752bb8/Event/Subscriber/LoadMetadataSubscriber.php#L68-L83 |
ekino/EkinoWordpressBundle | Twig/Extension/TermTaxonomyExtension.php | TermTaxonomyExtension.getTermLink | public function getTermLink(TermTaxonomy $termTaxonomy, $type = 'category')
{
$prefix = ($prefix = $this->optionManager->findOneByOptionName($type.'_base')) ? $prefix->getValue() : null;
$output = [$termTaxonomy->getTerm()->getSlug()];
while ($parent = $termTaxonomy->getParent()) {
$output[] = $parent->getTerm()->getSlug();
$termTaxonomy = $parent;
}
return ($prefix ? $prefix : '').'/'.implode('/', array_reverse($output)).(count($output) ? '/' : '');
} | php | public function getTermLink(TermTaxonomy $termTaxonomy, $type = 'category')
{
$prefix = ($prefix = $this->optionManager->findOneByOptionName($type.'_base')) ? $prefix->getValue() : null;
$output = [$termTaxonomy->getTerm()->getSlug()];
while ($parent = $termTaxonomy->getParent()) {
$output[] = $parent->getTerm()->getSlug();
$termTaxonomy = $parent;
}
return ($prefix ? $prefix : '').'/'.implode('/', array_reverse($output)).(count($output) ? '/' : '');
} | [
"public",
"function",
"getTermLink",
"(",
"TermTaxonomy",
"$",
"termTaxonomy",
",",
"$",
"type",
"=",
"'category'",
")",
"{",
"$",
"prefix",
"=",
"(",
"$",
"prefix",
"=",
"$",
"this",
"->",
"optionManager",
"->",
"findOneByOptionName",
"(",
"$",
"type",
".... | @param TermTaxonomy $termTaxonomy A term taxonomy instance
@param string $type The link type. Can be "category" or "tag"
@return string | [
"@param",
"TermTaxonomy",
"$termTaxonomy",
"A",
"term",
"taxonomy",
"instance",
"@param",
"string",
"$type",
"The",
"link",
"type",
".",
"Can",
"be",
"category",
"or",
"tag"
] | train | https://github.com/ekino/EkinoWordpressBundle/blob/bf3f4cac10d62d7b57ebf1fb6a5cef1780752bb8/Twig/Extension/TermTaxonomyExtension.php#L54-L65 |
ekino/EkinoWordpressBundle | Manager/PostManager.php | PostManager.isPasswordRequired | public function isPasswordRequired(Post $post, Request $request, $cookieHash)
{
if (!$post->getPassword()) {
return false;
}
$cookies = $request->cookies;
if (!$cookies->has('wp-postpass_'.$cookieHash)) {
return true;
}
$hash = stripslashes($cookies->get('wp-postpass_'.$cookieHash));
if (0 !== strpos($hash, '$P$B')) {
return true;
}
$wpHasher = new PasswordHash(8, true);
return !$wpHasher->CheckPassword($post->getPassword(), $hash);
} | php | public function isPasswordRequired(Post $post, Request $request, $cookieHash)
{
if (!$post->getPassword()) {
return false;
}
$cookies = $request->cookies;
if (!$cookies->has('wp-postpass_'.$cookieHash)) {
return true;
}
$hash = stripslashes($cookies->get('wp-postpass_'.$cookieHash));
if (0 !== strpos($hash, '$P$B')) {
return true;
}
$wpHasher = new PasswordHash(8, true);
return !$wpHasher->CheckPassword($post->getPassword(), $hash);
} | [
"public",
"function",
"isPasswordRequired",
"(",
"Post",
"$",
"post",
",",
"Request",
"$",
"request",
",",
"$",
"cookieHash",
")",
"{",
"if",
"(",
"!",
"$",
"post",
"->",
"getPassword",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"cookies",
... | @param Post $post
@param Request $request
@param string $cookieHash
@return bool | [
"@param",
"Post",
"$post",
"@param",
"Request",
"$request",
"@param",
"string",
"$cookieHash"
] | train | https://github.com/ekino/EkinoWordpressBundle/blob/bf3f4cac10d62d7b57ebf1fb6a5cef1780752bb8/Manager/PostManager.php#L77-L98 |
ekino/EkinoWordpressBundle | Manager/PostManager.php | PostManager.getThumbnailPath | public function getThumbnailPath(Post $post)
{
if (!$thumbnailPostMeta = $this->postMetaManager->getThumbnailPostId($post)) {
return '';
}
/** @var $post Post */
if (!$post = $this->find($thumbnailPostMeta->getValue())) {
return '';
}
return $post->getGuid();
} | php | public function getThumbnailPath(Post $post)
{
if (!$thumbnailPostMeta = $this->postMetaManager->getThumbnailPostId($post)) {
return '';
}
/** @var $post Post */
if (!$post = $this->find($thumbnailPostMeta->getValue())) {
return '';
}
return $post->getGuid();
} | [
"public",
"function",
"getThumbnailPath",
"(",
"Post",
"$",
"post",
")",
"{",
"if",
"(",
"!",
"$",
"thumbnailPostMeta",
"=",
"$",
"this",
"->",
"postMetaManager",
"->",
"getThumbnailPostId",
"(",
"$",
"post",
")",
")",
"{",
"return",
"''",
";",
"}",
"/**... | @param Post $post
@return string | [
"@param",
"Post",
"$post"
] | train | https://github.com/ekino/EkinoWordpressBundle/blob/bf3f4cac10d62d7b57ebf1fb6a5cef1780752bb8/Manager/PostManager.php#L105-L117 |
ekino/EkinoWordpressBundle | Manager/PostManager.php | PostManager.findByDate | public function findByDate(\DateTime $date = null)
{
$date = $date ?: new \DateTime();
return $this->repository->findByDate($date);
} | php | public function findByDate(\DateTime $date = null)
{
$date = $date ?: new \DateTime();
return $this->repository->findByDate($date);
} | [
"public",
"function",
"findByDate",
"(",
"\\",
"DateTime",
"$",
"date",
"=",
"null",
")",
"{",
"$",
"date",
"=",
"$",
"date",
"?",
":",
"new",
"\\",
"DateTime",
"(",
")",
";",
"return",
"$",
"this",
"->",
"repository",
"->",
"findByDate",
"(",
"$",
... | Returns posts for current date or a specified date.
@param \DateTime|null $date
@return array | [
"Returns",
"posts",
"for",
"current",
"date",
"or",
"a",
"specified",
"date",
"."
] | train | https://github.com/ekino/EkinoWordpressBundle/blob/bf3f4cac10d62d7b57ebf1fb6a5cef1780752bb8/Manager/PostManager.php#L126-L131 |
ekino/EkinoWordpressBundle | DependencyInjection/Configuration.php | Configuration.getConfigTreeBuilder | public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('ekino_wordpress');
$rootNode
->children()
->scalarNode('table_prefix')->end()
->scalarNode('wordpress_directory')->defaultNull()->end()
->scalarNode('entity_manager')->end()
->booleanNode('load_twig_extension')->defaultFalse()->end()
->booleanNode('cookie_hash')->defaultNull()->end()
->scalarNode('i18n_cookie_name')->defaultFalse()->end()
->booleanNode('enable_wordpress_listener')->defaultTrue()->end()
->arrayNode('globals')
->prototype('scalar')->defaultValue([])->end()
->end()
->arrayNode('security')
->addDefaultsIfNotSet()
->children()
->scalarNode('firewall_name')->defaultValue('secured_area')->end()
->scalarNode('login_url')->defaultValue('/wp-login.php')->end()
->end()
->end()
->end();
$this->addServicesSection($rootNode);
return $treeBuilder;
} | php | public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('ekino_wordpress');
$rootNode
->children()
->scalarNode('table_prefix')->end()
->scalarNode('wordpress_directory')->defaultNull()->end()
->scalarNode('entity_manager')->end()
->booleanNode('load_twig_extension')->defaultFalse()->end()
->booleanNode('cookie_hash')->defaultNull()->end()
->scalarNode('i18n_cookie_name')->defaultFalse()->end()
->booleanNode('enable_wordpress_listener')->defaultTrue()->end()
->arrayNode('globals')
->prototype('scalar')->defaultValue([])->end()
->end()
->arrayNode('security')
->addDefaultsIfNotSet()
->children()
->scalarNode('firewall_name')->defaultValue('secured_area')->end()
->scalarNode('login_url')->defaultValue('/wp-login.php')->end()
->end()
->end()
->end();
$this->addServicesSection($rootNode);
return $treeBuilder;
} | [
"public",
"function",
"getConfigTreeBuilder",
"(",
")",
"{",
"$",
"treeBuilder",
"=",
"new",
"TreeBuilder",
"(",
")",
";",
"$",
"rootNode",
"=",
"$",
"treeBuilder",
"->",
"root",
"(",
"'ekino_wordpress'",
")",
";",
"$",
"rootNode",
"->",
"children",
"(",
"... | Builds configuration tree.
@return \Symfony\Component\Config\Definition\Builder\TreeBuilder A tree builder instance | [
"Builds",
"configuration",
"tree",
"."
] | train | https://github.com/ekino/EkinoWordpressBundle/blob/bf3f4cac10d62d7b57ebf1fb6a5cef1780752bb8/DependencyInjection/Configuration.php#L31-L62 |
ekino/EkinoWordpressBundle | Model/TermTaxonomy.php | TermTaxonomy.addRelationship | public function addRelationship(TermRelationships $relationship)
{
if (!$this->relationships->contains($relationship)) {
$this->relationships[] = $relationship;
}
return $this;
} | php | public function addRelationship(TermRelationships $relationship)
{
if (!$this->relationships->contains($relationship)) {
$this->relationships[] = $relationship;
}
return $this;
} | [
"public",
"function",
"addRelationship",
"(",
"TermRelationships",
"$",
"relationship",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"relationships",
"->",
"contains",
"(",
"$",
"relationship",
")",
")",
"{",
"$",
"this",
"->",
"relationships",
"[",
"]",
"... | @param TermRelationships $relationship
@return Term | [
"@param",
"TermRelationships",
"$relationship"
] | train | https://github.com/ekino/EkinoWordpressBundle/blob/bf3f4cac10d62d7b57ebf1fb6a5cef1780752bb8/Model/TermTaxonomy.php#L188-L195 |
ekino/EkinoWordpressBundle | Model/TermTaxonomy.php | TermTaxonomy.removeRelationship | public function removeRelationship(TermRelationships $relationship)
{
if ($this->relationships->contains($relationship)) {
$this->relationships->remove($relationship);
}
return $this;
} | php | public function removeRelationship(TermRelationships $relationship)
{
if ($this->relationships->contains($relationship)) {
$this->relationships->remove($relationship);
}
return $this;
} | [
"public",
"function",
"removeRelationship",
"(",
"TermRelationships",
"$",
"relationship",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"relationships",
"->",
"contains",
"(",
"$",
"relationship",
")",
")",
"{",
"$",
"this",
"->",
"relationships",
"->",
"remove",
... | @param TermRelationships $relationship
@return Term | [
"@param",
"TermRelationships",
"$relationship"
] | train | https://github.com/ekino/EkinoWordpressBundle/blob/bf3f4cac10d62d7b57ebf1fb6a5cef1780752bb8/Model/TermTaxonomy.php#L202-L209 |
ekino/EkinoWordpressBundle | Manager/OptionManager.php | OptionManager.isActiveSidebar | public function isActiveSidebar($sidebarName)
{
if (!$sidebarOption = $this->findOneByOptionName('sidebars_widgets')) {
return false;
}
if (false === ($sidebarOption = unserialize($sidebarOption->getValue()))) {
return false;
}
return isset($sidebarOption[$sidebarName]);
} | php | public function isActiveSidebar($sidebarName)
{
if (!$sidebarOption = $this->findOneByOptionName('sidebars_widgets')) {
return false;
}
if (false === ($sidebarOption = unserialize($sidebarOption->getValue()))) {
return false;
}
return isset($sidebarOption[$sidebarName]);
} | [
"public",
"function",
"isActiveSidebar",
"(",
"$",
"sidebarName",
")",
"{",
"if",
"(",
"!",
"$",
"sidebarOption",
"=",
"$",
"this",
"->",
"findOneByOptionName",
"(",
"'sidebars_widgets'",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"false",
"===... | @param string $sidebarName
@return bool | [
"@param",
"string",
"$sidebarName"
] | train | https://github.com/ekino/EkinoWordpressBundle/blob/bf3f4cac10d62d7b57ebf1fb6a5cef1780752bb8/Manager/OptionManager.php#L37-L48 |
ekino/EkinoWordpressBundle | Manager/PostMetaManager.php | PostMetaManager.getPostMeta | public function getPostMeta($postId, $metaName, $fetchOneResult = false)
{
$query = $this->repository->getPostMetaQuery($postId, $metaName);
return $fetchOneResult ? $query->getOneOrNullResult() : $query->getResult();
} | php | public function getPostMeta($postId, $metaName, $fetchOneResult = false)
{
$query = $this->repository->getPostMetaQuery($postId, $metaName);
return $fetchOneResult ? $query->getOneOrNullResult() : $query->getResult();
} | [
"public",
"function",
"getPostMeta",
"(",
"$",
"postId",
",",
"$",
"metaName",
",",
"$",
"fetchOneResult",
"=",
"false",
")",
"{",
"$",
"query",
"=",
"$",
"this",
"->",
"repository",
"->",
"getPostMetaQuery",
"(",
"$",
"postId",
",",
"$",
"metaName",
")"... | @param int $postId A post identifier
@param string $metaName A meta name
@param bool $fetchOneResult Use fetchOneOrNullResult() method instead of getResult()?
@return array|\Ekino\WordpressBundle\Entity\PostMeta | [
"@param",
"int",
"$postId",
"A",
"post",
"identifier",
"@param",
"string",
"$metaName",
"A",
"meta",
"name",
"@param",
"bool",
"$fetchOneResult",
"Use",
"fetchOneOrNullResult",
"()",
"method",
"instead",
"of",
"getResult",
"()",
"?"
] | train | https://github.com/ekino/EkinoWordpressBundle/blob/bf3f4cac10d62d7b57ebf1fb6a5cef1780752bb8/Manager/PostMetaManager.php#L38-L43 |
peppeocchi/php-cron-scheduler | src/GO/Scheduler.php | Scheduler.prioritiseJobs | private function prioritiseJobs()
{
$background = [];
$foreground = [];
foreach ($this->jobs as $job) {
if ($job->canRunInBackground()) {
$background[] = $job;
} else {
$foreground[] = $job;
}
}
return array_merge($background, $foreground);
} | php | private function prioritiseJobs()
{
$background = [];
$foreground = [];
foreach ($this->jobs as $job) {
if ($job->canRunInBackground()) {
$background[] = $job;
} else {
$foreground[] = $job;
}
}
return array_merge($background, $foreground);
} | [
"private",
"function",
"prioritiseJobs",
"(",
")",
"{",
"$",
"background",
"=",
"[",
"]",
";",
"$",
"foreground",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"jobs",
"as",
"$",
"job",
")",
"{",
"if",
"(",
"$",
"job",
"->",
"canRunInBackg... | Prioritise jobs in background.
@return array | [
"Prioritise",
"jobs",
"in",
"background",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Scheduler.php#L68-L82 |
peppeocchi/php-cron-scheduler | src/GO/Scheduler.php | Scheduler.php | public function php($script, $bin = null, $args = [], $id = null)
{
if (! is_string($script)) {
throw new InvalidArgumentException('The script should be a valid path to a file.');
}
$bin = $bin !== null && is_string($bin) && file_exists($bin) ?
$bin : (PHP_BINARY === '' ? '/usr/bin/php' : PHP_BINARY);
$job = new Job($bin . ' ' . $script, $args, $id);
if (! file_exists($script)) {
$this->pushFailedJob(
$job,
new InvalidArgumentException('The script should be a valid path to a file.')
);
}
$this->queueJob($job->configure($this->config));
return $job;
} | php | public function php($script, $bin = null, $args = [], $id = null)
{
if (! is_string($script)) {
throw new InvalidArgumentException('The script should be a valid path to a file.');
}
$bin = $bin !== null && is_string($bin) && file_exists($bin) ?
$bin : (PHP_BINARY === '' ? '/usr/bin/php' : PHP_BINARY);
$job = new Job($bin . ' ' . $script, $args, $id);
if (! file_exists($script)) {
$this->pushFailedJob(
$job,
new InvalidArgumentException('The script should be a valid path to a file.')
);
}
$this->queueJob($job->configure($this->config));
return $job;
} | [
"public",
"function",
"php",
"(",
"$",
"script",
",",
"$",
"bin",
"=",
"null",
",",
"$",
"args",
"=",
"[",
"]",
",",
"$",
"id",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"script",
")",
")",
"{",
"throw",
"new",
"InvalidArgum... | Queues a php script execution.
@param string $script The path to the php script to execute
@param string $bin Optional path to the php binary
@param array $args Optional arguments to pass to the php script
@param string $id Optional custom identifier
@return Job | [
"Queues",
"a",
"php",
"script",
"execution",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Scheduler.php#L120-L141 |
peppeocchi/php-cron-scheduler | src/GO/Scheduler.php | Scheduler.raw | public function raw($command, $args = [], $id = null)
{
$job = new Job($command, $args, $id);
$this->queueJob($job->configure($this->config));
return $job;
} | php | public function raw($command, $args = [], $id = null)
{
$job = new Job($command, $args, $id);
$this->queueJob($job->configure($this->config));
return $job;
} | [
"public",
"function",
"raw",
"(",
"$",
"command",
",",
"$",
"args",
"=",
"[",
"]",
",",
"$",
"id",
"=",
"null",
")",
"{",
"$",
"job",
"=",
"new",
"Job",
"(",
"$",
"command",
",",
"$",
"args",
",",
"$",
"id",
")",
";",
"$",
"this",
"->",
"qu... | Queue a raw shell command.
@param string $command The command to execute
@param array $args Optional arguments to pass to the command
@param string $id Optional custom identifier
@return Job | [
"Queue",
"a",
"raw",
"shell",
"command",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Scheduler.php#L151-L158 |
peppeocchi/php-cron-scheduler | src/GO/Scheduler.php | Scheduler.run | public function run(Datetime $runTime = null)
{
$jobs = $this->getQueuedJobs();
if (is_null($runTime)) {
$runTime = new DateTime('now');
}
foreach ($jobs as $job) {
if ($job->isDue($runTime)) {
try {
$job->run();
$this->pushExecutedJob($job);
} catch (\Exception $e) {
$this->pushFailedJob($job, $e);
}
}
}
return $this->getExecutedJobs();
} | php | public function run(Datetime $runTime = null)
{
$jobs = $this->getQueuedJobs();
if (is_null($runTime)) {
$runTime = new DateTime('now');
}
foreach ($jobs as $job) {
if ($job->isDue($runTime)) {
try {
$job->run();
$this->pushExecutedJob($job);
} catch (\Exception $e) {
$this->pushFailedJob($job, $e);
}
}
}
return $this->getExecutedJobs();
} | [
"public",
"function",
"run",
"(",
"Datetime",
"$",
"runTime",
"=",
"null",
")",
"{",
"$",
"jobs",
"=",
"$",
"this",
"->",
"getQueuedJobs",
"(",
")",
";",
"if",
"(",
"is_null",
"(",
"$",
"runTime",
")",
")",
"{",
"$",
"runTime",
"=",
"new",
"DateTim... | Run the scheduler.
@param DateTime $runTime Optional, run at specific moment
@return array Executed jobs | [
"Run",
"the",
"scheduler",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Scheduler.php#L166-L186 |
peppeocchi/php-cron-scheduler | src/GO/Scheduler.php | Scheduler.pushExecutedJob | private function pushExecutedJob(Job $job)
{
$this->executedJobs[] = $job;
$compiled = $job->compile();
// If callable, log the string Closure
if (is_callable($compiled)) {
$compiled = 'Closure';
}
$this->addSchedulerVerboseOutput("Executing {$compiled}");
return $job;
} | php | private function pushExecutedJob(Job $job)
{
$this->executedJobs[] = $job;
$compiled = $job->compile();
// If callable, log the string Closure
if (is_callable($compiled)) {
$compiled = 'Closure';
}
$this->addSchedulerVerboseOutput("Executing {$compiled}");
return $job;
} | [
"private",
"function",
"pushExecutedJob",
"(",
"Job",
"$",
"job",
")",
"{",
"$",
"this",
"->",
"executedJobs",
"[",
"]",
"=",
"$",
"job",
";",
"$",
"compiled",
"=",
"$",
"job",
"->",
"compile",
"(",
")",
";",
"// If callable, log the string Closure",
"if",... | Push a succesfully executed job.
@param Job $job
@return Job | [
"Push",
"a",
"succesfully",
"executed",
"job",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Scheduler.php#L224-L238 |
peppeocchi/php-cron-scheduler | src/GO/Scheduler.php | Scheduler.pushFailedJob | private function pushFailedJob(Job $job, Exception $e)
{
$this->failedJobs[] = $job;
$compiled = $job->compile();
// If callable, log the string Closure
if (is_callable($compiled)) {
$compiled = 'Closure';
}
$this->addSchedulerVerboseOutput("{$e->getMessage()}: {$compiled}");
return $job;
} | php | private function pushFailedJob(Job $job, Exception $e)
{
$this->failedJobs[] = $job;
$compiled = $job->compile();
// If callable, log the string Closure
if (is_callable($compiled)) {
$compiled = 'Closure';
}
$this->addSchedulerVerboseOutput("{$e->getMessage()}: {$compiled}");
return $job;
} | [
"private",
"function",
"pushFailedJob",
"(",
"Job",
"$",
"job",
",",
"Exception",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"failedJobs",
"[",
"]",
"=",
"$",
"job",
";",
"$",
"compiled",
"=",
"$",
"job",
"->",
"compile",
"(",
")",
";",
"// If callable, ... | Push a failed job.
@param Job $job
@param Exception $e
@return Job | [
"Push",
"a",
"failed",
"job",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Scheduler.php#L257-L271 |
peppeocchi/php-cron-scheduler | src/GO/Scheduler.php | Scheduler.getVerboseOutput | public function getVerboseOutput($type = 'text')
{
switch ($type) {
case 'text':
return implode("\n", $this->outputSchedule);
case 'html':
return implode('<br>', $this->outputSchedule);
case 'array':
return $this->outputSchedule;
default:
throw new InvalidArgumentException('Invalid output type');
}
} | php | public function getVerboseOutput($type = 'text')
{
switch ($type) {
case 'text':
return implode("\n", $this->outputSchedule);
case 'html':
return implode('<br>', $this->outputSchedule);
case 'array':
return $this->outputSchedule;
default:
throw new InvalidArgumentException('Invalid output type');
}
} | [
"public",
"function",
"getVerboseOutput",
"(",
"$",
"type",
"=",
"'text'",
")",
"{",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"'text'",
":",
"return",
"implode",
"(",
"\"\\n\"",
",",
"$",
"this",
"->",
"outputSchedule",
")",
";",
"case",
"'html'",
... | Get the scheduler verbose output.
@param string $type Allowed: text, html, array
@return mixed The return depends on the requested $type | [
"Get",
"the",
"scheduler",
"verbose",
"output",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Scheduler.php#L289-L301 |
peppeocchi/php-cron-scheduler | src/GO/Job.php | Job.isDue | public function isDue(DateTime $date = null)
{
// The execution time is being defaulted if not defined
if (! $this->executionTime) {
$this->at('* * * * *');
}
$date = $date !== null ? $date : $this->creationTime;
if ($this->executionYear && $this->executionYear !== $date->format('Y')) {
return false;
}
return $this->executionTime->isDue($date);
} | php | public function isDue(DateTime $date = null)
{
// The execution time is being defaulted if not defined
if (! $this->executionTime) {
$this->at('* * * * *');
}
$date = $date !== null ? $date : $this->creationTime;
if ($this->executionYear && $this->executionYear !== $date->format('Y')) {
return false;
}
return $this->executionTime->isDue($date);
} | [
"public",
"function",
"isDue",
"(",
"DateTime",
"$",
"date",
"=",
"null",
")",
"{",
"// The execution time is being defaulted if not defined",
"if",
"(",
"!",
"$",
"this",
"->",
"executionTime",
")",
"{",
"$",
"this",
"->",
"at",
"(",
"'* * * * *'",
")",
";",
... | Check if the Job is due to run.
It accepts as input a DateTime used to check if
the job is due. Defaults to job creation time.
It also defaults the execution time if not previously defined.
@param DateTime $date
@return bool | [
"Check",
"if",
"the",
"Job",
"is",
"due",
"to",
"run",
".",
"It",
"accepts",
"as",
"input",
"a",
"DateTime",
"used",
"to",
"check",
"if",
"the",
"job",
"is",
"due",
".",
"Defaults",
"to",
"job",
"creation",
"time",
".",
"It",
"also",
"defaults",
"the... | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Job.php#L194-L208 |
peppeocchi/php-cron-scheduler | src/GO/Job.php | Job.compile | public function compile()
{
$compiled = $this->command;
// If callable, return the function itself
if (is_callable($compiled)) {
return $compiled;
}
// Augment with any supplied arguments
foreach ($this->args as $key => $value) {
$compiled .= ' ' . escapeshellarg($key);
if ($value !== null) {
$compiled .= ' ' . escapeshellarg($value);
}
}
// Add the boilerplate to redirect the output to file/s
if (count($this->outputTo) > 0) {
$compiled .= ' | tee ';
$compiled .= $this->outputMode === 'a' ? '-a ' : '';
foreach ($this->outputTo as $file) {
$compiled .= $file . ' ';
}
$compiled = trim($compiled);
}
// Add boilerplate to remove lockfile after execution
if ($this->lockFile) {
$compiled .= '; rm ' . $this->lockFile;
}
// Add boilerplate to run in background
if ($this->canRunInBackground()) {
// Parentheses are need execute the chain of commands in a subshell
// that can then run in background
$compiled = '(' . $compiled . ') > /dev/null 2>&1 &';
}
return trim($compiled);
} | php | public function compile()
{
$compiled = $this->command;
// If callable, return the function itself
if (is_callable($compiled)) {
return $compiled;
}
// Augment with any supplied arguments
foreach ($this->args as $key => $value) {
$compiled .= ' ' . escapeshellarg($key);
if ($value !== null) {
$compiled .= ' ' . escapeshellarg($value);
}
}
// Add the boilerplate to redirect the output to file/s
if (count($this->outputTo) > 0) {
$compiled .= ' | tee ';
$compiled .= $this->outputMode === 'a' ? '-a ' : '';
foreach ($this->outputTo as $file) {
$compiled .= $file . ' ';
}
$compiled = trim($compiled);
}
// Add boilerplate to remove lockfile after execution
if ($this->lockFile) {
$compiled .= '; rm ' . $this->lockFile;
}
// Add boilerplate to run in background
if ($this->canRunInBackground()) {
// Parentheses are need execute the chain of commands in a subshell
// that can then run in background
$compiled = '(' . $compiled . ') > /dev/null 2>&1 &';
}
return trim($compiled);
} | [
"public",
"function",
"compile",
"(",
")",
"{",
"$",
"compiled",
"=",
"$",
"this",
"->",
"command",
";",
"// If callable, return the function itself",
"if",
"(",
"is_callable",
"(",
"$",
"compiled",
")",
")",
"{",
"return",
"$",
"compiled",
";",
"}",
"// Aug... | Compile the Job command.
@return mixed | [
"Compile",
"the",
"Job",
"command",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Job.php#L285-L326 |
peppeocchi/php-cron-scheduler | src/GO/Job.php | Job.configure | public function configure(array $config = [])
{
if (isset($config['email'])) {
if (! is_array($config['email'])) {
throw new InvalidArgumentException('Email configuration should be an array.');
}
$this->emailConfig = $config['email'];
}
// Check if config has defined a tempDir
if (isset($config['tempDir']) && is_dir($config['tempDir'])) {
$this->tempDir = $config['tempDir'];
}
return $this;
} | php | public function configure(array $config = [])
{
if (isset($config['email'])) {
if (! is_array($config['email'])) {
throw new InvalidArgumentException('Email configuration should be an array.');
}
$this->emailConfig = $config['email'];
}
// Check if config has defined a tempDir
if (isset($config['tempDir']) && is_dir($config['tempDir'])) {
$this->tempDir = $config['tempDir'];
}
return $this;
} | [
"public",
"function",
"configure",
"(",
"array",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"config",
"[",
"'email'",
"]",
")",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"config",
"[",
"'email'",
"]",
")",
")",
... | Configure the job.
@param array $config
@return self | [
"Configure",
"the",
"job",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Job.php#L334-L349 |
peppeocchi/php-cron-scheduler | src/GO/Job.php | Job.run | public function run()
{
// If the truthTest failed, don't run
if ($this->truthTest !== true) {
return false;
}
// If overlapping, don't run
if ($this->isOverlapping()) {
return false;
}
$compiled = $this->compile();
// Write lock file if necessary
$this->createLockFile();
if (is_callable($this->before)) {
call_user_func($this->before);
}
if (is_callable($compiled)) {
$this->output = $this->exec($compiled);
} else {
exec($compiled, $this->output, $this->returnCode);
}
$this->finalise();
return true;
} | php | public function run()
{
// If the truthTest failed, don't run
if ($this->truthTest !== true) {
return false;
}
// If overlapping, don't run
if ($this->isOverlapping()) {
return false;
}
$compiled = $this->compile();
// Write lock file if necessary
$this->createLockFile();
if (is_callable($this->before)) {
call_user_func($this->before);
}
if (is_callable($compiled)) {
$this->output = $this->exec($compiled);
} else {
exec($compiled, $this->output, $this->returnCode);
}
$this->finalise();
return true;
} | [
"public",
"function",
"run",
"(",
")",
"{",
"// If the truthTest failed, don't run",
"if",
"(",
"$",
"this",
"->",
"truthTest",
"!==",
"true",
")",
"{",
"return",
"false",
";",
"}",
"// If overlapping, don't run",
"if",
"(",
"$",
"this",
"->",
"isOverlapping",
... | Run the job.
@return bool | [
"Run",
"the",
"job",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Job.php#L369-L399 |
peppeocchi/php-cron-scheduler | src/GO/Job.php | Job.createLockFile | private function createLockFile($content = null)
{
if ($this->lockFile) {
if ($content === null || ! is_string($content)) {
$content = $this->getId();
}
file_put_contents($this->lockFile, $content);
}
} | php | private function createLockFile($content = null)
{
if ($this->lockFile) {
if ($content === null || ! is_string($content)) {
$content = $this->getId();
}
file_put_contents($this->lockFile, $content);
}
} | [
"private",
"function",
"createLockFile",
"(",
"$",
"content",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"lockFile",
")",
"{",
"if",
"(",
"$",
"content",
"===",
"null",
"||",
"!",
"is_string",
"(",
"$",
"content",
")",
")",
"{",
"$",
"con... | Create the job lock file.
@param mixed $content
@return void | [
"Create",
"the",
"job",
"lock",
"file",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Job.php#L407-L416 |
peppeocchi/php-cron-scheduler | src/GO/Job.php | Job.exec | private function exec(callable $fn)
{
ob_start();
try {
$returnData = call_user_func_array($fn, $this->args);
} catch (Exception $e) {
ob_end_clean();
throw $e;
}
$outputBuffer = ob_get_clean();
foreach ($this->outputTo as $filename) {
if ($outputBuffer) {
file_put_contents($filename, $outputBuffer, $this->outputMode === 'a' ? FILE_APPEND : 0);
}
if ($returnData) {
file_put_contents($filename, $returnData, FILE_APPEND);
}
}
$this->removeLockFile();
return $outputBuffer . (is_string($returnData) ? $returnData : '');
} | php | private function exec(callable $fn)
{
ob_start();
try {
$returnData = call_user_func_array($fn, $this->args);
} catch (Exception $e) {
ob_end_clean();
throw $e;
}
$outputBuffer = ob_get_clean();
foreach ($this->outputTo as $filename) {
if ($outputBuffer) {
file_put_contents($filename, $outputBuffer, $this->outputMode === 'a' ? FILE_APPEND : 0);
}
if ($returnData) {
file_put_contents($filename, $returnData, FILE_APPEND);
}
}
$this->removeLockFile();
return $outputBuffer . (is_string($returnData) ? $returnData : '');
} | [
"private",
"function",
"exec",
"(",
"callable",
"$",
"fn",
")",
"{",
"ob_start",
"(",
")",
";",
"try",
"{",
"$",
"returnData",
"=",
"call_user_func_array",
"(",
"$",
"fn",
",",
"$",
"this",
"->",
"args",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",... | Execute a callable job.
@param callable $fn
@throws Exception
@return string | [
"Execute",
"a",
"callable",
"job",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Job.php#L437-L463 |
peppeocchi/php-cron-scheduler | src/GO/Job.php | Job.output | public function output($filename, $append = false)
{
$this->outputTo = is_array($filename) ? $filename : [$filename];
$this->outputMode = $append === false ? 'w' : 'a';
return $this;
} | php | public function output($filename, $append = false)
{
$this->outputTo = is_array($filename) ? $filename : [$filename];
$this->outputMode = $append === false ? 'w' : 'a';
return $this;
} | [
"public",
"function",
"output",
"(",
"$",
"filename",
",",
"$",
"append",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"outputTo",
"=",
"is_array",
"(",
"$",
"filename",
")",
"?",
"$",
"filename",
":",
"[",
"$",
"filename",
"]",
";",
"$",
"this",
"->... | Set the file/s where to write the output of the job.
@param string|array $filename
@param bool $append
@return self | [
"Set",
"the",
"file",
"/",
"s",
"where",
"to",
"write",
"the",
"output",
"of",
"the",
"job",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Job.php#L472-L478 |
peppeocchi/php-cron-scheduler | src/GO/Job.php | Job.email | public function email($email)
{
if (! is_string($email) && ! is_array($email)) {
throw new InvalidArgumentException('The email can be only string or array');
}
$this->emailTo = is_array($email) ? $email : [$email];
// Force the job to run in foreground
$this->inForeground();
return $this;
} | php | public function email($email)
{
if (! is_string($email) && ! is_array($email)) {
throw new InvalidArgumentException('The email can be only string or array');
}
$this->emailTo = is_array($email) ? $email : [$email];
// Force the job to run in foreground
$this->inForeground();
return $this;
} | [
"public",
"function",
"email",
"(",
"$",
"email",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"email",
")",
"&&",
"!",
"is_array",
"(",
"$",
"email",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'The email can be only string or array... | Set the emails where the output should be sent to.
The Job should be set to write output to a file
for this to work.
@param string|array $email
@return self | [
"Set",
"the",
"emails",
"where",
"the",
"output",
"should",
"be",
"sent",
"to",
".",
"The",
"Job",
"should",
"be",
"set",
"to",
"write",
"output",
"to",
"a",
"file",
"for",
"this",
"to",
"work",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Job.php#L498-L510 |
peppeocchi/php-cron-scheduler | src/GO/Job.php | Job.finalise | private function finalise()
{
// Send output to email
$this->emailOutput();
// Call any callback defined
if (is_callable($this->after)) {
call_user_func($this->after, $this->output, $this->returnCode);
}
} | php | private function finalise()
{
// Send output to email
$this->emailOutput();
// Call any callback defined
if (is_callable($this->after)) {
call_user_func($this->after, $this->output, $this->returnCode);
}
} | [
"private",
"function",
"finalise",
"(",
")",
"{",
"// Send output to email",
"$",
"this",
"->",
"emailOutput",
"(",
")",
";",
"// Call any callback defined",
"if",
"(",
"is_callable",
"(",
"$",
"this",
"->",
"after",
")",
")",
"{",
"call_user_func",
"(",
"$",
... | Finilise the job after execution.
@return void | [
"Finilise",
"the",
"job",
"after",
"execution",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Job.php#L517-L526 |
peppeocchi/php-cron-scheduler | src/GO/Job.php | Job.emailOutput | private function emailOutput()
{
if (! count($this->outputTo) || ! count($this->emailTo)) {
return false;
}
if (isset($this->emailConfig['ignore_empty_output']) &&
$this->emailConfig['ignore_empty_output'] === true &&
empty($this->output)
) {
return false;
}
$this->sendToEmails($this->outputTo);
return true;
} | php | private function emailOutput()
{
if (! count($this->outputTo) || ! count($this->emailTo)) {
return false;
}
if (isset($this->emailConfig['ignore_empty_output']) &&
$this->emailConfig['ignore_empty_output'] === true &&
empty($this->output)
) {
return false;
}
$this->sendToEmails($this->outputTo);
return true;
} | [
"private",
"function",
"emailOutput",
"(",
")",
"{",
"if",
"(",
"!",
"count",
"(",
"$",
"this",
"->",
"outputTo",
")",
"||",
"!",
"count",
"(",
"$",
"this",
"->",
"emailTo",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"isset",
"(",
"$"... | Email the output of the job, if any.
@return bool | [
"Email",
"the",
"output",
"of",
"the",
"job",
"if",
"any",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Job.php#L533-L549 |
peppeocchi/php-cron-scheduler | src/GO/Traits/Mailer.php | Mailer.getEmailConfig | public function getEmailConfig()
{
if (! isset($this->emailConfig['subject']) ||
! is_string($this->emailConfig['subject'])
) {
$this->emailConfig['subject'] = 'Cronjob execution';
}
if (! isset($this->emailConfig['from'])) {
$this->emailConfig['from'] = ['cronjob@server.my' => 'My Email Server'];
}
if (! isset($this->emailConfig['body']) ||
! is_string($this->emailConfig['body'])
) {
$this->emailConfig['body'] = 'Cronjob output attached';
}
if (! isset($this->emailConfig['transport']) ||
! ($this->emailConfig['transport'] instanceof \Swift_Transport)
) {
$this->emailConfig['transport'] = new \Swift_SendmailTransport();
}
return $this->emailConfig;
} | php | public function getEmailConfig()
{
if (! isset($this->emailConfig['subject']) ||
! is_string($this->emailConfig['subject'])
) {
$this->emailConfig['subject'] = 'Cronjob execution';
}
if (! isset($this->emailConfig['from'])) {
$this->emailConfig['from'] = ['cronjob@server.my' => 'My Email Server'];
}
if (! isset($this->emailConfig['body']) ||
! is_string($this->emailConfig['body'])
) {
$this->emailConfig['body'] = 'Cronjob output attached';
}
if (! isset($this->emailConfig['transport']) ||
! ($this->emailConfig['transport'] instanceof \Swift_Transport)
) {
$this->emailConfig['transport'] = new \Swift_SendmailTransport();
}
return $this->emailConfig;
} | [
"public",
"function",
"getEmailConfig",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"emailConfig",
"[",
"'subject'",
"]",
")",
"||",
"!",
"is_string",
"(",
"$",
"this",
"->",
"emailConfig",
"[",
"'subject'",
"]",
")",
")",
"{",
"$... | Get email configuration.
@return array | [
"Get",
"email",
"configuration",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Traits/Mailer.php#L10-L35 |
peppeocchi/php-cron-scheduler | src/GO/Traits/Mailer.php | Mailer.sendToEmails | private function sendToEmails(array $files)
{
$config = $this->getEmailConfig();
$mailer = new \Swift_Mailer($config['transport']);
$message = (new \Swift_Message())
->setSubject($config['subject'])
->setFrom($config['from'])
->setTo($this->emailTo)
->setBody($config['body'])
->addPart('<q>Cronjob output attached</q>', 'text/html');
foreach ($files as $filename) {
$message->attach(\Swift_Attachment::fromPath($filename));
}
$mailer->send($message);
} | php | private function sendToEmails(array $files)
{
$config = $this->getEmailConfig();
$mailer = new \Swift_Mailer($config['transport']);
$message = (new \Swift_Message())
->setSubject($config['subject'])
->setFrom($config['from'])
->setTo($this->emailTo)
->setBody($config['body'])
->addPart('<q>Cronjob output attached</q>', 'text/html');
foreach ($files as $filename) {
$message->attach(\Swift_Attachment::fromPath($filename));
}
$mailer->send($message);
} | [
"private",
"function",
"sendToEmails",
"(",
"array",
"$",
"files",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"getEmailConfig",
"(",
")",
";",
"$",
"mailer",
"=",
"new",
"\\",
"Swift_Mailer",
"(",
"$",
"config",
"[",
"'transport'",
"]",
")",
";",... | Send files to emails.
@param array $files
@return void | [
"Send",
"files",
"to",
"emails",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Traits/Mailer.php#L43-L61 |
peppeocchi/php-cron-scheduler | src/GO/Traits/Interval.php | Interval.date | public function date($date)
{
if (! $date instanceof DateTime) {
$date = new DateTime($date);
}
$this->executionYear = $date->format('Y');
return $this->at("{$date->format('i')} {$date->format('H')} {$date->format('d')} {$date->format('m')} *");
} | php | public function date($date)
{
if (! $date instanceof DateTime) {
$date = new DateTime($date);
}
$this->executionYear = $date->format('Y');
return $this->at("{$date->format('i')} {$date->format('H')} {$date->format('d')} {$date->format('m')} *");
} | [
"public",
"function",
"date",
"(",
"$",
"date",
")",
"{",
"if",
"(",
"!",
"$",
"date",
"instanceof",
"DateTime",
")",
"{",
"$",
"date",
"=",
"new",
"DateTime",
"(",
"$",
"date",
")",
";",
"}",
"$",
"this",
"->",
"executionYear",
"=",
"$",
"date",
... | Run the Job at a specific date.
@param string/DateTime $date
@return self | [
"Run",
"the",
"Job",
"at",
"a",
"specific",
"date",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Traits/Interval.php#L28-L37 |
peppeocchi/php-cron-scheduler | src/GO/Traits/Interval.php | Interval.daily | public function daily($hour = 0, $minute = 0)
{
if (is_string($hour)) {
$parts = explode(':', $hour);
$hour = $parts[0];
$minute = isset($parts[1]) ? $parts[1] : '0';
}
$c = $this->validateCronSequence($minute, $hour);
return $this->at("{$c['minute']} {$c['hour']} * * *");
} | php | public function daily($hour = 0, $minute = 0)
{
if (is_string($hour)) {
$parts = explode(':', $hour);
$hour = $parts[0];
$minute = isset($parts[1]) ? $parts[1] : '0';
}
$c = $this->validateCronSequence($minute, $hour);
return $this->at("{$c['minute']} {$c['hour']} * * *");
} | [
"public",
"function",
"daily",
"(",
"$",
"hour",
"=",
"0",
",",
"$",
"minute",
"=",
"0",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"hour",
")",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"':'",
",",
"$",
"hour",
")",
";",
"$",
"hour",
"="... | Set the execution time to once a day.
@param int|string $hour
@param int|string $minute
@return self | [
"Set",
"the",
"execution",
"time",
"to",
"once",
"a",
"day",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Traits/Interval.php#L69-L80 |
peppeocchi/php-cron-scheduler | src/GO/Traits/Interval.php | Interval.weekly | public function weekly($weekday = 0, $hour = 0, $minute = 0)
{
if (is_string($hour)) {
$parts = explode(':', $hour);
$hour = $parts[0];
$minute = isset($parts[1]) ? $parts[1] : '0';
}
$c = $this->validateCronSequence($minute, $hour, null, null, $weekday);
return $this->at("{$c['minute']} {$c['hour']} * * {$c['weekday']}");
} | php | public function weekly($weekday = 0, $hour = 0, $minute = 0)
{
if (is_string($hour)) {
$parts = explode(':', $hour);
$hour = $parts[0];
$minute = isset($parts[1]) ? $parts[1] : '0';
}
$c = $this->validateCronSequence($minute, $hour, null, null, $weekday);
return $this->at("{$c['minute']} {$c['hour']} * * {$c['weekday']}");
} | [
"public",
"function",
"weekly",
"(",
"$",
"weekday",
"=",
"0",
",",
"$",
"hour",
"=",
"0",
",",
"$",
"minute",
"=",
"0",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"hour",
")",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"':'",
",",
"$",
"h... | Set the execution time to once a week.
@param int|string $weekday
@param int|string $hour
@param int|string $minute
@return self | [
"Set",
"the",
"execution",
"time",
"to",
"once",
"a",
"week",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Traits/Interval.php#L90-L101 |
peppeocchi/php-cron-scheduler | src/GO/Traits/Interval.php | Interval.validateCronRange | private function validateCronRange($value, $min, $max)
{
if ($value === null || $value === '*') {
return '*';
}
if (! is_numeric($value) ||
! ($value >= $min && $value <= $max)
) {
throw new InvalidArgumentException(
"Invalid value: it should be '*' or between {$min} and {$max}."
);
}
return $value;
} | php | private function validateCronRange($value, $min, $max)
{
if ($value === null || $value === '*') {
return '*';
}
if (! is_numeric($value) ||
! ($value >= $min && $value <= $max)
) {
throw new InvalidArgumentException(
"Invalid value: it should be '*' or between {$min} and {$max}."
);
}
return $value;
} | [
"private",
"function",
"validateCronRange",
"(",
"$",
"value",
",",
"$",
"min",
",",
"$",
"max",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"null",
"||",
"$",
"value",
"===",
"'*'",
")",
"{",
"return",
"'*'",
";",
"}",
"if",
"(",
"!",
"is_numeric",
... | Validate sequence of cron expression.
@param int|string $value
@param int $min
@param int $max
@return mixed | [
"Validate",
"sequence",
"of",
"cron",
"expression",
"."
] | train | https://github.com/peppeocchi/php-cron-scheduler/blob/1b18892fdd4f9c913107fda1544ac402eb7ec6e5/src/GO/Traits/Interval.php#L394-L409 |
stecman/symfony-console-completion | src/CompletionCommand.php | CompletionCommand.mergeApplicationDefinition | public function mergeApplicationDefinition($mergeArgs = true)
{
// Get current application options
$appDefinition = $this->getApplication()->getDefinition();
$originalOptions = $appDefinition->getOptions();
// Temporarily replace application options with a filtered list
$appDefinition->setOptions(
$this->filterApplicationOptions($originalOptions)
);
parent::mergeApplicationDefinition($mergeArgs);
// Restore original application options
$appDefinition->setOptions($originalOptions);
} | php | public function mergeApplicationDefinition($mergeArgs = true)
{
// Get current application options
$appDefinition = $this->getApplication()->getDefinition();
$originalOptions = $appDefinition->getOptions();
// Temporarily replace application options with a filtered list
$appDefinition->setOptions(
$this->filterApplicationOptions($originalOptions)
);
parent::mergeApplicationDefinition($mergeArgs);
// Restore original application options
$appDefinition->setOptions($originalOptions);
} | [
"public",
"function",
"mergeApplicationDefinition",
"(",
"$",
"mergeArgs",
"=",
"true",
")",
"{",
"// Get current application options",
"$",
"appDefinition",
"=",
"$",
"this",
"->",
"getApplication",
"(",
")",
"->",
"getDefinition",
"(",
")",
";",
"$",
"originalOp... | Ignore user-defined global options
Any global options defined by user-code are meaningless to this command.
Options outside of the core defaults are ignored to avoid name and shortcut conflicts. | [
"Ignore",
"user",
"-",
"defined",
"global",
"options"
] | train | https://github.com/stecman/symfony-console-completion/blob/b71718c729f0f4e055fc66d773004619e9ebcecf/src/CompletionCommand.php#L57-L72 |
stecman/symfony-console-completion | src/CompletionCommand.php | CompletionCommand.filterApplicationOptions | protected function filterApplicationOptions(array $appOptions)
{
return array_filter($appOptions, function(InputOption $option) {
static $coreOptions = array(
'help' => true,
'quiet' => true,
'verbose' => true,
'version' => true,
'ansi' => true,
'no-ansi' => true,
'no-interaction' => true,
);
return isset($coreOptions[$option->getName()]);
});
} | php | protected function filterApplicationOptions(array $appOptions)
{
return array_filter($appOptions, function(InputOption $option) {
static $coreOptions = array(
'help' => true,
'quiet' => true,
'verbose' => true,
'version' => true,
'ansi' => true,
'no-ansi' => true,
'no-interaction' => true,
);
return isset($coreOptions[$option->getName()]);
});
} | [
"protected",
"function",
"filterApplicationOptions",
"(",
"array",
"$",
"appOptions",
")",
"{",
"return",
"array_filter",
"(",
"$",
"appOptions",
",",
"function",
"(",
"InputOption",
"$",
"option",
")",
"{",
"static",
"$",
"coreOptions",
"=",
"array",
"(",
"'h... | Reduce the passed list of options to the core defaults (if they exist)
@param InputOption[] $appOptions
@return InputOption[] | [
"Reduce",
"the",
"passed",
"list",
"of",
"options",
"to",
"the",
"core",
"defaults",
"(",
"if",
"they",
"exist",
")"
] | train | https://github.com/stecman/symfony-console-completion/blob/b71718c729f0f4e055fc66d773004619e9ebcecf/src/CompletionCommand.php#L80-L95 |
stecman/symfony-console-completion | src/CompletionCommand.php | CompletionCommand.escapeForShell | protected function escapeForShell($result, $shellType)
{
switch ($shellType) {
// BASH requires special escaping for multi-word and special character results
// This emulates registering completion with`-o filenames`, without side-effects like dir name slashes
case 'bash':
$context = $this->handler->getContext();
$wordStart = substr($context->getRawCurrentWord(), 0, 1);
if ($wordStart == "'") {
// If the current word is single-quoted, escape any single quotes in the result
$result = str_replace("'", "\\'", $result);
} else if ($wordStart == '"') {
// If the current word is double-quoted, escape any double quotes in the result
$result = str_replace('"', '\\"', $result);
} else {
// Otherwise assume the string is unquoted and word breaks should be escaped
$result = preg_replace('/([\s\'"\\\\])/', '\\\\$1', $result);
}
// Escape output to prevent special characters being lost when passing results to compgen
return escapeshellarg($result);
// No transformation by default
default:
return $result;
}
} | php | protected function escapeForShell($result, $shellType)
{
switch ($shellType) {
// BASH requires special escaping for multi-word and special character results
// This emulates registering completion with`-o filenames`, without side-effects like dir name slashes
case 'bash':
$context = $this->handler->getContext();
$wordStart = substr($context->getRawCurrentWord(), 0, 1);
if ($wordStart == "'") {
// If the current word is single-quoted, escape any single quotes in the result
$result = str_replace("'", "\\'", $result);
} else if ($wordStart == '"') {
// If the current word is double-quoted, escape any double quotes in the result
$result = str_replace('"', '\\"', $result);
} else {
// Otherwise assume the string is unquoted and word breaks should be escaped
$result = preg_replace('/([\s\'"\\\\])/', '\\\\$1', $result);
}
// Escape output to prevent special characters being lost when passing results to compgen
return escapeshellarg($result);
// No transformation by default
default:
return $result;
}
} | [
"protected",
"function",
"escapeForShell",
"(",
"$",
"result",
",",
"$",
"shellType",
")",
"{",
"switch",
"(",
"$",
"shellType",
")",
"{",
"// BASH requires special escaping for multi-word and special character results",
"// This emulates registering completion with`-o filenames`... | Escape each completion result for the specified shell
@param string $result - Completion results that should appear in the shell
@param string $shellType - Valid shell type from HookFactory
@return string | [
"Escape",
"each",
"completion",
"result",
"for",
"the",
"specified",
"shell"
] | train | https://github.com/stecman/symfony-console-completion/blob/b71718c729f0f4e055fc66d773004619e9ebcecf/src/CompletionCommand.php#L146-L173 |
stecman/symfony-console-completion | src/Completion.php | Completion.makeGlobalHandler | public static function makeGlobalHandler($targetName, $type, $completion)
{
return new Completion(CompletionInterface::ALL_COMMANDS, $targetName, $type, $completion);
} | php | public static function makeGlobalHandler($targetName, $type, $completion)
{
return new Completion(CompletionInterface::ALL_COMMANDS, $targetName, $type, $completion);
} | [
"public",
"static",
"function",
"makeGlobalHandler",
"(",
"$",
"targetName",
",",
"$",
"type",
",",
"$",
"completion",
")",
"{",
"return",
"new",
"Completion",
"(",
"CompletionInterface",
"::",
"ALL_COMMANDS",
",",
"$",
"targetName",
",",
"$",
"type",
",",
"... | Create a Completion with the command name set to CompletionInterface::ALL_COMMANDS
@deprecated - This will be removed in 1.0.0 as it is redundant and isn't any more concise than what it implements.
@param string $targetName
@param string $type
@param array|callable $completion
@return Completion | [
"Create",
"a",
"Completion",
"with",
"the",
"command",
"name",
"set",
"to",
"CompletionInterface",
"::",
"ALL_COMMANDS"
] | train | https://github.com/stecman/symfony-console-completion/blob/b71718c729f0f4e055fc66d773004619e9ebcecf/src/Completion.php#L51-L54 |
stecman/symfony-console-completion | src/CompletionHandler.php | CompletionHandler.runCompletion | public function runCompletion()
{
if (!$this->context) {
throw new \RuntimeException('A CompletionContext must be set before requesting completion.');
}
$cmdName = $this->getInput()->getFirstArgument();
try {
$this->command = $this->application->find($cmdName);
} catch (\InvalidArgumentException $e) {
// Exception thrown, when multiple or none commands are found.
}
$process = array(
'completeForOptionValues',
'completeForOptionShortcuts',
'completeForOptionShortcutValues',
'completeForOptions',
'completeForCommandName',
'completeForCommandArguments'
);
foreach ($process as $methodName) {
$result = $this->{$methodName}();
if (false !== $result) {
// Return the result of the first completion mode that matches
return $this->filterResults((array) $result);
}
}
return array();
} | php | public function runCompletion()
{
if (!$this->context) {
throw new \RuntimeException('A CompletionContext must be set before requesting completion.');
}
$cmdName = $this->getInput()->getFirstArgument();
try {
$this->command = $this->application->find($cmdName);
} catch (\InvalidArgumentException $e) {
// Exception thrown, when multiple or none commands are found.
}
$process = array(
'completeForOptionValues',
'completeForOptionShortcuts',
'completeForOptionShortcutValues',
'completeForOptions',
'completeForCommandName',
'completeForCommandArguments'
);
foreach ($process as $methodName) {
$result = $this->{$methodName}();
if (false !== $result) {
// Return the result of the first completion mode that matches
return $this->filterResults((array) $result);
}
}
return array();
} | [
"public",
"function",
"runCompletion",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"context",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'A CompletionContext must be set before requesting completion.'",
")",
";",
"}",
"$",
"cmdName",
"=",
"$... | Do the actual completion, returning an array of strings to provide to the parent shell's completion system
@throws \RuntimeException
@return string[] | [
"Do",
"the",
"actual",
"completion",
"returning",
"an",
"array",
"of",
"strings",
"to",
"provide",
"to",
"the",
"parent",
"shell",
"s",
"completion",
"system"
] | train | https://github.com/stecman/symfony-console-completion/blob/b71718c729f0f4e055fc66d773004619e9ebcecf/src/CompletionHandler.php#L97-L130 |
stecman/symfony-console-completion | src/CompletionHandler.php | CompletionHandler.getInput | public function getInput()
{
// Filter the command line content to suit ArrayInput
$words = $this->context->getWords();
array_shift($words);
$words = array_filter($words);
return new ArrayInput($words);
} | php | public function getInput()
{
// Filter the command line content to suit ArrayInput
$words = $this->context->getWords();
array_shift($words);
$words = array_filter($words);
return new ArrayInput($words);
} | [
"public",
"function",
"getInput",
"(",
")",
"{",
"// Filter the command line content to suit ArrayInput",
"$",
"words",
"=",
"$",
"this",
"->",
"context",
"->",
"getWords",
"(",
")",
";",
"array_shift",
"(",
"$",
"words",
")",
";",
"$",
"words",
"=",
"array_fi... | Get an InputInterface representation of the completion context
@return ArrayInput | [
"Get",
"an",
"InputInterface",
"representation",
"of",
"the",
"completion",
"context"
] | train | https://github.com/stecman/symfony-console-completion/blob/b71718c729f0f4e055fc66d773004619e9ebcecf/src/CompletionHandler.php#L137-L145 |
stecman/symfony-console-completion | src/CompletionHandler.php | CompletionHandler.completeForOptions | protected function completeForOptions()
{
$word = $this->context->getCurrentWord();
if (substr($word, 0, 2) === '--') {
$options = array();
foreach ($this->getAllOptions() as $opt) {
$options[] = '--'.$opt->getName();
}
return $options;
}
return false;
} | php | protected function completeForOptions()
{
$word = $this->context->getCurrentWord();
if (substr($word, 0, 2) === '--') {
$options = array();
foreach ($this->getAllOptions() as $opt) {
$options[] = '--'.$opt->getName();
}
return $options;
}
return false;
} | [
"protected",
"function",
"completeForOptions",
"(",
")",
"{",
"$",
"word",
"=",
"$",
"this",
"->",
"context",
"->",
"getCurrentWord",
"(",
")",
";",
"if",
"(",
"substr",
"(",
"$",
"word",
",",
"0",
",",
"2",
")",
"===",
"'--'",
")",
"{",
"$",
"opti... | Attempt to complete the current word as a long-form option (--my-option)
@return array|false | [
"Attempt",
"to",
"complete",
"the",
"current",
"word",
"as",
"a",
"long",
"-",
"form",
"option",
"(",
"--",
"my",
"-",
"option",
")"
] | train | https://github.com/stecman/symfony-console-completion/blob/b71718c729f0f4e055fc66d773004619e9ebcecf/src/CompletionHandler.php#L152-L167 |
stecman/symfony-console-completion | src/CompletionHandler.php | CompletionHandler.completeForOptionShortcuts | protected function completeForOptionShortcuts()
{
$word = $this->context->getCurrentWord();
if (strpos($word, '-') === 0 && strlen($word) == 2) {
$definition = $this->command ? $this->command->getNativeDefinition() : $this->application->getDefinition();
if ($definition->hasShortcut(substr($word, 1))) {
return array($word);
}
}
return false;
} | php | protected function completeForOptionShortcuts()
{
$word = $this->context->getCurrentWord();
if (strpos($word, '-') === 0 && strlen($word) == 2) {
$definition = $this->command ? $this->command->getNativeDefinition() : $this->application->getDefinition();
if ($definition->hasShortcut(substr($word, 1))) {
return array($word);
}
}
return false;
} | [
"protected",
"function",
"completeForOptionShortcuts",
"(",
")",
"{",
"$",
"word",
"=",
"$",
"this",
"->",
"context",
"->",
"getCurrentWord",
"(",
")",
";",
"if",
"(",
"strpos",
"(",
"$",
"word",
",",
"'-'",
")",
"===",
"0",
"&&",
"strlen",
"(",
"$",
... | Attempt to complete the current word as an option shortcut.
If the shortcut exists it will be completed, but a list of possible shortcuts is never returned for completion.
@return array|false | [
"Attempt",
"to",
"complete",
"the",
"current",
"word",
"as",
"an",
"option",
"shortcut",
"."
] | train | https://github.com/stecman/symfony-console-completion/blob/b71718c729f0f4e055fc66d773004619e9ebcecf/src/CompletionHandler.php#L176-L189 |
stecman/symfony-console-completion | src/CompletionHandler.php | CompletionHandler.completeForOptionShortcutValues | protected function completeForOptionShortcutValues()
{
$wordIndex = $this->context->getWordIndex();
if ($this->command && $wordIndex > 1) {
$left = $this->context->getWordAtIndex($wordIndex - 1);
// Complete short options
if ($left[0] == '-' && strlen($left) == 2) {
$shortcut = substr($left, 1);
$def = $this->command->getNativeDefinition();
if (!$def->hasShortcut($shortcut)) {
return false;
}
$opt = $def->getOptionForShortcut($shortcut);
if ($opt->isValueRequired() || $opt->isValueOptional()) {
return $this->completeOption($opt);
}
}
}
return false;
} | php | protected function completeForOptionShortcutValues()
{
$wordIndex = $this->context->getWordIndex();
if ($this->command && $wordIndex > 1) {
$left = $this->context->getWordAtIndex($wordIndex - 1);
// Complete short options
if ($left[0] == '-' && strlen($left) == 2) {
$shortcut = substr($left, 1);
$def = $this->command->getNativeDefinition();
if (!$def->hasShortcut($shortcut)) {
return false;
}
$opt = $def->getOptionForShortcut($shortcut);
if ($opt->isValueRequired() || $opt->isValueOptional()) {
return $this->completeOption($opt);
}
}
}
return false;
} | [
"protected",
"function",
"completeForOptionShortcutValues",
"(",
")",
"{",
"$",
"wordIndex",
"=",
"$",
"this",
"->",
"context",
"->",
"getWordIndex",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"command",
"&&",
"$",
"wordIndex",
">",
"1",
")",
"{",
"$",... | Attempt to complete the current word as the value of an option shortcut
@return array|false | [
"Attempt",
"to",
"complete",
"the",
"current",
"word",
"as",
"the",
"value",
"of",
"an",
"option",
"shortcut"
] | train | https://github.com/stecman/symfony-console-completion/blob/b71718c729f0f4e055fc66d773004619e9ebcecf/src/CompletionHandler.php#L196-L220 |
stecman/symfony-console-completion | src/CompletionHandler.php | CompletionHandler.completeForOptionValues | protected function completeForOptionValues()
{
$wordIndex = $this->context->getWordIndex();
if ($this->command && $wordIndex > 1) {
$left = $this->context->getWordAtIndex($wordIndex - 1);
if (strpos($left, '--') === 0) {
$name = substr($left, 2);
$def = $this->command->getNativeDefinition();
if (!$def->hasOption($name)) {
return false;
}
$opt = $def->getOption($name);
if ($opt->isValueRequired() || $opt->isValueOptional()) {
return $this->completeOption($opt);
}
}
}
return false;
} | php | protected function completeForOptionValues()
{
$wordIndex = $this->context->getWordIndex();
if ($this->command && $wordIndex > 1) {
$left = $this->context->getWordAtIndex($wordIndex - 1);
if (strpos($left, '--') === 0) {
$name = substr($left, 2);
$def = $this->command->getNativeDefinition();
if (!$def->hasOption($name)) {
return false;
}
$opt = $def->getOption($name);
if ($opt->isValueRequired() || $opt->isValueOptional()) {
return $this->completeOption($opt);
}
}
}
return false;
} | [
"protected",
"function",
"completeForOptionValues",
"(",
")",
"{",
"$",
"wordIndex",
"=",
"$",
"this",
"->",
"context",
"->",
"getWordIndex",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"command",
"&&",
"$",
"wordIndex",
">",
"1",
")",
"{",
"$",
"left... | Attemp to complete the current word as the value of a long-form option
@return array|false | [
"Attemp",
"to",
"complete",
"the",
"current",
"word",
"as",
"the",
"value",
"of",
"a",
"long",
"-",
"form",
"option"
] | train | https://github.com/stecman/symfony-console-completion/blob/b71718c729f0f4e055fc66d773004619e9ebcecf/src/CompletionHandler.php#L227-L250 |
stecman/symfony-console-completion | src/CompletionHandler.php | CompletionHandler.completeForCommandName | protected function completeForCommandName()
{
if (!$this->command || (count($this->context->getWords()) == 2 && $this->context->getWordIndex() == 1)) {
return $this->getCommandNames();
}
return false;
} | php | protected function completeForCommandName()
{
if (!$this->command || (count($this->context->getWords()) == 2 && $this->context->getWordIndex() == 1)) {
return $this->getCommandNames();
}
return false;
} | [
"protected",
"function",
"completeForCommandName",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"command",
"||",
"(",
"count",
"(",
"$",
"this",
"->",
"context",
"->",
"getWords",
"(",
")",
")",
"==",
"2",
"&&",
"$",
"this",
"->",
"context",
"->... | Attempt to complete the current word as a command name
@return array|false | [
"Attempt",
"to",
"complete",
"the",
"current",
"word",
"as",
"a",
"command",
"name"
] | train | https://github.com/stecman/symfony-console-completion/blob/b71718c729f0f4e055fc66d773004619e9ebcecf/src/CompletionHandler.php#L257-L264 |
stecman/symfony-console-completion | src/CompletionHandler.php | CompletionHandler.completeForCommandArguments | protected function completeForCommandArguments()
{
if (!$this->command || strpos($this->context->getCurrentWord(), '-') === 0) {
return false;
}
$definition = $this->command->getNativeDefinition();
$argWords = $this->mapArgumentsToWords($definition->getArguments());
$wordIndex = $this->context->getWordIndex();
if (isset($argWords[$wordIndex])) {
$name = $argWords[$wordIndex];
} elseif (!empty($argWords) && $definition->getArgument(end($argWords))->isArray()) {
$name = end($argWords);
} else {
return false;
}
if ($helper = $this->getCompletionHelper($name, Completion::TYPE_ARGUMENT)) {
return $helper->run();
}
if ($this->command instanceof CompletionAwareInterface) {
return $this->command->completeArgumentValues($name, $this->context);
}
return false;
} | php | protected function completeForCommandArguments()
{
if (!$this->command || strpos($this->context->getCurrentWord(), '-') === 0) {
return false;
}
$definition = $this->command->getNativeDefinition();
$argWords = $this->mapArgumentsToWords($definition->getArguments());
$wordIndex = $this->context->getWordIndex();
if (isset($argWords[$wordIndex])) {
$name = $argWords[$wordIndex];
} elseif (!empty($argWords) && $definition->getArgument(end($argWords))->isArray()) {
$name = end($argWords);
} else {
return false;
}
if ($helper = $this->getCompletionHelper($name, Completion::TYPE_ARGUMENT)) {
return $helper->run();
}
if ($this->command instanceof CompletionAwareInterface) {
return $this->command->completeArgumentValues($name, $this->context);
}
return false;
} | [
"protected",
"function",
"completeForCommandArguments",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"command",
"||",
"strpos",
"(",
"$",
"this",
"->",
"context",
"->",
"getCurrentWord",
"(",
")",
",",
"'-'",
")",
"===",
"0",
")",
"{",
"return",
"... | Attempt to complete the current word as a command argument value
@see Symfony\Component\Console\Input\InputArgument
@return array|false | [
"Attempt",
"to",
"complete",
"the",
"current",
"word",
"as",
"a",
"command",
"argument",
"value"
] | train | https://github.com/stecman/symfony-console-completion/blob/b71718c729f0f4e055fc66d773004619e9ebcecf/src/CompletionHandler.php#L272-L299 |
stecman/symfony-console-completion | src/CompletionHandler.php | CompletionHandler.getCompletionHelper | protected function getCompletionHelper($name, $type)
{
foreach ($this->helpers as $helper) {
if ($helper->getType() != $type && $helper->getType() != CompletionInterface::ALL_TYPES) {
continue;
}
if ($helper->getCommandName() == CompletionInterface::ALL_COMMANDS || $helper->getCommandName() == $this->command->getName()) {
if ($helper->getTargetName() == $name) {
return $helper;
}
}
}
return null;
} | php | protected function getCompletionHelper($name, $type)
{
foreach ($this->helpers as $helper) {
if ($helper->getType() != $type && $helper->getType() != CompletionInterface::ALL_TYPES) {
continue;
}
if ($helper->getCommandName() == CompletionInterface::ALL_COMMANDS || $helper->getCommandName() == $this->command->getName()) {
if ($helper->getTargetName() == $name) {
return $helper;
}
}
}
return null;
} | [
"protected",
"function",
"getCompletionHelper",
"(",
"$",
"name",
",",
"$",
"type",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"helpers",
"as",
"$",
"helper",
")",
"{",
"if",
"(",
"$",
"helper",
"->",
"getType",
"(",
")",
"!=",
"$",
"type",
"&&",
... | Find a CompletionInterface that matches the current command, target name, and target type
@param string $name
@param string $type
@return CompletionInterface|null | [
"Find",
"a",
"CompletionInterface",
"that",
"matches",
"the",
"current",
"command",
"target",
"name",
"and",
"target",
"type"
] | train | https://github.com/stecman/symfony-console-completion/blob/b71718c729f0f4e055fc66d773004619e9ebcecf/src/CompletionHandler.php#L308-L323 |
stecman/symfony-console-completion | src/CompletionHandler.php | CompletionHandler.completeOption | protected function completeOption(InputOption $option)
{
if ($helper = $this->getCompletionHelper($option->getName(), Completion::TYPE_OPTION)) {
return $helper->run();
}
if ($this->command instanceof CompletionAwareInterface) {
return $this->command->completeOptionValues($option->getName(), $this->context);
}
return false;
} | php | protected function completeOption(InputOption $option)
{
if ($helper = $this->getCompletionHelper($option->getName(), Completion::TYPE_OPTION)) {
return $helper->run();
}
if ($this->command instanceof CompletionAwareInterface) {
return $this->command->completeOptionValues($option->getName(), $this->context);
}
return false;
} | [
"protected",
"function",
"completeOption",
"(",
"InputOption",
"$",
"option",
")",
"{",
"if",
"(",
"$",
"helper",
"=",
"$",
"this",
"->",
"getCompletionHelper",
"(",
"$",
"option",
"->",
"getName",
"(",
")",
",",
"Completion",
"::",
"TYPE_OPTION",
")",
")"... | Complete the value for the given option if a value completion is availble
@param InputOption $option
@return array|false | [
"Complete",
"the",
"value",
"for",
"the",
"given",
"option",
"if",
"a",
"value",
"completion",
"is",
"availble"
] | train | https://github.com/stecman/symfony-console-completion/blob/b71718c729f0f4e055fc66d773004619e9ebcecf/src/CompletionHandler.php#L331-L342 |
stecman/symfony-console-completion | src/CompletionHandler.php | CompletionHandler.mapArgumentsToWords | protected function mapArgumentsToWords($argumentDefinitions)
{
$argumentPositions = array();
$argumentNumber = 0;
$previousWord = null;
$argumentNames = array_keys($argumentDefinitions);
// Build a list of option values to filter out
$optionsWithArgs = $this->getOptionWordsWithValues();
foreach ($this->context->getWords() as $wordIndex => $word) {
// Skip program name, command name, options, and option values
if ($wordIndex < 2
|| ($word && '-' === $word[0])
|| in_array($previousWord, $optionsWithArgs)) {
$previousWord = $word;
continue;
} else {
$previousWord = $word;
}
// If argument n exists, pair that argument's name with the current word
if (isset($argumentNames[$argumentNumber])) {
$argumentPositions[$wordIndex] = $argumentNames[$argumentNumber];
}
$argumentNumber++;
}
return $argumentPositions;
} | php | protected function mapArgumentsToWords($argumentDefinitions)
{
$argumentPositions = array();
$argumentNumber = 0;
$previousWord = null;
$argumentNames = array_keys($argumentDefinitions);
// Build a list of option values to filter out
$optionsWithArgs = $this->getOptionWordsWithValues();
foreach ($this->context->getWords() as $wordIndex => $word) {
// Skip program name, command name, options, and option values
if ($wordIndex < 2
|| ($word && '-' === $word[0])
|| in_array($previousWord, $optionsWithArgs)) {
$previousWord = $word;
continue;
} else {
$previousWord = $word;
}
// If argument n exists, pair that argument's name with the current word
if (isset($argumentNames[$argumentNumber])) {
$argumentPositions[$wordIndex] = $argumentNames[$argumentNumber];
}
$argumentNumber++;
}
return $argumentPositions;
} | [
"protected",
"function",
"mapArgumentsToWords",
"(",
"$",
"argumentDefinitions",
")",
"{",
"$",
"argumentPositions",
"=",
"array",
"(",
")",
";",
"$",
"argumentNumber",
"=",
"0",
";",
"$",
"previousWord",
"=",
"null",
";",
"$",
"argumentNames",
"=",
"array_key... | Step through the command line to determine which word positions represent which argument values
The word indexes of argument values are found by eliminating words that are known to not be arguments (options,
option values, and command names). Any word that doesn't match for elimination is assumed to be an argument value,
@param InputArgument[] $argumentDefinitions
@return array as [argument name => word index on command line] | [
"Step",
"through",
"the",
"command",
"line",
"to",
"determine",
"which",
"word",
"positions",
"represent",
"which",
"argument",
"values"
] | train | https://github.com/stecman/symfony-console-completion/blob/b71718c729f0f4e055fc66d773004619e9ebcecf/src/CompletionHandler.php#L353-L383 |
stecman/symfony-console-completion | src/CompletionHandler.php | CompletionHandler.getOptionWordsWithValues | protected function getOptionWordsWithValues()
{
$strings = array();
foreach ($this->getAllOptions() as $option) {
if ($option->isValueRequired()) {
$strings[] = '--' . $option->getName();
if ($option->getShortcut()) {
$strings[] = '-' . $option->getShortcut();
}
}
}
return $strings;
} | php | protected function getOptionWordsWithValues()
{
$strings = array();
foreach ($this->getAllOptions() as $option) {
if ($option->isValueRequired()) {
$strings[] = '--' . $option->getName();
if ($option->getShortcut()) {
$strings[] = '-' . $option->getShortcut();
}
}
}
return $strings;
} | [
"protected",
"function",
"getOptionWordsWithValues",
"(",
")",
"{",
"$",
"strings",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getAllOptions",
"(",
")",
"as",
"$",
"option",
")",
"{",
"if",
"(",
"$",
"option",
"->",
"isValueRequired... | Build a list of option words/flags that will have a value after them
Options are returned in the format they appear as on the command line.
@return string[] - eg. ['--myoption', '-m', ... ] | [
"Build",
"a",
"list",
"of",
"option",
"words",
"/",
"flags",
"that",
"will",
"have",
"a",
"value",
"after",
"them",
"Options",
"are",
"returned",
"in",
"the",
"format",
"they",
"appear",
"as",
"on",
"the",
"command",
"line",
"."
] | train | https://github.com/stecman/symfony-console-completion/blob/b71718c729f0f4e055fc66d773004619e9ebcecf/src/CompletionHandler.php#L391-L406 |
stecman/symfony-console-completion | src/CompletionHandler.php | CompletionHandler.filterResults | protected function filterResults(array $array)
{
$curWord = $this->context->getCurrentWord();
return array_filter($array, function($val) use ($curWord) {
return fnmatch($curWord.'*', $val);
});
} | php | protected function filterResults(array $array)
{
$curWord = $this->context->getCurrentWord();
return array_filter($array, function($val) use ($curWord) {
return fnmatch($curWord.'*', $val);
});
} | [
"protected",
"function",
"filterResults",
"(",
"array",
"$",
"array",
")",
"{",
"$",
"curWord",
"=",
"$",
"this",
"->",
"context",
"->",
"getCurrentWord",
"(",
")",
";",
"return",
"array_filter",
"(",
"$",
"array",
",",
"function",
"(",
"$",
"val",
")",
... | Filter out results that don't match the current word on the command line
@param string[] $array
@return string[] | [
"Filter",
"out",
"results",
"that",
"don",
"t",
"match",
"the",
"current",
"word",
"on",
"the",
"command",
"line"
] | train | https://github.com/stecman/symfony-console-completion/blob/b71718c729f0f4e055fc66d773004619e9ebcecf/src/CompletionHandler.php#L414-L421 |
stecman/symfony-console-completion | src/CompletionHandler.php | CompletionHandler.getAllOptions | protected function getAllOptions()
{
if (!$this->command) {
return $this->application->getDefinition()->getOptions();
}
return array_merge(
$this->command->getNativeDefinition()->getOptions(),
$this->application->getDefinition()->getOptions()
);
} | php | protected function getAllOptions()
{
if (!$this->command) {
return $this->application->getDefinition()->getOptions();
}
return array_merge(
$this->command->getNativeDefinition()->getOptions(),
$this->application->getDefinition()->getOptions()
);
} | [
"protected",
"function",
"getAllOptions",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"command",
")",
"{",
"return",
"$",
"this",
"->",
"application",
"->",
"getDefinition",
"(",
")",
"->",
"getOptions",
"(",
")",
";",
"}",
"return",
"array_merge",... | Get the combined options of the application and entered command
@return InputOption[] | [
"Get",
"the",
"combined",
"options",
"of",
"the",
"application",
"and",
"entered",
"command"
] | train | https://github.com/stecman/symfony-console-completion/blob/b71718c729f0f4e055fc66d773004619e9ebcecf/src/CompletionHandler.php#L428-L438 |
stecman/symfony-console-completion | src/CompletionHandler.php | CompletionHandler.getCommandNames | protected function getCommandNames()
{
// Command::Hidden isn't supported before Symfony Console 3.2.0
// We don't complete hidden command names as these are intended to be private
if (method_exists('\Symfony\Component\Console\Command\Command', 'isHidden')) {
$commands = array();
foreach ($this->application->all() as $name => $command) {
if (!$command->isHidden()) {
$commands[] = $name;
}
}
return $commands;
} else {
// Fallback for compatibility with Symfony Console < 3.2.0
// This was the behaviour prior to pull #75
$commands = $this->application->all();
unset($commands['_completion']);
return array_keys($commands);
}
} | php | protected function getCommandNames()
{
// Command::Hidden isn't supported before Symfony Console 3.2.0
// We don't complete hidden command names as these are intended to be private
if (method_exists('\Symfony\Component\Console\Command\Command', 'isHidden')) {
$commands = array();
foreach ($this->application->all() as $name => $command) {
if (!$command->isHidden()) {
$commands[] = $name;
}
}
return $commands;
} else {
// Fallback for compatibility with Symfony Console < 3.2.0
// This was the behaviour prior to pull #75
$commands = $this->application->all();
unset($commands['_completion']);
return array_keys($commands);
}
} | [
"protected",
"function",
"getCommandNames",
"(",
")",
"{",
"// Command::Hidden isn't supported before Symfony Console 3.2.0",
"// We don't complete hidden command names as these are intended to be private",
"if",
"(",
"method_exists",
"(",
"'\\Symfony\\Component\\Console\\Command\\Command'",... | Get command names available for completion
Filters out hidden commands where supported.
@return string[] | [
"Get",
"command",
"names",
"available",
"for",
"completion"
] | train | https://github.com/stecman/symfony-console-completion/blob/b71718c729f0f4e055fc66d773004619e9ebcecf/src/CompletionHandler.php#L447-L471 |
stecman/symfony-console-completion | src/HookFactory.php | HookFactory.generateHook | public function generateHook($type, $programPath, $programName = null, $multiple = false)
{
if (!isset(self::$hooks[$type])) {
throw new \RuntimeException(sprintf(
"Cannot generate hook for unknown shell type '%s'. Available hooks are: %s",
$type,
implode(', ', self::getShellTypes())
));
}
// Use the program path if an alias/name is not given
$programName = $programName ?: $programPath;
if ($multiple) {
$completionCommand = '$1 _completion';
} else {
$completionCommand = $programPath . ' _completion';
}
// Pass shell type during completion so output can be encoded if the shell requires it
$completionCommand .= " --shell-type $type";
return str_replace(
array(
'%%function_name%%',
'%%program_name%%',
'%%program_path%%',
'%%completion_command%%',
),
array(
$this->generateFunctionName($programPath, $programName),
$programName,
$programPath,
$completionCommand
),
$this->stripComments(self::$hooks[$type])
);
} | php | public function generateHook($type, $programPath, $programName = null, $multiple = false)
{
if (!isset(self::$hooks[$type])) {
throw new \RuntimeException(sprintf(
"Cannot generate hook for unknown shell type '%s'. Available hooks are: %s",
$type,
implode(', ', self::getShellTypes())
));
}
// Use the program path if an alias/name is not given
$programName = $programName ?: $programPath;
if ($multiple) {
$completionCommand = '$1 _completion';
} else {
$completionCommand = $programPath . ' _completion';
}
// Pass shell type during completion so output can be encoded if the shell requires it
$completionCommand .= " --shell-type $type";
return str_replace(
array(
'%%function_name%%',
'%%program_name%%',
'%%program_path%%',
'%%completion_command%%',
),
array(
$this->generateFunctionName($programPath, $programName),
$programName,
$programPath,
$completionCommand
),
$this->stripComments(self::$hooks[$type])
);
} | [
"public",
"function",
"generateHook",
"(",
"$",
"type",
",",
"$",
"programPath",
",",
"$",
"programName",
"=",
"null",
",",
"$",
"multiple",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"hooks",
"[",
"$",
"type",
"]",
")... | Return a completion hook for the specified shell type
@param string $type - a key from self::$hooks
@param string $programPath
@param string $programName
@param bool $multiple
@return string | [
"Return",
"a",
"completion",
"hook",
"for",
"the",
"specified",
"shell",
"type"
] | train | https://github.com/stecman/symfony-console-completion/blob/b71718c729f0f4e055fc66d773004619e9ebcecf/src/HookFactory.php#L136-L173 |
stecman/symfony-console-completion | src/HookFactory.php | HookFactory.generateFunctionName | protected function generateFunctionName($programPath, $programName)
{
return sprintf(
'_%s_%s_complete',
$this->sanitiseForFunctionName(basename($programName)),
substr(md5($programPath), 0, 16)
);
} | php | protected function generateFunctionName($programPath, $programName)
{
return sprintf(
'_%s_%s_complete',
$this->sanitiseForFunctionName(basename($programName)),
substr(md5($programPath), 0, 16)
);
} | [
"protected",
"function",
"generateFunctionName",
"(",
"$",
"programPath",
",",
"$",
"programName",
")",
"{",
"return",
"sprintf",
"(",
"'_%s_%s_complete'",
",",
"$",
"this",
"->",
"sanitiseForFunctionName",
"(",
"basename",
"(",
"$",
"programName",
")",
")",
","... | Generate a function name that is unlikely to conflict with other generated function names in the same shell | [
"Generate",
"a",
"function",
"name",
"that",
"is",
"unlikely",
"to",
"conflict",
"with",
"other",
"generated",
"function",
"names",
"in",
"the",
"same",
"shell"
] | train | https://github.com/stecman/symfony-console-completion/blob/b71718c729f0f4e055fc66d773004619e9ebcecf/src/HookFactory.php#L178-L185 |
yii2mod/yii2-settings | actions/SettingsAction.php | SettingsAction.run | public function run()
{
/* @var $model Model */
$model = Yii::createObject($this->modelClass);
$event = Yii::createObject(['class' => FormEvent::class, 'form' => $model]);
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$this->trigger(self::EVENT_BEFORE_SAVE, $event);
$this->saveSettings($model);
$this->trigger(self::EVENT_AFTER_SAVE, $event);
if ($this->successMessage !== null) {
Yii::$app->session->setFlash('success', $this->successMessage);
}
return $this->controller->refresh();
}
$this->prepareModel($model);
return $this->controller->render($this->view, ArrayHelper::merge($this->viewParams, [
'model' => $model,
]));
} | php | public function run()
{
/* @var $model Model */
$model = Yii::createObject($this->modelClass);
$event = Yii::createObject(['class' => FormEvent::class, 'form' => $model]);
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$this->trigger(self::EVENT_BEFORE_SAVE, $event);
$this->saveSettings($model);
$this->trigger(self::EVENT_AFTER_SAVE, $event);
if ($this->successMessage !== null) {
Yii::$app->session->setFlash('success', $this->successMessage);
}
return $this->controller->refresh();
}
$this->prepareModel($model);
return $this->controller->render($this->view, ArrayHelper::merge($this->viewParams, [
'model' => $model,
]));
} | [
"public",
"function",
"run",
"(",
")",
"{",
"/* @var $model Model */",
"$",
"model",
"=",
"Yii",
"::",
"createObject",
"(",
"$",
"this",
"->",
"modelClass",
")",
";",
"$",
"event",
"=",
"Yii",
"::",
"createObject",
"(",
"[",
"'class'",
"=>",
"FormEvent",
... | Renders the settings form.
@return string | [
"Renders",
"the",
"settings",
"form",
"."
] | train | https://github.com/yii2mod/yii2-settings/blob/5e61cf4de48c7d61fd6d93ea40bc9a16ba518df6/actions/SettingsAction.php#L99-L124 |
yii2mod/yii2-settings | actions/SettingsAction.php | SettingsAction.prepareModel | protected function prepareModel(Model $model)
{
if (is_callable($this->prepareModel)) {
call_user_func($this->prepareModel, $model);
} else {
foreach ($model->attributes() as $attribute) {
$value = Yii::$app->settings->get($this->getSection($model), $attribute);
if (!is_null($value)) {
$model->{$attribute} = $value;
}
}
}
} | php | protected function prepareModel(Model $model)
{
if (is_callable($this->prepareModel)) {
call_user_func($this->prepareModel, $model);
} else {
foreach ($model->attributes() as $attribute) {
$value = Yii::$app->settings->get($this->getSection($model), $attribute);
if (!is_null($value)) {
$model->{$attribute} = $value;
}
}
}
} | [
"protected",
"function",
"prepareModel",
"(",
"Model",
"$",
"model",
")",
"{",
"if",
"(",
"is_callable",
"(",
"$",
"this",
"->",
"prepareModel",
")",
")",
"{",
"call_user_func",
"(",
"$",
"this",
"->",
"prepareModel",
",",
"$",
"model",
")",
";",
"}",
... | Prepares the model which will be used to validate the attributes.
@param Model $model | [
"Prepares",
"the",
"model",
"which",
"will",
"be",
"used",
"to",
"validate",
"the",
"attributes",
"."
] | train | https://github.com/yii2mod/yii2-settings/blob/5e61cf4de48c7d61fd6d93ea40bc9a16ba518df6/actions/SettingsAction.php#L131-L144 |
yii2mod/yii2-settings | actions/SettingsAction.php | SettingsAction.getSection | protected function getSection(Model $model): string
{
if ($this->sectionName !== null) {
return $this->sectionName;
}
return $model->formName();
} | php | protected function getSection(Model $model): string
{
if ($this->sectionName !== null) {
return $this->sectionName;
}
return $model->formName();
} | [
"protected",
"function",
"getSection",
"(",
"Model",
"$",
"model",
")",
":",
"string",
"{",
"if",
"(",
"$",
"this",
"->",
"sectionName",
"!==",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"sectionName",
";",
"}",
"return",
"$",
"model",
"->",
"formN... | @param Model $model
@return string | [
"@param",
"Model",
"$model"
] | train | https://github.com/yii2mod/yii2-settings/blob/5e61cf4de48c7d61fd6d93ea40bc9a16ba518df6/actions/SettingsAction.php#L165-L172 |
yii2mod/yii2-settings | models/search/SettingSearch.php | SettingSearch.search | public function search(array $params): ActiveDataProvider
{
$query = self::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => $this->pageSize,
],
]);
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
$query->andFilterWhere([
'status' => $this->status,
'section' => $this->section,
'type' => $this->type,
]);
$query->andFilterWhere(['like', 'key', $this->key])
->andFilterWhere(['like', 'value', $this->value])
->andFilterWhere(['like', 'description', $this->description]);
return $dataProvider;
} | php | public function search(array $params): ActiveDataProvider
{
$query = self::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => $this->pageSize,
],
]);
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
$query->andFilterWhere([
'status' => $this->status,
'section' => $this->section,
'type' => $this->type,
]);
$query->andFilterWhere(['like', 'key', $this->key])
->andFilterWhere(['like', 'value', $this->value])
->andFilterWhere(['like', 'description', $this->description]);
return $dataProvider;
} | [
"public",
"function",
"search",
"(",
"array",
"$",
"params",
")",
":",
"ActiveDataProvider",
"{",
"$",
"query",
"=",
"self",
"::",
"find",
"(",
")",
";",
"$",
"dataProvider",
"=",
"new",
"ActiveDataProvider",
"(",
"[",
"'query'",
"=>",
"$",
"query",
",",... | Creates data provider instance with search query applied
@param array $params
@return ActiveDataProvider | [
"Creates",
"data",
"provider",
"instance",
"with",
"search",
"query",
"applied"
] | train | https://github.com/yii2mod/yii2-settings/blob/5e61cf4de48c7d61fd6d93ea40bc9a16ba518df6/models/search/SettingSearch.php#L37-L65 |
yii2mod/yii2-settings | controllers/DefaultController.php | DefaultController.findModel | protected function findModel(int $id)
{
$settingModelClass = $this->modelClass;
if (($model = $settingModelClass::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException(Yii::t('yii2mod.settings', 'The requested page does not exist.'));
}
} | php | protected function findModel(int $id)
{
$settingModelClass = $this->modelClass;
if (($model = $settingModelClass::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException(Yii::t('yii2mod.settings', 'The requested page does not exist.'));
}
} | [
"protected",
"function",
"findModel",
"(",
"int",
"$",
"id",
")",
"{",
"$",
"settingModelClass",
"=",
"$",
"this",
"->",
"modelClass",
";",
"if",
"(",
"(",
"$",
"model",
"=",
"$",
"settingModelClass",
"::",
"findOne",
"(",
"$",
"id",
")",
")",
"!==",
... | Finds a Setting model based on its primary key value.
If the model is not found, a 404 HTTP exception will be thrown.
@param int $id
@return SettingModel the loaded model
@throws NotFoundHttpException if the model cannot be found | [
"Finds",
"a",
"Setting",
"model",
"based",
"on",
"its",
"primary",
"key",
"value",
"."
] | train | https://github.com/yii2mod/yii2-settings/blob/5e61cf4de48c7d61fd6d93ea40bc9a16ba518df6/controllers/DefaultController.php#L170-L179 |
yii2mod/yii2-settings | components/Settings.php | Settings.init | public function init()
{
parent::init();
if ($this->cache !== null) {
$this->cache = Instance::ensure($this->cache, Cache::class);
}
$this->model = Yii::createObject($this->modelClass);
} | php | public function init()
{
parent::init();
if ($this->cache !== null) {
$this->cache = Instance::ensure($this->cache, Cache::class);
}
$this->model = Yii::createObject($this->modelClass);
} | [
"public",
"function",
"init",
"(",
")",
"{",
"parent",
"::",
"init",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"cache",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"cache",
"=",
"Instance",
"::",
"ensure",
"(",
"$",
"this",
"->",
"cache",
",",... | Initialize the component | [
"Initialize",
"the",
"component"
] | train | https://github.com/yii2mod/yii2-settings/blob/5e61cf4de48c7d61fd6d93ea40bc9a16ba518df6/components/Settings.php#L58-L67 |
yii2mod/yii2-settings | components/Settings.php | Settings.getAllBySection | public function getAllBySection($section, $default = null)
{
$items = $this->getSettingsConfig();
if (isset($items[$section])) {
$this->setting = ArrayHelper::getColumn($items[$section], 'value');
} else {
$this->setting = $default;
}
return $this->setting;
} | php | public function getAllBySection($section, $default = null)
{
$items = $this->getSettingsConfig();
if (isset($items[$section])) {
$this->setting = ArrayHelper::getColumn($items[$section], 'value');
} else {
$this->setting = $default;
}
return $this->setting;
} | [
"public",
"function",
"getAllBySection",
"(",
"$",
"section",
",",
"$",
"default",
"=",
"null",
")",
"{",
"$",
"items",
"=",
"$",
"this",
"->",
"getSettingsConfig",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"items",
"[",
"$",
"section",
"]",
")",
... | Get's all values in the specific section.
@param string $section
@param null $default
@return mixed | [
"Get",
"s",
"all",
"values",
"in",
"the",
"specific",
"section",
"."
] | train | https://github.com/yii2mod/yii2-settings/blob/5e61cf4de48c7d61fd6d93ea40bc9a16ba518df6/components/Settings.php#L77-L88 |
yii2mod/yii2-settings | components/Settings.php | Settings.get | public function get($section, $key, $default = null)
{
$items = $this->getSettingsConfig();
if (isset($items[$section][$key])) {
$this->setting = ArrayHelper::getValue($items[$section][$key], 'value');
$type = ArrayHelper::getValue($items[$section][$key], 'type');
$this->convertSettingType($type);
} else {
$this->setting = $default;
}
return $this->setting;
} | php | public function get($section, $key, $default = null)
{
$items = $this->getSettingsConfig();
if (isset($items[$section][$key])) {
$this->setting = ArrayHelper::getValue($items[$section][$key], 'value');
$type = ArrayHelper::getValue($items[$section][$key], 'type');
$this->convertSettingType($type);
} else {
$this->setting = $default;
}
return $this->setting;
} | [
"public",
"function",
"get",
"(",
"$",
"section",
",",
"$",
"key",
",",
"$",
"default",
"=",
"null",
")",
"{",
"$",
"items",
"=",
"$",
"this",
"->",
"getSettingsConfig",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"items",
"[",
"$",
"section",
"... | Get's the value for the given section and key.
@param string $section
@param string $key
@param null $default
@return mixed | [
"Get",
"s",
"the",
"value",
"for",
"the",
"given",
"section",
"and",
"key",
"."
] | train | https://github.com/yii2mod/yii2-settings/blob/5e61cf4de48c7d61fd6d93ea40bc9a16ba518df6/components/Settings.php#L99-L112 |
yii2mod/yii2-settings | components/Settings.php | Settings.set | public function set($section, $key, $value, $type = null): bool
{
if ($this->model->setSetting($section, $key, $value, $type)) {
if ($this->invalidateCache()) {
return true;
}
}
return false;
} | php | public function set($section, $key, $value, $type = null): bool
{
if ($this->model->setSetting($section, $key, $value, $type)) {
if ($this->invalidateCache()) {
return true;
}
}
return false;
} | [
"public",
"function",
"set",
"(",
"$",
"section",
",",
"$",
"key",
",",
"$",
"value",
",",
"$",
"type",
"=",
"null",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"this",
"->",
"model",
"->",
"setSetting",
"(",
"$",
"section",
",",
"$",
"key",
",",
"$... | Add a new setting or update an existing one.
@param null $section
@param string $key
@param string $value
@param null $type
@return bool | [
"Add",
"a",
"new",
"setting",
"or",
"update",
"an",
"existing",
"one",
"."
] | train | https://github.com/yii2mod/yii2-settings/blob/5e61cf4de48c7d61fd6d93ea40bc9a16ba518df6/components/Settings.php#L124-L133 |
yii2mod/yii2-settings | components/Settings.php | Settings.has | public function has($section, $key): bool
{
$setting = $this->get($section, $key);
return !empty($setting);
} | php | public function has($section, $key): bool
{
$setting = $this->get($section, $key);
return !empty($setting);
} | [
"public",
"function",
"has",
"(",
"$",
"section",
",",
"$",
"key",
")",
":",
"bool",
"{",
"$",
"setting",
"=",
"$",
"this",
"->",
"get",
"(",
"$",
"section",
",",
"$",
"key",
")",
";",
"return",
"!",
"empty",
"(",
"$",
"setting",
")",
";",
"}"
... | Checking existence of setting
@param string $section
@param string $key
@return bool | [
"Checking",
"existence",
"of",
"setting"
] | train | https://github.com/yii2mod/yii2-settings/blob/5e61cf4de48c7d61fd6d93ea40bc9a16ba518df6/components/Settings.php#L143-L148 |
yii2mod/yii2-settings | components/Settings.php | Settings.remove | public function remove($section, $key): bool
{
if ($this->model->removeSetting($section, $key)) {
if ($this->invalidateCache()) {
return true;
}
}
return false;
} | php | public function remove($section, $key): bool
{
if ($this->model->removeSetting($section, $key)) {
if ($this->invalidateCache()) {
return true;
}
}
return false;
} | [
"public",
"function",
"remove",
"(",
"$",
"section",
",",
"$",
"key",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"this",
"->",
"model",
"->",
"removeSetting",
"(",
"$",
"section",
",",
"$",
"key",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"invalid... | Remove setting by section and key
@param string $section
@param string $key
@return bool | [
"Remove",
"setting",
"by",
"section",
"and",
"key"
] | train | https://github.com/yii2mod/yii2-settings/blob/5e61cf4de48c7d61fd6d93ea40bc9a16ba518df6/components/Settings.php#L158-L167 |
yii2mod/yii2-settings | components/Settings.php | Settings.getSettingsConfig | protected function getSettingsConfig(): array
{
if (!$this->cache instanceof Cache) {
$this->items = $this->model->getSettings();
} else {
$cacheItems = $this->cache->get($this->cacheKey);
if (!empty($cacheItems)) {
$this->items = $cacheItems;
} else {
$this->items = $this->model->getSettings();
$this->cache->set($this->cacheKey, $this->items);
}
}
return $this->items;
} | php | protected function getSettingsConfig(): array
{
if (!$this->cache instanceof Cache) {
$this->items = $this->model->getSettings();
} else {
$cacheItems = $this->cache->get($this->cacheKey);
if (!empty($cacheItems)) {
$this->items = $cacheItems;
} else {
$this->items = $this->model->getSettings();
$this->cache->set($this->cacheKey, $this->items);
}
}
return $this->items;
} | [
"protected",
"function",
"getSettingsConfig",
"(",
")",
":",
"array",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"cache",
"instanceof",
"Cache",
")",
"{",
"$",
"this",
"->",
"items",
"=",
"$",
"this",
"->",
"model",
"->",
"getSettings",
"(",
")",
";",
"... | Returns the settings config
@return array | [
"Returns",
"the",
"settings",
"config"
] | train | https://github.com/yii2mod/yii2-settings/blob/5e61cf4de48c7d61fd6d93ea40bc9a16ba518df6/components/Settings.php#L210-L225 |
yii2mod/yii2-settings | components/Settings.php | Settings.invalidateCache | public function invalidateCache(): bool
{
if ($this->cache !== null) {
$this->cache->delete($this->cacheKey);
$this->items = null;
}
return true;
} | php | public function invalidateCache(): bool
{
if ($this->cache !== null) {
$this->cache->delete($this->cacheKey);
$this->items = null;
}
return true;
} | [
"public",
"function",
"invalidateCache",
"(",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"this",
"->",
"cache",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"cache",
"->",
"delete",
"(",
"$",
"this",
"->",
"cacheKey",
")",
";",
"$",
"this",
"->",
"items... | Invalidate the cache
@return bool | [
"Invalidate",
"the",
"cache"
] | train | https://github.com/yii2mod/yii2-settings/blob/5e61cf4de48c7d61fd6d93ea40bc9a16ba518df6/components/Settings.php#L232-L240 |
yii2mod/yii2-settings | components/Settings.php | Settings.convertSettingType | protected function convertSettingType($type)
{
if ($type === SettingType::BOOLEAN_TYPE) {
$this->setting = filter_var($this->setting, FILTER_VALIDATE_BOOLEAN);
} else {
settype($this->setting, $type);
}
} | php | protected function convertSettingType($type)
{
if ($type === SettingType::BOOLEAN_TYPE) {
$this->setting = filter_var($this->setting, FILTER_VALIDATE_BOOLEAN);
} else {
settype($this->setting, $type);
}
} | [
"protected",
"function",
"convertSettingType",
"(",
"$",
"type",
")",
"{",
"if",
"(",
"$",
"type",
"===",
"SettingType",
"::",
"BOOLEAN_TYPE",
")",
"{",
"$",
"this",
"->",
"setting",
"=",
"filter_var",
"(",
"$",
"this",
"->",
"setting",
",",
"FILTER_VALIDA... | Set type for setting
@param $type | [
"Set",
"type",
"for",
"setting"
] | train | https://github.com/yii2mod/yii2-settings/blob/5e61cf4de48c7d61fd6d93ea40bc9a16ba518df6/components/Settings.php#L247-L254 |
yii2mod/yii2-settings | models/SettingModel.php | SettingModel.getSettings | public function getSettings(): array
{
$result = [];
$settings = static::find()->select(['type', 'section', 'key', 'value'])->active()->asArray()->all();
foreach ($settings as $setting) {
$section = $setting['section'];
$key = $setting['key'];
$settingOptions = ['type' => $setting['type'], 'value' => $setting['value']];
if (isset($result[$section][$key])) {
ArrayHelper::merge($result[$section][$key], $settingOptions);
} else {
$result[$section][$key] = $settingOptions;
}
}
return $result;
} | php | public function getSettings(): array
{
$result = [];
$settings = static::find()->select(['type', 'section', 'key', 'value'])->active()->asArray()->all();
foreach ($settings as $setting) {
$section = $setting['section'];
$key = $setting['key'];
$settingOptions = ['type' => $setting['type'], 'value' => $setting['value']];
if (isset($result[$section][$key])) {
ArrayHelper::merge($result[$section][$key], $settingOptions);
} else {
$result[$section][$key] = $settingOptions;
}
}
return $result;
} | [
"public",
"function",
"getSettings",
"(",
")",
":",
"array",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"settings",
"=",
"static",
"::",
"find",
"(",
")",
"->",
"select",
"(",
"[",
"'type'",
",",
"'section'",
",",
"'key'",
",",
"'value'",
"]",
")... | Return array of settings
@return array | [
"Return",
"array",
"of",
"settings"
] | train | https://github.com/yii2mod/yii2-settings/blob/5e61cf4de48c7d61fd6d93ea40bc9a16ba518df6/models/SettingModel.php#L115-L133 |
yii2mod/yii2-settings | models/SettingModel.php | SettingModel.setSetting | public function setSetting($section, $key, $value, $type = null): bool
{
$model = static::findOne(['section' => $section, 'key' => $key]);
if (empty($model)) {
$model = new static();
}
$model->section = $section;
$model->key = $key;
$model->value = strval($value);
if ($type !== null && ArrayHelper::keyExists($type, SettingType::getConstantsByValue())) {
$model->type = $type;
} else {
$model->type = gettype($value);
}
return $model->save();
} | php | public function setSetting($section, $key, $value, $type = null): bool
{
$model = static::findOne(['section' => $section, 'key' => $key]);
if (empty($model)) {
$model = new static();
}
$model->section = $section;
$model->key = $key;
$model->value = strval($value);
if ($type !== null && ArrayHelper::keyExists($type, SettingType::getConstantsByValue())) {
$model->type = $type;
} else {
$model->type = gettype($value);
}
return $model->save();
} | [
"public",
"function",
"setSetting",
"(",
"$",
"section",
",",
"$",
"key",
",",
"$",
"value",
",",
"$",
"type",
"=",
"null",
")",
":",
"bool",
"{",
"$",
"model",
"=",
"static",
"::",
"findOne",
"(",
"[",
"'section'",
"=>",
"$",
"section",
",",
"'key... | Set setting
@param $section
@param $key
@param $value
@param null $type
@return bool | [
"Set",
"setting"
] | train | https://github.com/yii2mod/yii2-settings/blob/5e61cf4de48c7d61fd6d93ea40bc9a16ba518df6/models/SettingModel.php#L145-L164 |
yii2mod/yii2-settings | models/SettingModel.php | SettingModel.removeSetting | public function removeSetting($section, $key)
{
$model = static::findOne(['section' => $section, 'key' => $key]);
if (!empty($model)) {
return $model->delete();
}
return false;
} | php | public function removeSetting($section, $key)
{
$model = static::findOne(['section' => $section, 'key' => $key]);
if (!empty($model)) {
return $model->delete();
}
return false;
} | [
"public",
"function",
"removeSetting",
"(",
"$",
"section",
",",
"$",
"key",
")",
"{",
"$",
"model",
"=",
"static",
"::",
"findOne",
"(",
"[",
"'section'",
"=>",
"$",
"section",
",",
"'key'",
"=>",
"$",
"key",
"]",
")",
";",
"if",
"(",
"!",
"empty"... | Remove setting
@param $section
@param $key
@return bool|int|null
@throws \Exception | [
"Remove",
"setting"
] | train | https://github.com/yii2mod/yii2-settings/blob/5e61cf4de48c7d61fd6d93ea40bc9a16ba518df6/models/SettingModel.php#L176-L185 |
yii2mod/yii2-settings | models/SettingModel.php | SettingModel.activateSetting | public function activateSetting($section, $key): bool
{
$model = static::findOne(['section' => $section, 'key' => $key]);
if ($model && $model->status === SettingStatus::INACTIVE) {
$model->status = SettingStatus::ACTIVE;
return $model->save(true, ['status']);
}
return false;
} | php | public function activateSetting($section, $key): bool
{
$model = static::findOne(['section' => $section, 'key' => $key]);
if ($model && $model->status === SettingStatus::INACTIVE) {
$model->status = SettingStatus::ACTIVE;
return $model->save(true, ['status']);
}
return false;
} | [
"public",
"function",
"activateSetting",
"(",
"$",
"section",
",",
"$",
"key",
")",
":",
"bool",
"{",
"$",
"model",
"=",
"static",
"::",
"findOne",
"(",
"[",
"'section'",
"=>",
"$",
"section",
",",
"'key'",
"=>",
"$",
"key",
"]",
")",
";",
"if",
"(... | Activates a setting
@param $section
@param $key
@return bool | [
"Activates",
"a",
"setting"
] | train | https://github.com/yii2mod/yii2-settings/blob/5e61cf4de48c7d61fd6d93ea40bc9a16ba518df6/models/SettingModel.php#L205-L216 |
grasmash/yaml-expander | src/Expander.php | Expander.expandArrayProperties | public static function expandArrayProperties($array, $reference_array = [])
{
$data = new Data($array);
if ($reference_array) {
$reference_data = new Data($reference_array);
self::doExpandArrayProperties($data, $array, '', $reference_data);
} else {
self::doExpandArrayProperties($data, $array);
}
return $data->export();
} | php | public static function expandArrayProperties($array, $reference_array = [])
{
$data = new Data($array);
if ($reference_array) {
$reference_data = new Data($reference_array);
self::doExpandArrayProperties($data, $array, '', $reference_data);
} else {
self::doExpandArrayProperties($data, $array);
}
return $data->export();
} | [
"public",
"static",
"function",
"expandArrayProperties",
"(",
"$",
"array",
",",
"$",
"reference_array",
"=",
"[",
"]",
")",
"{",
"$",
"data",
"=",
"new",
"Data",
"(",
"$",
"array",
")",
";",
"if",
"(",
"$",
"reference_array",
")",
"{",
"$",
"reference... | Expands property placeholders in an array.
Placeholders should formatted as ${parent.child}.
@param array $array
An array containing properties to expand.
@return array
The modified array in which placeholders have been replaced with
values. | [
"Expands",
"property",
"placeholders",
"in",
"an",
"array",
"."
] | train | https://github.com/grasmash/yaml-expander/blob/07d39a898da7a7317deae2aa3ee982f86346ab2d/src/Expander.php#L49-L60 |
grasmash/yaml-expander | src/Expander.php | Expander.expandPropertyWithReferenceData | public static function expandPropertyWithReferenceData(
$property_name,
$unexpanded_value,
$data,
$reference_data
) {
$expanded_value = self::expandProperty(
$property_name,
$unexpanded_value,
$data
);
// If the string was not changed using the subject data, try using
// the reference data.
if ($expanded_value == $unexpanded_value) {
$expanded_value = self::expandProperty(
$property_name,
$unexpanded_value,
$reference_data
);
}
return $expanded_value;
} | php | public static function expandPropertyWithReferenceData(
$property_name,
$unexpanded_value,
$data,
$reference_data
) {
$expanded_value = self::expandProperty(
$property_name,
$unexpanded_value,
$data
);
// If the string was not changed using the subject data, try using
// the reference data.
if ($expanded_value == $unexpanded_value) {
$expanded_value = self::expandProperty(
$property_name,
$unexpanded_value,
$reference_data
);
}
return $expanded_value;
} | [
"public",
"static",
"function",
"expandPropertyWithReferenceData",
"(",
"$",
"property_name",
",",
"$",
"unexpanded_value",
",",
"$",
"data",
",",
"$",
"reference_data",
")",
"{",
"$",
"expanded_value",
"=",
"self",
"::",
"expandProperty",
"(",
"$",
"property_name... | Searches both the subject data and the reference data for value.
@param string $property_name
The name of the value for which to search.
@param string $unexpanded_value
The original, unexpanded value, containing the placeholder.
@param Data $data
A data object containing the complete array being operated upon.
@param Data|null $reference_data
A reference data object. This is not operated upon but is used as a
reference to provide supplemental values for property expansion.
@return string
The expanded string. | [
"Searches",
"both",
"the",
"subject",
"data",
"and",
"the",
"reference",
"data",
"for",
"value",
"."
] | train | https://github.com/grasmash/yaml-expander/blob/07d39a898da7a7317deae2aa3ee982f86346ab2d/src/Expander.php#L206-L228 |
grasmash/yaml-expander | src/Expander.php | Expander.expandProperty | public static function expandProperty($property_name, $unexpanded_value, $data)
{
if (strpos($property_name, "env.") === 0 &&
!$data->has($property_name)) {
$env_key = substr($property_name, 4);
if (getenv($env_key)) {
$data->set($property_name, getenv($env_key));
}
}
if (!$data->has($property_name)) {
self::log("Property \${'$property_name'} could not be expanded.");
return $unexpanded_value;
} else {
$expanded_value = $data->get($property_name);
if (is_array($expanded_value)) {
$expanded_value = Yaml::dump($expanded_value, 0);
return $expanded_value;
}
self::log("Expanding property \${'$property_name'} => $expanded_value.");
return $expanded_value;
}
} | php | public static function expandProperty($property_name, $unexpanded_value, $data)
{
if (strpos($property_name, "env.") === 0 &&
!$data->has($property_name)) {
$env_key = substr($property_name, 4);
if (getenv($env_key)) {
$data->set($property_name, getenv($env_key));
}
}
if (!$data->has($property_name)) {
self::log("Property \${'$property_name'} could not be expanded.");
return $unexpanded_value;
} else {
$expanded_value = $data->get($property_name);
if (is_array($expanded_value)) {
$expanded_value = Yaml::dump($expanded_value, 0);
return $expanded_value;
}
self::log("Expanding property \${'$property_name'} => $expanded_value.");
return $expanded_value;
}
} | [
"public",
"static",
"function",
"expandProperty",
"(",
"$",
"property_name",
",",
"$",
"unexpanded_value",
",",
"$",
"data",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"property_name",
",",
"\"env.\"",
")",
"===",
"0",
"&&",
"!",
"$",
"data",
"->",
"has",
... | Searches a data object for a value.
@param string $property_name
The name of the value for which to search.
@param string $unexpanded_value
The original, unexpanded value, containing the placeholder.
@param Data $data
A data object containing possible replacement values.
@return mixed | [
"Searches",
"a",
"data",
"object",
"for",
"a",
"value",
"."
] | train | https://github.com/grasmash/yaml-expander/blob/07d39a898da7a7317deae2aa3ee982f86346ab2d/src/Expander.php#L242-L264 |
oat-sa/extension-tao-itemqti | model/qti/asset/handler/PortableAssetHandler.php | PortableAssetHandler.isApplicable | public function isApplicable($relativePath)
{
//adapt the file path before comparing them to expected files
$relativePathAdapted = preg_replace('/^\.\//', '', $relativePath);
if ($this->portableItemParser->hasPortableElement()
&& $this->portableItemParser->isPortableElementAsset($relativePathAdapted)
) {
return true;
}
return false;
} | php | public function isApplicable($relativePath)
{
//adapt the file path before comparing them to expected files
$relativePathAdapted = preg_replace('/^\.\//', '', $relativePath);
if ($this->portableItemParser->hasPortableElement()
&& $this->portableItemParser->isPortableElementAsset($relativePathAdapted)
) {
return true;
}
return false;
} | [
"public",
"function",
"isApplicable",
"(",
"$",
"relativePath",
")",
"{",
"//adapt the file path before comparing them to expected files",
"$",
"relativePathAdapted",
"=",
"preg_replace",
"(",
"'/^\\.\\//'",
",",
"''",
",",
"$",
"relativePath",
")",
";",
"if",
"(",
"$... | Check if given file is into pci and required by this pci
@param $relativePath
@return bool | [
"Check",
"if",
"given",
"file",
"is",
"into",
"pci",
"and",
"required",
"by",
"this",
"pci"
] | train | https://github.com/oat-sa/extension-tao-itemqti/blob/a55b73c7894523bde169ba520d5001ce7b5bb88c/model/qti/asset/handler/PortableAssetHandler.php#L57-L67 |
oat-sa/extension-tao-itemqti | model/qti/asset/handler/PortableAssetHandler.php | PortableAssetHandler.handle | public function handle($absolutePath, $relativePath)
{
//adapt the file path before comparing them to expected files
$relativePathAdapted = preg_replace('/^\.\//', '', $relativePath);
return $this->portableItemParser->importPortableElementFile($absolutePath, $relativePathAdapted);
} | php | public function handle($absolutePath, $relativePath)
{
//adapt the file path before comparing them to expected files
$relativePathAdapted = preg_replace('/^\.\//', '', $relativePath);
return $this->portableItemParser->importPortableElementFile($absolutePath, $relativePathAdapted);
} | [
"public",
"function",
"handle",
"(",
"$",
"absolutePath",
",",
"$",
"relativePath",
")",
"{",
"//adapt the file path before comparing them to expected files",
"$",
"relativePathAdapted",
"=",
"preg_replace",
"(",
"'/^\\.\\//'",
",",
"''",
",",
"$",
"relativePath",
")",
... | Handle Pci asset import
@param $absolutePath
@param $relativePath
@return mixed | [
"Handle",
"Pci",
"asset",
"import"
] | train | https://github.com/oat-sa/extension-tao-itemqti/blob/a55b73c7894523bde169ba520d5001ce7b5bb88c/model/qti/asset/handler/PortableAssetHandler.php#L76-L81 |
oat-sa/extension-tao-itemqti | model/qti/ImportService.php | ImportService.importQTIFile | public function importQTIFile($qtiFile, core_kernel_classes_Class $itemClass, $validate = true)
{
$report = null;
try {
$qtiModel = $this->createQtiItemModel($qtiFile, $validate);
$rdfItem = $this->createRdfItem($itemClass, $qtiModel);
$report = \common_report_Report::createSuccess(__('The IMS QTI Item was successfully imported.'), $rdfItem);
} catch (ValidationException $ve) {
$report = \common_report_Report::createFailure(__('The IMS QTI Item could not be imported.'));
$report->add($ve->getReport());
}
return $report;
} | php | public function importQTIFile($qtiFile, core_kernel_classes_Class $itemClass, $validate = true)
{
$report = null;
try {
$qtiModel = $this->createQtiItemModel($qtiFile, $validate);
$rdfItem = $this->createRdfItem($itemClass, $qtiModel);
$report = \common_report_Report::createSuccess(__('The IMS QTI Item was successfully imported.'), $rdfItem);
} catch (ValidationException $ve) {
$report = \common_report_Report::createFailure(__('The IMS QTI Item could not be imported.'));
$report->add($ve->getReport());
}
return $report;
} | [
"public",
"function",
"importQTIFile",
"(",
"$",
"qtiFile",
",",
"core_kernel_classes_Class",
"$",
"itemClass",
",",
"$",
"validate",
"=",
"true",
")",
"{",
"$",
"report",
"=",
"null",
";",
"try",
"{",
"$",
"qtiModel",
"=",
"$",
"this",
"->",
"createQtiIte... | Short description of method importQTIFile
@access public
@author Joel Bout, <joel.bout@tudor.lu>
@param $qtiFile
@param core_kernel_classes_Class $itemClass
@param bool $validate
@throws \common_Exception
@throws \common_ext_ExtensionException
@throws common_exception_Error
@return common_report_Report | [
"Short",
"description",
"of",
"method",
"importQTIFile"
] | train | https://github.com/oat-sa/extension-tao-itemqti/blob/a55b73c7894523bde169ba520d5001ce7b5bb88c/model/qti/ImportService.php#L109-L126 |
oat-sa/extension-tao-itemqti | model/qti/ImportService.php | ImportService.importQTIPACKFile | public function importQTIPACKFile(
$file,
core_kernel_classes_Class $itemClass,
$validate = true,
$rollbackOnError = false,
$rollbackOnWarning = false,
$enableMetadataGuardians = true,
$enableMetadataValidators = true,
$itemMustExist = false,
$itemMustBeOverwritten = false
) {
$initialLogMsg = "Importing QTI Package with the following options:\n";
$initialLogMsg .= '- Rollback On Warning: ' . json_encode($rollbackOnWarning) . "\n";
$initialLogMsg .= '- Rollback On Error: ' . json_encode($rollbackOnError) . "\n";
$initialLogMsg .= '- Enable Metadata Guardians: ' . json_encode($enableMetadataGuardians) . "\n";
$initialLogMsg .= '- Enable Metadata Validators: ' . json_encode($enableMetadataValidators) . "\n";
$initialLogMsg .= '- Item Must Exist: ' . json_encode($itemMustExist) . "\n";
$initialLogMsg .= '- Item Must Be Overwritten: ' .json_encode($itemMustBeOverwritten) . "\n";
\common_Logger::d($initialLogMsg);
//load and validate the package
$qtiPackageParser = new PackageParser($file);
if ($validate) {
$qtiPackageParser->validate();
if (!$qtiPackageParser->isValid()) {
throw new ParsingException('Invalid QTI package format');
}
}
//extract the package
$folder = $qtiPackageParser->extract();
if (!is_dir($folder)) {
throw new ExtractException();
}
$report = new common_report_Report(common_report_Report::TYPE_SUCCESS, '');
$successItems = array();
$allCreatedClasses = array();
$overwrittenItems = array();
$itemCount = 0;
try {
// The metadata import feature needs a DOM representation of the manifest.
$domManifest = new DOMDocument('1.0', 'UTF-8');
$domManifest->load($folder . 'imsmanifest.xml');
/** @var Resource[] $qtiItemResources */
$qtiItemResources = $this->createQtiManifest($folder . 'imsmanifest.xml');
$metadataValues = $this->getMetadataImporter()->extract($domManifest);
$createdClasses = array();
foreach ($qtiItemResources as $qtiItemResource) {
$itemCount++;
$itemReport = $this->importQtiItem(
$folder,
$qtiItemResource,
$itemClass,
array(),
$metadataValues,
array(),
array(),
array(),
array(),
$createdClasses,
$enableMetadataGuardians,
$enableMetadataValidators,
$itemMustExist,
$itemMustBeOverwritten,
$overwrittenItems
);
$allCreatedClasses = array_merge($allCreatedClasses, $createdClasses);
$rdfItem = $itemReport->getData();
if ($rdfItem) {
$successItems[$qtiItemResource->getIdentifier()] = $rdfItem;
}
$report->add($itemReport);
}
} catch (ValidationException $ve) {
$validationReport = \common_report_Report::createFailure("The IMS Manifest file could not be validated");
$validationReport->add($ve->getReport());
$report->setMessage(__("No Items could be imported from the given IMS QTI package."));
$report->setType(common_report_Report::TYPE_ERROR);
$report->add($validationReport);
} catch (common_exception_UserReadableException $e) {
$report = new common_report_Report(common_report_Report::TYPE_ERROR, $e->getUserMessage());
$report->add($e);
}
if (!empty($successItems)) {
// Some items were imported from the package.
$report->setMessage(__('%d Item(s) of %d imported from the given IMS QTI Package.', count($successItems),
$itemCount));
if (count($successItems) !== $itemCount) {
$report->setType(common_report_Report::TYPE_WARNING);
}
} else {
$report->setMessage(__('No Items could be imported from the given IMS QTI package.'));
$report->setType(common_report_Report::TYPE_ERROR);
}
if ($rollbackOnError === true) {
if ($report->getType() === common_report_Report::TYPE_ERROR || $report->contains(common_report_Report::TYPE_ERROR)) {
$this->rollback($successItems, $report, $allCreatedClasses, $overwrittenItems);
}
} elseif ($rollbackOnWarning === true) {
if ($report->contains(common_report_Report::TYPE_WARNING)) {
$this->rollback($successItems, $report, $allCreatedClasses, $overwrittenItems);
}
}
// cleanup
tao_helpers_File::delTree($folder);
return $report;
} | php | public function importQTIPACKFile(
$file,
core_kernel_classes_Class $itemClass,
$validate = true,
$rollbackOnError = false,
$rollbackOnWarning = false,
$enableMetadataGuardians = true,
$enableMetadataValidators = true,
$itemMustExist = false,
$itemMustBeOverwritten = false
) {
$initialLogMsg = "Importing QTI Package with the following options:\n";
$initialLogMsg .= '- Rollback On Warning: ' . json_encode($rollbackOnWarning) . "\n";
$initialLogMsg .= '- Rollback On Error: ' . json_encode($rollbackOnError) . "\n";
$initialLogMsg .= '- Enable Metadata Guardians: ' . json_encode($enableMetadataGuardians) . "\n";
$initialLogMsg .= '- Enable Metadata Validators: ' . json_encode($enableMetadataValidators) . "\n";
$initialLogMsg .= '- Item Must Exist: ' . json_encode($itemMustExist) . "\n";
$initialLogMsg .= '- Item Must Be Overwritten: ' .json_encode($itemMustBeOverwritten) . "\n";
\common_Logger::d($initialLogMsg);
//load and validate the package
$qtiPackageParser = new PackageParser($file);
if ($validate) {
$qtiPackageParser->validate();
if (!$qtiPackageParser->isValid()) {
throw new ParsingException('Invalid QTI package format');
}
}
//extract the package
$folder = $qtiPackageParser->extract();
if (!is_dir($folder)) {
throw new ExtractException();
}
$report = new common_report_Report(common_report_Report::TYPE_SUCCESS, '');
$successItems = array();
$allCreatedClasses = array();
$overwrittenItems = array();
$itemCount = 0;
try {
// The metadata import feature needs a DOM representation of the manifest.
$domManifest = new DOMDocument('1.0', 'UTF-8');
$domManifest->load($folder . 'imsmanifest.xml');
/** @var Resource[] $qtiItemResources */
$qtiItemResources = $this->createQtiManifest($folder . 'imsmanifest.xml');
$metadataValues = $this->getMetadataImporter()->extract($domManifest);
$createdClasses = array();
foreach ($qtiItemResources as $qtiItemResource) {
$itemCount++;
$itemReport = $this->importQtiItem(
$folder,
$qtiItemResource,
$itemClass,
array(),
$metadataValues,
array(),
array(),
array(),
array(),
$createdClasses,
$enableMetadataGuardians,
$enableMetadataValidators,
$itemMustExist,
$itemMustBeOverwritten,
$overwrittenItems
);
$allCreatedClasses = array_merge($allCreatedClasses, $createdClasses);
$rdfItem = $itemReport->getData();
if ($rdfItem) {
$successItems[$qtiItemResource->getIdentifier()] = $rdfItem;
}
$report->add($itemReport);
}
} catch (ValidationException $ve) {
$validationReport = \common_report_Report::createFailure("The IMS Manifest file could not be validated");
$validationReport->add($ve->getReport());
$report->setMessage(__("No Items could be imported from the given IMS QTI package."));
$report->setType(common_report_Report::TYPE_ERROR);
$report->add($validationReport);
} catch (common_exception_UserReadableException $e) {
$report = new common_report_Report(common_report_Report::TYPE_ERROR, $e->getUserMessage());
$report->add($e);
}
if (!empty($successItems)) {
// Some items were imported from the package.
$report->setMessage(__('%d Item(s) of %d imported from the given IMS QTI Package.', count($successItems),
$itemCount));
if (count($successItems) !== $itemCount) {
$report->setType(common_report_Report::TYPE_WARNING);
}
} else {
$report->setMessage(__('No Items could be imported from the given IMS QTI package.'));
$report->setType(common_report_Report::TYPE_ERROR);
}
if ($rollbackOnError === true) {
if ($report->getType() === common_report_Report::TYPE_ERROR || $report->contains(common_report_Report::TYPE_ERROR)) {
$this->rollback($successItems, $report, $allCreatedClasses, $overwrittenItems);
}
} elseif ($rollbackOnWarning === true) {
if ($report->contains(common_report_Report::TYPE_WARNING)) {
$this->rollback($successItems, $report, $allCreatedClasses, $overwrittenItems);
}
}
// cleanup
tao_helpers_File::delTree($folder);
return $report;
} | [
"public",
"function",
"importQTIPACKFile",
"(",
"$",
"file",
",",
"core_kernel_classes_Class",
"$",
"itemClass",
",",
"$",
"validate",
"=",
"true",
",",
"$",
"rollbackOnError",
"=",
"false",
",",
"$",
"rollbackOnWarning",
"=",
"false",
",",
"$",
"enableMetadataG... | imports a qti package and
returns the number of items imported
@access public
@author Joel Bout, <joel.bout@tudor.lu>
@param $file
@param core_kernel_classes_Class $itemClass
@param bool $validate
@param bool $rollbackOnError
@param bool $rollbackOnWarning
@param bool $enableMetadataGuardians
@param bool $enableMetadataValidators
@param bool $itemMustExist
@param bool $itemMustBeOverwritten
@throws Exception
@throws ExtractException
@throws ParsingException
@throws \common_Exception
@throws \common_ext_ExtensionException
@throws common_exception_Error
@return common_report_Report | [
"imports",
"a",
"qti",
"package",
"and",
"returns",
"the",
"number",
"of",
"items",
"imported"
] | train | https://github.com/oat-sa/extension-tao-itemqti/blob/a55b73c7894523bde169ba520d5001ce7b5bb88c/model/qti/ImportService.php#L260-L382 |
oat-sa/extension-tao-itemqti | model/qti/ImportService.php | ImportService.importResourceMetadata | public function importResourceMetadata(
array $metadataValues,
Resource $qtiResource,
core_kernel_classes_Resource $resource,
array $ontologyInjectors = array()
) {
// Filter metadata values for this given item.
$identifier = $qtiResource->getIdentifier();
if (isset($metadataValues[$identifier]) === true) {
\common_Logger::i("Preparing Metadata Values for resource '${identifier}'...");
$values = $metadataValues[$identifier];
foreach ($ontologyInjectors as $injector) {
$valuesCount = count($values);
$injectorClass = get_class($injector);
\common_Logger::i("Attempting to inject ${valuesCount} Metadata Values in database for resource '${identifier}' with Metadata Injector '${injectorClass}'.");
$injector->inject($resource, array($identifier => $values));
}
}
} | php | public function importResourceMetadata(
array $metadataValues,
Resource $qtiResource,
core_kernel_classes_Resource $resource,
array $ontologyInjectors = array()
) {
// Filter metadata values for this given item.
$identifier = $qtiResource->getIdentifier();
if (isset($metadataValues[$identifier]) === true) {
\common_Logger::i("Preparing Metadata Values for resource '${identifier}'...");
$values = $metadataValues[$identifier];
foreach ($ontologyInjectors as $injector) {
$valuesCount = count($values);
$injectorClass = get_class($injector);
\common_Logger::i("Attempting to inject ${valuesCount} Metadata Values in database for resource '${identifier}' with Metadata Injector '${injectorClass}'.");
$injector->inject($resource, array($identifier => $values));
}
}
} | [
"public",
"function",
"importResourceMetadata",
"(",
"array",
"$",
"metadataValues",
",",
"Resource",
"$",
"qtiResource",
",",
"core_kernel_classes_Resource",
"$",
"resource",
",",
"array",
"$",
"ontologyInjectors",
"=",
"array",
"(",
")",
")",
"{",
"// Filter metad... | Import metadata to a given QTI Item.
@deprecated use MetadataService::getImporter::inject()
@param MetadataValue[] $metadataValues An array of MetadataValue objects.
@param Resource $qtiResource The object representing the QTI Resource, from an IMS Manifest perspective.
@param core_kernel_classes_Resource $resource The object representing the target QTI Item in the Ontology.
@param MetadataInjector[] $ontologyInjectors Implementations of MetadataInjector that will take care to inject the metadata values in the appropriate Ontology Resource Properties.
@throws MetadataInjectionException If an error occurs while importing the metadata. | [
"Import",
"metadata",
"to",
"a",
"given",
"QTI",
"Item",
"."
] | train | https://github.com/oat-sa/extension-tao-itemqti/blob/a55b73c7894523bde169ba520d5001ce7b5bb88c/model/qti/ImportService.php#L691-L710 |
oat-sa/extension-tao-itemqti | model/qti/ImportService.php | ImportService.getMetadataImporter | protected function getMetadataImporter()
{
if (! $this->metadataImporter) {
$this->metadataImporter = $this->getServiceLocator()->get(MetadataService::SERVICE_ID)->getImporter();
}
return $this->metadataImporter;
} | php | protected function getMetadataImporter()
{
if (! $this->metadataImporter) {
$this->metadataImporter = $this->getServiceLocator()->get(MetadataService::SERVICE_ID)->getImporter();
}
return $this->metadataImporter;
} | [
"protected",
"function",
"getMetadataImporter",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"metadataImporter",
")",
"{",
"$",
"this",
"->",
"metadataImporter",
"=",
"$",
"this",
"->",
"getServiceLocator",
"(",
")",
"->",
"get",
"(",
"MetadataService",... | Get the lom metadata importer
@return MetadataImporter | [
"Get",
"the",
"lom",
"metadata",
"importer"
] | train | https://github.com/oat-sa/extension-tao-itemqti/blob/a55b73c7894523bde169ba520d5001ce7b5bb88c/model/qti/ImportService.php#L750-L756 |
oat-sa/extension-tao-itemqti | model/ItemModel.php | ItemModel.render | public function render( core_kernel_classes_Resource $item, $langCode)
{
$returnValue = (string) '';
$qitService = Service::singleton();
$qtiItem = $qitService->getDataItemByRdfItem($item, $langCode);
if(!is_null($qtiItem)) {
$returnValue = $qitService->renderQTIItem($qtiItem, $langCode);
} else {
common_Logger::w('No qti data for item '.$item->getUri().' in '.__FUNCTION__, 'taoQtiItem');
}
return (string) $returnValue;
} | php | public function render( core_kernel_classes_Resource $item, $langCode)
{
$returnValue = (string) '';
$qitService = Service::singleton();
$qtiItem = $qitService->getDataItemByRdfItem($item, $langCode);
if(!is_null($qtiItem)) {
$returnValue = $qitService->renderQTIItem($qtiItem, $langCode);
} else {
common_Logger::w('No qti data for item '.$item->getUri().' in '.__FUNCTION__, 'taoQtiItem');
}
return (string) $returnValue;
} | [
"public",
"function",
"render",
"(",
"core_kernel_classes_Resource",
"$",
"item",
",",
"$",
"langCode",
")",
"{",
"$",
"returnValue",
"=",
"(",
"string",
")",
"''",
";",
"$",
"qitService",
"=",
"Service",
"::",
"singleton",
"(",
")",
";",
"$",
"qtiItem",
... | render used for deploy and preview
@access public
@author Joel Bout, <joel@taotesting.com>
@param core_kernel_classes_Resource $item
@param $langCode
@throws \common_Exception
@return string | [
"render",
"used",
"for",
"deploy",
"and",
"preview"
] | train | https://github.com/oat-sa/extension-tao-itemqti/blob/a55b73c7894523bde169ba520d5001ce7b5bb88c/model/ItemModel.php#L81-L96 |
oat-sa/extension-tao-itemqti | model/qti/asset/handler/StimulusHandler.php | StimulusHandler.isApplicable | public function isApplicable($relativePath)
{
$xincluded = array();
/** @var Element $xincludeElement */
foreach ($this->getQtiItem()->getComposingElements('oat\taoQtiItem\model\qti\Xinclude') as $xincludeElement) {
$xincluded[] = $xincludeElement->attr('href');
\common_Logger::i("Xinclude component found in resource '" .
$this->getQtiItem()->getIdentifier() . "' with href '" . $xincludeElement->attr('href') . "'.");
}
return in_array($relativePath, $xincluded);
} | php | public function isApplicable($relativePath)
{
$xincluded = array();
/** @var Element $xincludeElement */
foreach ($this->getQtiItem()->getComposingElements('oat\taoQtiItem\model\qti\Xinclude') as $xincludeElement) {
$xincluded[] = $xincludeElement->attr('href');
\common_Logger::i("Xinclude component found in resource '" .
$this->getQtiItem()->getIdentifier() . "' with href '" . $xincludeElement->attr('href') . "'.");
}
return in_array($relativePath, $xincluded);
} | [
"public",
"function",
"isApplicable",
"(",
"$",
"relativePath",
")",
"{",
"$",
"xincluded",
"=",
"array",
"(",
")",
";",
"/** @var Element $xincludeElement */",
"foreach",
"(",
"$",
"this",
"->",
"getQtiItem",
"(",
")",
"->",
"getComposingElements",
"(",
"'oat\\... | Applicable to all items that contain <xinclude> tag
@param $relativePath
@return bool
@throws \common_exception_MissingParameter | [
"Applicable",
"to",
"all",
"items",
"that",
"contain",
"<xinclude",
">",
"tag"
] | train | https://github.com/oat-sa/extension-tao-itemqti/blob/a55b73c7894523bde169ba520d5001ce7b5bb88c/model/qti/asset/handler/StimulusHandler.php#L58-L69 |
oat-sa/extension-tao-itemqti | model/qti/asset/handler/StimulusHandler.php | StimulusHandler.handle | public function handle($absolutePath, $relativePath)
{
$safePath = $this->safePath($relativePath);
$this->encodeStimulusImages($absolutePath);
$info = $this->getItemSource()->add($absolutePath, basename($absolutePath), $safePath);
\common_Logger::i('Stimulus file \'' . $absolutePath . '\' copied.');
return $info;
} | php | public function handle($absolutePath, $relativePath)
{
$safePath = $this->safePath($relativePath);
$this->encodeStimulusImages($absolutePath);
$info = $this->getItemSource()->add($absolutePath, basename($absolutePath), $safePath);
\common_Logger::i('Stimulus file \'' . $absolutePath . '\' copied.');
return $info;
} | [
"public",
"function",
"handle",
"(",
"$",
"absolutePath",
",",
"$",
"relativePath",
")",
"{",
"$",
"safePath",
"=",
"$",
"this",
"->",
"safePath",
"(",
"$",
"relativePath",
")",
";",
"$",
"this",
"->",
"encodeStimulusImages",
"(",
"$",
"absolutePath",
")",... | Store locally, in a safe directory
Encoded all stimulus images to avoid file dependencies
@param $absolutePath
@param $relativePath
@return array|mixed
@throws \common_Exception | [
"Store",
"locally",
"in",
"a",
"safe",
"directory",
"Encoded",
"all",
"stimulus",
"images",
"to",
"avoid",
"file",
"dependencies"
] | train | https://github.com/oat-sa/extension-tao-itemqti/blob/a55b73c7894523bde169ba520d5001ce7b5bb88c/model/qti/asset/handler/StimulusHandler.php#L80-L89 |
oat-sa/extension-tao-itemqti | model/qti/asset/handler/StimulusHandler.php | StimulusHandler.safePath | protected function safePath($path)
{
$safePath = '';
if (dirname($path) !== '.') {
$safePath = str_replace('../', '', dirname($path)) . '/';
}
return $safePath;
} | php | protected function safePath($path)
{
$safePath = '';
if (dirname($path) !== '.') {
$safePath = str_replace('../', '', dirname($path)) . '/';
}
return $safePath;
} | [
"protected",
"function",
"safePath",
"(",
"$",
"path",
")",
"{",
"$",
"safePath",
"=",
"''",
";",
"if",
"(",
"dirname",
"(",
"$",
"path",
")",
"!==",
"'.'",
")",
"{",
"$",
"safePath",
"=",
"str_replace",
"(",
"'../'",
",",
"''",
",",
"dirname",
"("... | Remove ../ to secure path
@param $path
@return string | [
"Remove",
"..",
"/",
"to",
"secure",
"path"
] | train | https://github.com/oat-sa/extension-tao-itemqti/blob/a55b73c7894523bde169ba520d5001ce7b5bb88c/model/qti/asset/handler/StimulusHandler.php#L97-L104 |
oat-sa/extension-tao-itemqti | model/qti/asset/handler/StimulusHandler.php | StimulusHandler.encodeStimulusImages | protected function encodeStimulusImages($absolutePath)
{
if (!is_readable($absolutePath) || !is_writable($absolutePath)) {
throw new \common_Exception('Stimulus cannot be imported, asset file is not readable/writable.');
}
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->loadXML(file_get_contents($absolutePath));
$images = $dom->getElementsByTagName('img');
for($i=0 ; $i<$images->length ; $i++) {
$imageFile = dirname($absolutePath) . DIRECTORY_SEPARATOR . ltrim($images->item($i)->getAttribute('src'), DIRECTORY_SEPARATOR);
if (is_readable($imageFile)) {
$encodedSrc = 'data:image/png;base64,' . base64_encode(file_get_contents($imageFile));
$images->item($i)->setAttribute('src', $encodedSrc);
}
}
if (isset($encodedSrc)) {
file_put_contents($absolutePath, $dom->saveXML());
}
} | php | protected function encodeStimulusImages($absolutePath)
{
if (!is_readable($absolutePath) || !is_writable($absolutePath)) {
throw new \common_Exception('Stimulus cannot be imported, asset file is not readable/writable.');
}
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->loadXML(file_get_contents($absolutePath));
$images = $dom->getElementsByTagName('img');
for($i=0 ; $i<$images->length ; $i++) {
$imageFile = dirname($absolutePath) . DIRECTORY_SEPARATOR . ltrim($images->item($i)->getAttribute('src'), DIRECTORY_SEPARATOR);
if (is_readable($imageFile)) {
$encodedSrc = 'data:image/png;base64,' . base64_encode(file_get_contents($imageFile));
$images->item($i)->setAttribute('src', $encodedSrc);
}
}
if (isset($encodedSrc)) {
file_put_contents($absolutePath, $dom->saveXML());
}
} | [
"protected",
"function",
"encodeStimulusImages",
"(",
"$",
"absolutePath",
")",
"{",
"if",
"(",
"!",
"is_readable",
"(",
"$",
"absolutePath",
")",
"||",
"!",
"is_writable",
"(",
"$",
"absolutePath",
")",
")",
"{",
"throw",
"new",
"\\",
"common_Exception",
"(... | Walk into stimulus file to transform images from path to base64encoded data:image
@param $absolutePath
@throws \common_Exception | [
"Walk",
"into",
"stimulus",
"file",
"to",
"transform",
"images",
"from",
"path",
"to",
"base64encoded",
"data",
":",
"image"
] | train | https://github.com/oat-sa/extension-tao-itemqti/blob/a55b73c7894523bde169ba520d5001ce7b5bb88c/model/qti/asset/handler/StimulusHandler.php#L112-L131 |
oat-sa/extension-tao-itemqti | model/qti/interaction/Interaction.php | Interaction.getChoiceBySerial | public function getChoiceBySerial($serial){
$returnValue = null;
$choices = $this->getChoices();
if(isset($choices[$serial])){
$returnValue = $choices[$serial];
}
return $returnValue;
} | php | public function getChoiceBySerial($serial){
$returnValue = null;
$choices = $this->getChoices();
if(isset($choices[$serial])){
$returnValue = $choices[$serial];
}
return $returnValue;
} | [
"public",
"function",
"getChoiceBySerial",
"(",
"$",
"serial",
")",
"{",
"$",
"returnValue",
"=",
"null",
";",
"$",
"choices",
"=",
"$",
"this",
"->",
"getChoices",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"choices",
"[",
"$",
"serial",
"]",
")",... | Find a choice identified by its serial
@param string $serial
@return oat\taoQtiItem\model\qti\choice\Choice | [
"Find",
"a",
"choice",
"identified",
"by",
"its",
"serial"
] | train | https://github.com/oat-sa/extension-tao-itemqti/blob/a55b73c7894523bde169ba520d5001ce7b5bb88c/model/qti/interaction/Interaction.php#L83-L90 |
oat-sa/extension-tao-itemqti | model/qti/interaction/Interaction.php | Interaction.getResponse | public function getResponse(){
$returnValue = null;
$responseAttribute = $this->getAttribute('responseIdentifier');
if(!is_null($responseAttribute)){
$idenfierBaseType = $responseAttribute->getValue(true);
if(!is_null($idenfierBaseType)){
$returnValue = $idenfierBaseType->getReferencedObject();
}else{
$responseDeclaration = new ResponseDeclaration();
if($this->setResponse($responseDeclaration)){
$returnValue = $responseDeclaration;
}else{
throw new QtiModelException('cannot create the interaction response');
}
}
}
return $returnValue;
} | php | public function getResponse(){
$returnValue = null;
$responseAttribute = $this->getAttribute('responseIdentifier');
if(!is_null($responseAttribute)){
$idenfierBaseType = $responseAttribute->getValue(true);
if(!is_null($idenfierBaseType)){
$returnValue = $idenfierBaseType->getReferencedObject();
}else{
$responseDeclaration = new ResponseDeclaration();
if($this->setResponse($responseDeclaration)){
$returnValue = $responseDeclaration;
}else{
throw new QtiModelException('cannot create the interaction response');
}
}
}
return $returnValue;
} | [
"public",
"function",
"getResponse",
"(",
")",
"{",
"$",
"returnValue",
"=",
"null",
";",
"$",
"responseAttribute",
"=",
"$",
"this",
"->",
"getAttribute",
"(",
"'responseIdentifier'",
")",
";",
"if",
"(",
"!",
"is_null",
"(",
"$",
"responseAttribute",
")",
... | Get the response declaration associated to the interaction
If no response exists, one will be created
@access public
@author Sam, <sam@taotesting.com>
@return oat\taoQtiItem\model\qti\ResponseDeclaration | [
"Get",
"the",
"response",
"declaration",
"associated",
"to",
"the",
"interaction",
"If",
"no",
"response",
"exists",
"one",
"will",
"be",
"created"
] | train | https://github.com/oat-sa/extension-tao-itemqti/blob/a55b73c7894523bde169ba520d5001ce7b5bb88c/model/qti/interaction/Interaction.php#L190-L209 |
oat-sa/extension-tao-itemqti | model/qti/interaction/Interaction.php | Interaction.setResponse | public function setResponse(ResponseDeclaration $response){
$relatedItem = $this->getRelatedItem();
if(!is_null($relatedItem)){
$relatedItem->addResponse($response);
}
return $this->setAttribute('responseIdentifier', $response);
} | php | public function setResponse(ResponseDeclaration $response){
$relatedItem = $this->getRelatedItem();
if(!is_null($relatedItem)){
$relatedItem->addResponse($response);
}
return $this->setAttribute('responseIdentifier', $response);
} | [
"public",
"function",
"setResponse",
"(",
"ResponseDeclaration",
"$",
"response",
")",
"{",
"$",
"relatedItem",
"=",
"$",
"this",
"->",
"getRelatedItem",
"(",
")",
";",
"if",
"(",
"!",
"is_null",
"(",
"$",
"relatedItem",
")",
")",
"{",
"$",
"relatedItem",
... | Define the interaction's response
@access public
@author Sam, <sam@taotesting.com>
@param oat\taoQtiItem\model\qti\ResponseDeclaration response
@return mixed | [
"Define",
"the",
"interaction",
"s",
"response"
] | train | https://github.com/oat-sa/extension-tao-itemqti/blob/a55b73c7894523bde169ba520d5001ce7b5bb88c/model/qti/interaction/Interaction.php#L219-L225 |
oat-sa/extension-tao-itemqti | model/qti/interaction/Interaction.php | Interaction.getCardinality | public function getCardinality($numeric = false){
$returnValue = null;
// get maximum possibility:
switch(strtolower($this->getType())){
case 'choice':
case 'hottext':
case 'hotspot':
case 'selectpoint':
case 'positionobject':{
$max = intval($this->getAttributeValue('maxChoices'));
if($numeric){
$returnValue = $max;
}
else {
$returnValue = ($max == 1) ? 'single' : 'multiple'; // default=1
}
break;
}
case 'associate':
case 'match':
case 'graphicassociate':{
$max = intval($this->getAttributeValue('maxAssociations'));
if($numeric){
$returnValue = $max;
}
else{
$returnValue = ($max == 1) ? 'single' : 'multiple';
} // default=1
break;
}
case 'extendedtext':{
// maxStrings + order or not?
$cardinality = $this->getAttributeValue('cardinality');
if($cardinality == 'ordered'){
if($numeric){
$returnValue = 0;
} // meaning, infinite
else {
$returnValue = $cardinality;
}
break;
}
$max = intval($this->getAttributeValue('maxStrings'));
if($numeric){
$returnValue = $max;
}
else {
$returnValue = ($max > 1) ? 'multiple' : 'single'; // optional
}
break;
}
case 'gapmatch':{
// count the number of gap, i.e. "groups" in the interaction:
$max = count($this->getGaps());
if($numeric) {
$returnValue = $max;
}
else {
$returnValue = ($max > 1) ? 'multiple' : 'single';
}
break;
}
case 'graphicgapmatch':{
// strange that the standard always specifies "multiple":
$returnValue = 'multiple';
break;
}
case 'order':
case 'graphicorder':{
$returnValue = ($numeric) ? 1 : 'ordered';
break;
}
case 'inlinechoice':
case 'textentry':
case 'media':
case 'slider':
case 'upload':
case 'endattempt':{
$returnValue = ($numeric) ? 1 : 'single';
break;
}
default:{
throw new QtiModelException("the current interaction type \"{$this->type}\" is not available yet");
}
}
return $returnValue;
} | php | public function getCardinality($numeric = false){
$returnValue = null;
// get maximum possibility:
switch(strtolower($this->getType())){
case 'choice':
case 'hottext':
case 'hotspot':
case 'selectpoint':
case 'positionobject':{
$max = intval($this->getAttributeValue('maxChoices'));
if($numeric){
$returnValue = $max;
}
else {
$returnValue = ($max == 1) ? 'single' : 'multiple'; // default=1
}
break;
}
case 'associate':
case 'match':
case 'graphicassociate':{
$max = intval($this->getAttributeValue('maxAssociations'));
if($numeric){
$returnValue = $max;
}
else{
$returnValue = ($max == 1) ? 'single' : 'multiple';
} // default=1
break;
}
case 'extendedtext':{
// maxStrings + order or not?
$cardinality = $this->getAttributeValue('cardinality');
if($cardinality == 'ordered'){
if($numeric){
$returnValue = 0;
} // meaning, infinite
else {
$returnValue = $cardinality;
}
break;
}
$max = intval($this->getAttributeValue('maxStrings'));
if($numeric){
$returnValue = $max;
}
else {
$returnValue = ($max > 1) ? 'multiple' : 'single'; // optional
}
break;
}
case 'gapmatch':{
// count the number of gap, i.e. "groups" in the interaction:
$max = count($this->getGaps());
if($numeric) {
$returnValue = $max;
}
else {
$returnValue = ($max > 1) ? 'multiple' : 'single';
}
break;
}
case 'graphicgapmatch':{
// strange that the standard always specifies "multiple":
$returnValue = 'multiple';
break;
}
case 'order':
case 'graphicorder':{
$returnValue = ($numeric) ? 1 : 'ordered';
break;
}
case 'inlinechoice':
case 'textentry':
case 'media':
case 'slider':
case 'upload':
case 'endattempt':{
$returnValue = ($numeric) ? 1 : 'single';
break;
}
default:{
throw new QtiModelException("the current interaction type \"{$this->type}\" is not available yet");
}
}
return $returnValue;
} | [
"public",
"function",
"getCardinality",
"(",
"$",
"numeric",
"=",
"false",
")",
"{",
"$",
"returnValue",
"=",
"null",
";",
"// get maximum possibility:",
"switch",
"(",
"strtolower",
"(",
"$",
"this",
"->",
"getType",
"(",
")",
")",
")",
"{",
"case",
"'cho... | Retrieve the interaction cardinality
(single, multiple or ordered)
@access public
@author Sam, <sam@taotesting.com>
@param boolean numeric
@return mixed | [
"Retrieve",
"the",
"interaction",
"cardinality",
"(",
"single",
"multiple",
"or",
"ordered",
")"
] | train | https://github.com/oat-sa/extension-tao-itemqti/blob/a55b73c7894523bde169ba520d5001ce7b5bb88c/model/qti/interaction/Interaction.php#L236-L324 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.