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
aimeos/aimeos-symfony
Composer/ScriptHandler.php
ScriptHandler.getConsoleDir
protected static function getConsoleDir( Event $event ) { $options = self::getOptions( $event ); $bindir = 'bin'; if( isset( $options['symfony-app-dir'] ) && is_dir( $options['symfony-app-dir'] ) ) { $bindir = $options['symfony-app-dir']; } if( isset( $options['symfony-bin-dir'] ) && is_dir( $options['symfony-bin-dir'] ) ) { $bindir = $options['symfony-bin-dir']; } return $bindir; }
php
protected static function getConsoleDir( Event $event ) { $options = self::getOptions( $event ); $bindir = 'bin'; if( isset( $options['symfony-app-dir'] ) && is_dir( $options['symfony-app-dir'] ) ) { $bindir = $options['symfony-app-dir']; } if( isset( $options['symfony-bin-dir'] ) && is_dir( $options['symfony-bin-dir'] ) ) { $bindir = $options['symfony-bin-dir']; } return $bindir; }
[ "protected", "static", "function", "getConsoleDir", "(", "Event", "$", "event", ")", "{", "$", "options", "=", "self", "::", "getOptions", "(", "$", "event", ")", ";", "$", "bindir", "=", "'bin'", ";", "if", "(", "isset", "(", "$", "options", "[", "'...
Returns a relative path to the directory that contains the `console` command. @param Event $event Command event object @return string The path to the console directory @throws \RuntimeException If console directory couldn't be found
[ "Returns", "a", "relative", "path", "to", "the", "directory", "that", "contains", "the", "console", "command", "." ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Composer/ScriptHandler.php#L155-L170
aimeos/aimeos-symfony
Composer/ScriptHandler.php
ScriptHandler.updateConfigFile
protected static function updateConfigFile( $filename ) { if( ( $content = file_get_contents( $filename ) ) === false ) { throw new \RuntimeException( sprintf( 'File "%1$s" not found', $filename ) ); } if( self::addAsseticBundle( $content ) === true ) { $fs = new Filesystem(); $fs->dumpFile( $filename, $content ); } }
php
protected static function updateConfigFile( $filename ) { if( ( $content = file_get_contents( $filename ) ) === false ) { throw new \RuntimeException( sprintf( 'File "%1$s" not found', $filename ) ); } if( self::addAsseticBundle( $content ) === true ) { $fs = new Filesystem(); $fs->dumpFile( $filename, $content ); } }
[ "protected", "static", "function", "updateConfigFile", "(", "$", "filename", ")", "{", "if", "(", "(", "$", "content", "=", "file_get_contents", "(", "$", "filename", ")", ")", "===", "false", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprin...
Adds the Aimeos shop bundle to the config file of the application. @param string $filename Name of the YAML config file @throws \RuntimeException If file is not found
[ "Adds", "the", "Aimeos", "shop", "bundle", "to", "the", "config", "file", "of", "the", "application", "." ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Composer/ScriptHandler.php#L209-L219
aimeos/aimeos-symfony
Composer/ScriptHandler.php
ScriptHandler.updateRoutingFile
protected static function updateRoutingFile( $filename ) { $content = ''; if( file_exists( $filename ) && ( $content = file_get_contents( $filename ) ) === false ) { throw new \RuntimeException( sprintf( 'File "%1$s" not readable', $filename ) ); } if( strpos( $content, 'fos_user:' ) === false ) { $content .= "\n" . 'fos_user: resource: "@FOSUserBundle/Resources/config/routing/all.xml"'; } if( strpos( $content, 'aimeos_shop:' ) === false ) { $content .= "\n" . 'aimeos_shop: resource: "@AimeosShopBundle/Resources/config/routing.yml" prefix: /'; } $fs = new Filesystem(); $fs->dumpFile( $filename, $content ); }
php
protected static function updateRoutingFile( $filename ) { $content = ''; if( file_exists( $filename ) && ( $content = file_get_contents( $filename ) ) === false ) { throw new \RuntimeException( sprintf( 'File "%1$s" not readable', $filename ) ); } if( strpos( $content, 'fos_user:' ) === false ) { $content .= "\n" . 'fos_user: resource: "@FOSUserBundle/Resources/config/routing/all.xml"'; } if( strpos( $content, 'aimeos_shop:' ) === false ) { $content .= "\n" . 'aimeos_shop: resource: "@AimeosShopBundle/Resources/config/routing.yml" prefix: /'; } $fs = new Filesystem(); $fs->dumpFile( $filename, $content ); }
[ "protected", "static", "function", "updateRoutingFile", "(", "$", "filename", ")", "{", "$", "content", "=", "''", ";", "if", "(", "file_exists", "(", "$", "filename", ")", "&&", "(", "$", "content", "=", "file_get_contents", "(", "$", "filename", ")", "...
Adds the Aimeos shop bundle to the routing file of the application. @param string $filename Name of the YAML config file @throws \RuntimeException If file is not found
[ "Adds", "the", "Aimeos", "shop", "bundle", "to", "the", "routing", "file", "of", "the", "application", "." ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Composer/ScriptHandler.php#L228-L251
aimeos/aimeos-symfony
Composer/ScriptHandler.php
ScriptHandler.addAsseticBundle
protected static function addAsseticBundle( &$content ) { if( preg_match( "/ bundles:[ ]*\[.*'AimeosShopBundle'.*\]/", $content ) !== 1 ) { $search = array( "/ bundles:[ ]*\[([^\]]+)\]/", "/ bundles:[ ]*\[([ ]*)\]/" ); $replace = array( " bundles: [$1,'AimeosShopBundle']", " bundles: ['AimeosShopBundle']" ); if( ( $content = preg_replace( $search, $replace, $content ) ) !== null ) { return true; } } return false; }
php
protected static function addAsseticBundle( &$content ) { if( preg_match( "/ bundles:[ ]*\[.*'AimeosShopBundle'.*\]/", $content ) !== 1 ) { $search = array( "/ bundles:[ ]*\[([^\]]+)\]/", "/ bundles:[ ]*\[([ ]*)\]/" ); $replace = array( " bundles: [$1,'AimeosShopBundle']", " bundles: ['AimeosShopBundle']" ); if( ( $content = preg_replace( $search, $replace, $content ) ) !== null ) { return true; } } return false; }
[ "protected", "static", "function", "addAsseticBundle", "(", "&", "$", "content", ")", "{", "if", "(", "preg_match", "(", "\"/ bundles:[ ]*\\[.*'AimeosShopBundle'.*\\]/\"", ",", "$", "content", ")", "!==", "1", ")", "{", "$", "search", "=", "array", "(", "\"...
Adds the AimeosShopBundle to the assetic section of the config file @param string &$content Content of the config.yml file @return boolean True if modified, false if not
[ "Adds", "the", "AimeosShopBundle", "to", "the", "assetic", "section", "of", "the", "config", "file" ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Composer/ScriptHandler.php#L260-L273
aimeos/aimeos-symfony
Service/I18n.php
I18n.get
public function get( array $languageIds ) { $i18nPaths = $this->container->get( 'aimeos' )->get()->getI18nPaths(); foreach( $languageIds as $langid ) { if( !isset( $this->i18n[$langid] ) ) { $i18n = new \Aimeos\MW\Translation\Gettext( $i18nPaths, $langid ); $apc = (bool) $this->container->getParameter( 'aimeos_shop.apc_enable' ); $prefix = $this->container->getParameter( 'aimeos_shop.apc_prefix' ); if( function_exists( 'apcu_store' ) === true && $apc === true ) { $i18n = new \Aimeos\MW\Translation\Decorator\APC( $i18n, $prefix ); } $translations = $this->container->getParameter( 'aimeos_shop.i18n' ); if( isset( $translations[$langid] ) ) { $i18n = new \Aimeos\MW\Translation\Decorator\Memory( $i18n, $translations[$langid] ); } $this->i18n[$langid] = $i18n; } } return $this->i18n; }
php
public function get( array $languageIds ) { $i18nPaths = $this->container->get( 'aimeos' )->get()->getI18nPaths(); foreach( $languageIds as $langid ) { if( !isset( $this->i18n[$langid] ) ) { $i18n = new \Aimeos\MW\Translation\Gettext( $i18nPaths, $langid ); $apc = (bool) $this->container->getParameter( 'aimeos_shop.apc_enable' ); $prefix = $this->container->getParameter( 'aimeos_shop.apc_prefix' ); if( function_exists( 'apcu_store' ) === true && $apc === true ) { $i18n = new \Aimeos\MW\Translation\Decorator\APC( $i18n, $prefix ); } $translations = $this->container->getParameter( 'aimeos_shop.i18n' ); if( isset( $translations[$langid] ) ) { $i18n = new \Aimeos\MW\Translation\Decorator\Memory( $i18n, $translations[$langid] ); } $this->i18n[$langid] = $i18n; } } return $this->i18n; }
[ "public", "function", "get", "(", "array", "$", "languageIds", ")", "{", "$", "i18nPaths", "=", "$", "this", "->", "container", "->", "get", "(", "'aimeos'", ")", "->", "get", "(", ")", "->", "getI18nPaths", "(", ")", ";", "foreach", "(", "$", "langu...
Creates new translation objects. @param array $languageIds List of two letter ISO language IDs @return \Aimeos\MW\Translation\Interface[] List of translation objects
[ "Creates", "new", "translation", "objects", "." ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Service/I18n.php#L44-L72
aimeos/aimeos-symfony
Command/JobsCommand.php
JobsCommand.configure
protected function configure() { $names = ''; $aimeos = new \Aimeos\Bootstrap( array() ); $cntlPaths = $aimeos->getCustomPaths( 'controller/jobs' ); $controllers = \Aimeos\Controller\Jobs::get( $this->getBareContext(), $aimeos, $cntlPaths ); foreach( $controllers as $key => $controller ) { $names .= str_pad( $key, 30 ) . $controller->getName() . PHP_EOL; } $this->setName( self::$defaultName ); $this->setDescription( 'Executes the job controllers' ); $this->addArgument( 'jobs', InputArgument::REQUIRED, 'One or more job controller names like "admin/job customer/email/watch"' ); $this->addArgument( 'site', InputArgument::OPTIONAL, 'Site codes to execute the jobs for like "default unittest" (none for all)' ); $this->setHelp( "Available jobs are:\n" . $names ); }
php
protected function configure() { $names = ''; $aimeos = new \Aimeos\Bootstrap( array() ); $cntlPaths = $aimeos->getCustomPaths( 'controller/jobs' ); $controllers = \Aimeos\Controller\Jobs::get( $this->getBareContext(), $aimeos, $cntlPaths ); foreach( $controllers as $key => $controller ) { $names .= str_pad( $key, 30 ) . $controller->getName() . PHP_EOL; } $this->setName( self::$defaultName ); $this->setDescription( 'Executes the job controllers' ); $this->addArgument( 'jobs', InputArgument::REQUIRED, 'One or more job controller names like "admin/job customer/email/watch"' ); $this->addArgument( 'site', InputArgument::OPTIONAL, 'Site codes to execute the jobs for like "default unittest" (none for all)' ); $this->setHelp( "Available jobs are:\n" . $names ); }
[ "protected", "function", "configure", "(", ")", "{", "$", "names", "=", "''", ";", "$", "aimeos", "=", "new", "\\", "Aimeos", "\\", "Bootstrap", "(", "array", "(", ")", ")", ";", "$", "cntlPaths", "=", "$", "aimeos", "->", "getCustomPaths", "(", "'co...
Configures the command name and description.
[ "Configures", "the", "command", "name", "and", "description", "." ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Command/JobsCommand.php#L32-L48
aimeos/aimeos-symfony
Command/JobsCommand.php
JobsCommand.execute
protected function execute( InputInterface $input, OutputInterface $output ) { $context = $this->getContext(); $process = $context->getProcess(); $aimeos = $this->getContainer()->get( 'aimeos' )->get(); $jobs = explode( ' ', $input->getArgument( 'jobs' ) ); $localeManager = \Aimeos\MShop::create( $context, 'locale' ); foreach( $this->getSiteItems( $context, $input ) as $siteItem ) { $localeItem = $localeManager->bootstrap( $siteItem->getCode(), '', '', false ); $localeItem->setLanguageId( null ); $localeItem->setCurrencyId( null ); $context->setLocale( $localeItem ); $output->writeln( sprintf( 'Executing the Aimeos jobs for "<info>%s</info>"', $siteItem->getCode() ) ); foreach( $jobs as $jobname ) { $fcn = function( $context, $aimeos, $jobname ) { \Aimeos\Controller\Jobs::create( $context, $aimeos, $jobname )->run(); }; $process->start( $fcn, [$context, $aimeos, $jobname], true ); } } $process->wait(); }
php
protected function execute( InputInterface $input, OutputInterface $output ) { $context = $this->getContext(); $process = $context->getProcess(); $aimeos = $this->getContainer()->get( 'aimeos' )->get(); $jobs = explode( ' ', $input->getArgument( 'jobs' ) ); $localeManager = \Aimeos\MShop::create( $context, 'locale' ); foreach( $this->getSiteItems( $context, $input ) as $siteItem ) { $localeItem = $localeManager->bootstrap( $siteItem->getCode(), '', '', false ); $localeItem->setLanguageId( null ); $localeItem->setCurrencyId( null ); $context->setLocale( $localeItem ); $output->writeln( sprintf( 'Executing the Aimeos jobs for "<info>%s</info>"', $siteItem->getCode() ) ); foreach( $jobs as $jobname ) { $fcn = function( $context, $aimeos, $jobname ) { \Aimeos\Controller\Jobs::create( $context, $aimeos, $jobname )->run(); }; $process->start( $fcn, [$context, $aimeos, $jobname], true ); } } $process->wait(); }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "context", "=", "$", "this", "->", "getContext", "(", ")", ";", "$", "process", "=", "$", "context", "->", "getProcess", "(", "...
Executes the job controllers. @param InputInterface $input Input object @param OutputInterface $output Output object
[ "Executes", "the", "job", "controllers", "." ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Command/JobsCommand.php#L57-L87
aimeos/aimeos-symfony
Command/JobsCommand.php
JobsCommand.getBareContext
protected function getBareContext() { $ctx = new \Aimeos\MShop\Context\Item\Standard(); $conf = new \Aimeos\MW\Config\PHPArray( array(), array() ); $ctx->setConfig( $conf ); $locale = \Aimeos\MShop::create( $ctx, 'locale' )->createItem(); $locale->setLanguageId( 'en' ); $ctx->setLocale( $locale ); $i18n = new \Aimeos\MW\Translation\None( 'en' ); $ctx->setI18n( array( 'en' => $i18n ) ); return $ctx; }
php
protected function getBareContext() { $ctx = new \Aimeos\MShop\Context\Item\Standard(); $conf = new \Aimeos\MW\Config\PHPArray( array(), array() ); $ctx->setConfig( $conf ); $locale = \Aimeos\MShop::create( $ctx, 'locale' )->createItem(); $locale->setLanguageId( 'en' ); $ctx->setLocale( $locale ); $i18n = new \Aimeos\MW\Translation\None( 'en' ); $ctx->setI18n( array( 'en' => $i18n ) ); return $ctx; }
[ "protected", "function", "getBareContext", "(", ")", "{", "$", "ctx", "=", "new", "\\", "Aimeos", "\\", "MShop", "\\", "Context", "\\", "Item", "\\", "Standard", "(", ")", ";", "$", "conf", "=", "new", "\\", "Aimeos", "\\", "MW", "\\", "Config", "\\"...
Returns a bare context object @return \Aimeos\MShop\Context\Item\Standard Context object containing only the most necessary dependencies
[ "Returns", "a", "bare", "context", "object" ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Command/JobsCommand.php#L95-L110
aimeos/aimeos-symfony
Command/JobsCommand.php
JobsCommand.getContext
protected function getContext() { $container = $this->getContainer(); $aimeos = $container->get('aimeos')->get(); $context = $container->get( 'aimeos.context' )->get( false, 'command' ); $tmplPaths = $aimeos->getCustomPaths( 'controller/jobs/templates' ); $tmplPaths = array_merge( $tmplPaths, $aimeos->getCustomPaths( 'client/html/templates' ) ); $view = $container->get('aimeos.view')->create( $context, $tmplPaths ); $langManager = \Aimeos\MShop::create( $context, 'locale/language' ); $langids = array_keys( $langManager->searchItems( $langManager->createSearch( true ) ) ); $i18n = $this->getContainer()->get( 'aimeos.i18n' )->get( $langids ); $context->setEditor( 'aimeos:jobs' ); $context->setView( $view ); $context->setI18n( $i18n ); return $context; }
php
protected function getContext() { $container = $this->getContainer(); $aimeos = $container->get('aimeos')->get(); $context = $container->get( 'aimeos.context' )->get( false, 'command' ); $tmplPaths = $aimeos->getCustomPaths( 'controller/jobs/templates' ); $tmplPaths = array_merge( $tmplPaths, $aimeos->getCustomPaths( 'client/html/templates' ) ); $view = $container->get('aimeos.view')->create( $context, $tmplPaths ); $langManager = \Aimeos\MShop::create( $context, 'locale/language' ); $langids = array_keys( $langManager->searchItems( $langManager->createSearch( true ) ) ); $i18n = $this->getContainer()->get( 'aimeos.i18n' )->get( $langids ); $context->setEditor( 'aimeos:jobs' ); $context->setView( $view ); $context->setI18n( $i18n ); return $context; }
[ "protected", "function", "getContext", "(", ")", "{", "$", "container", "=", "$", "this", "->", "getContainer", "(", ")", ";", "$", "aimeos", "=", "$", "container", "->", "get", "(", "'aimeos'", ")", "->", "get", "(", ")", ";", "$", "context", "=", ...
Returns a context object @return \Aimeos\MShop\Context\Item\Standard Context object
[ "Returns", "a", "context", "object" ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Command/JobsCommand.php#L118-L137
aimeos/aimeos-symfony
Controller/LocaleController.php
LocaleController.selectComponentAction
public function selectComponentAction() { $shop = $this->container->get( 'shop' ); $client = $shop->get( 'locale/select' ); $this->container->get( 'twig' )->addGlobal( 'aiheader', (string) $client->getHeader() ); return new Response( (string) $client->getBody() ); }
php
public function selectComponentAction() { $shop = $this->container->get( 'shop' ); $client = $shop->get( 'locale/select' ); $this->container->get( 'twig' )->addGlobal( 'aiheader', (string) $client->getHeader() ); return new Response( (string) $client->getBody() ); }
[ "public", "function", "selectComponentAction", "(", ")", "{", "$", "shop", "=", "$", "this", "->", "container", "->", "get", "(", "'shop'", ")", ";", "$", "client", "=", "$", "shop", "->", "get", "(", "'locale/select'", ")", ";", "$", "this", "->", "...
Returns the output of the locale select component @return Response Response object containing the generated output
[ "Returns", "the", "output", "of", "the", "locale", "select", "component" ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Controller/LocaleController.php#L30-L37
aimeos/aimeos-symfony
Command/SetupCommand.php
SetupCommand.execute
protected function execute( InputInterface $input, OutputInterface $output ) { $ctx = $this->getContainer()->get( 'aimeos.context' )->get( false, 'command' ); $ctx->setEditor( 'aimeos:setup' ); $config = $ctx->getConfig(); $site = $input->getArgument( 'site' ); $tplsite = $input->getArgument( 'tplsite' ); $config->set( 'setup/site', $site ); $dbconfig = $this->getDbConfig( $config ); $this->setOptions( $config, $input ); \Aimeos\MShop::cache( false ); \Aimeos\MAdmin::cache( false ); $taskPaths = $this->getContainer()->get( 'aimeos' )->get()->getSetupPaths( $tplsite ); $manager = new \Aimeos\MW\Setup\Manager\Multiple( $ctx->getDatabaseManager(), $dbconfig, $taskPaths, $ctx ); $output->writeln( sprintf( 'Initializing or updating the Aimeos database tables for site <info>%1$s</info>', $site ) ); if( ( $task = $input->getOption( 'task' ) ) && is_array( $task ) ) { $task = reset( $task ); } switch( $input->getOption( 'action' ) ) { case 'migrate': $manager->migrate( $task ); break; case 'rollback': $manager->rollback( $task ); break; case 'clean': $manager->clean( $task ); break; default: throw new \Exception( sprintf( 'Invalid setup action "%1$s"', $input->getOption( 'action' ) ) ); } }
php
protected function execute( InputInterface $input, OutputInterface $output ) { $ctx = $this->getContainer()->get( 'aimeos.context' )->get( false, 'command' ); $ctx->setEditor( 'aimeos:setup' ); $config = $ctx->getConfig(); $site = $input->getArgument( 'site' ); $tplsite = $input->getArgument( 'tplsite' ); $config->set( 'setup/site', $site ); $dbconfig = $this->getDbConfig( $config ); $this->setOptions( $config, $input ); \Aimeos\MShop::cache( false ); \Aimeos\MAdmin::cache( false ); $taskPaths = $this->getContainer()->get( 'aimeos' )->get()->getSetupPaths( $tplsite ); $manager = new \Aimeos\MW\Setup\Manager\Multiple( $ctx->getDatabaseManager(), $dbconfig, $taskPaths, $ctx ); $output->writeln( sprintf( 'Initializing or updating the Aimeos database tables for site <info>%1$s</info>', $site ) ); if( ( $task = $input->getOption( 'task' ) ) && is_array( $task ) ) { $task = reset( $task ); } switch( $input->getOption( 'action' ) ) { case 'migrate': $manager->migrate( $task ); break; case 'rollback': $manager->rollback( $task ); break; case 'clean': $manager->clean( $task ); break; default: throw new \Exception( sprintf( 'Invalid setup action "%1$s"', $input->getOption( 'action' ) ) ); } }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "ctx", "=", "$", "this", "->", "getContainer", "(", ")", "->", "get", "(", "'aimeos.context'", ")", "->", "get", "(", "false", ...
Executes the database initialization and update. @param InputInterface $input Input object @param OutputInterface $output Output object
[ "Executes", "the", "database", "initialization", "and", "update", "." ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Command/SetupCommand.php#L51-L90
aimeos/aimeos-symfony
Service/Locale.php
Locale.get
public function get( \Aimeos\MShop\Context\Item\Iface $context ) { if( $this->locale === null ) { $status = $this->container->getParameter( 'aimeos_shop.disable_sites' ); $request = $this->requestStack->getMasterRequest(); $site = $request->attributes->get( 'site', $request->query->get( 'site', 'default' ) ); $currency = $request->attributes->get( 'currency', $request->query->get( 'currency', '' ) ); $lang = $request->attributes->get( 'locale', $request->query->get( 'locale', '' ) ); $localeManager = \Aimeos\MShop::create( $context, 'locale' ); $this->locale = $localeManager->bootstrap( $site, $lang, $currency, $status ); } return $this->locale; }
php
public function get( \Aimeos\MShop\Context\Item\Iface $context ) { if( $this->locale === null ) { $status = $this->container->getParameter( 'aimeos_shop.disable_sites' ); $request = $this->requestStack->getMasterRequest(); $site = $request->attributes->get( 'site', $request->query->get( 'site', 'default' ) ); $currency = $request->attributes->get( 'currency', $request->query->get( 'currency', '' ) ); $lang = $request->attributes->get( 'locale', $request->query->get( 'locale', '' ) ); $localeManager = \Aimeos\MShop::create( $context, 'locale' ); $this->locale = $localeManager->bootstrap( $site, $lang, $currency, $status ); } return $this->locale; }
[ "public", "function", "get", "(", "\\", "Aimeos", "\\", "MShop", "\\", "Context", "\\", "Item", "\\", "Iface", "$", "context", ")", "{", "if", "(", "$", "this", "->", "locale", "===", "null", ")", "{", "$", "status", "=", "$", "this", "->", "contai...
Returns the locale item for the current request @param \Aimeos\MShop\Context\Item\Iface $context Context object @return \Aimeos\MShop\Locale\Item\Iface Locale item object
[ "Returns", "the", "locale", "item", "for", "the", "current", "request" ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Service/Locale.php#L48-L64
aimeos/aimeos-symfony
DependencyInjection/Configuration.php
Configuration.getConfigTreeBuilder
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root( 'aimeos_shop' ); $rootNode ->children() ->booleanNode('disable_sites')->defaultValue( true )->end() ->booleanNode('apc_enable')->defaultValue( false )->end() ->scalarNode('apc_prefix')->defaultValue( 'sf2:' )->end() ->scalarNode('extdir')->end() ->scalarNode('uploaddir')->end() ->variableNode('admin')->defaultValue( array() )->end() ->variableNode('client')->defaultValue( array() )->end() ->variableNode('controller')->defaultValue( array() )->end() ->variableNode('i18n')->defaultValue( array() )->end() ->variableNode('madmin')->defaultValue( array() )->end() ->variableNode('mshop')->defaultValue( array() )->end() ->variableNode('resource')->defaultValue( array() )->end() ->variableNode('page')->defaultValue( array() )->end() ->variableNode('backend')->defaultValue( array() )->end() ->variableNode('frontend')->defaultValue( array() )->end() ->variableNode('command')->defaultValue( array() )->end() ->end() ; return $treeBuilder; }
php
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root( 'aimeos_shop' ); $rootNode ->children() ->booleanNode('disable_sites')->defaultValue( true )->end() ->booleanNode('apc_enable')->defaultValue( false )->end() ->scalarNode('apc_prefix')->defaultValue( 'sf2:' )->end() ->scalarNode('extdir')->end() ->scalarNode('uploaddir')->end() ->variableNode('admin')->defaultValue( array() )->end() ->variableNode('client')->defaultValue( array() )->end() ->variableNode('controller')->defaultValue( array() )->end() ->variableNode('i18n')->defaultValue( array() )->end() ->variableNode('madmin')->defaultValue( array() )->end() ->variableNode('mshop')->defaultValue( array() )->end() ->variableNode('resource')->defaultValue( array() )->end() ->variableNode('page')->defaultValue( array() )->end() ->variableNode('backend')->defaultValue( array() )->end() ->variableNode('frontend')->defaultValue( array() )->end() ->variableNode('command')->defaultValue( array() )->end() ->end() ; return $treeBuilder; }
[ "public", "function", "getConfigTreeBuilder", "(", ")", "{", "$", "treeBuilder", "=", "new", "TreeBuilder", "(", ")", ";", "$", "rootNode", "=", "$", "treeBuilder", "->", "root", "(", "'aimeos_shop'", ")", ";", "$", "rootNode", "->", "children", "(", ")", ...
{@inheritDoc}
[ "{" ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/DependencyInjection/Configuration.php#L29-L56
aimeos/aimeos-symfony
Controller/AccountController.php
AccountController.indexAction
public function indexAction() { $params = []; $shop = $this->container->get( 'shop' ); foreach( $this->container->getParameter( 'aimeos_shop.page' )['account-index'] as $name ) { $params['aiheader'][$name] = $shop->get( $name )->getHeader(); $params['aibody'][$name] = $shop->get( $name )->getBody(); } return $this->render( 'AimeosShopBundle:Account:index.html.twig', $params )->setPrivate()->setMaxAge( 300 ); }
php
public function indexAction() { $params = []; $shop = $this->container->get( 'shop' ); foreach( $this->container->getParameter( 'aimeos_shop.page' )['account-index'] as $name ) { $params['aiheader'][$name] = $shop->get( $name )->getHeader(); $params['aibody'][$name] = $shop->get( $name )->getBody(); } return $this->render( 'AimeosShopBundle:Account:index.html.twig', $params )->setPrivate()->setMaxAge( 300 ); }
[ "public", "function", "indexAction", "(", ")", "{", "$", "params", "=", "[", "]", ";", "$", "shop", "=", "$", "this", "->", "container", "->", "get", "(", "'shop'", ")", ";", "foreach", "(", "$", "this", "->", "container", "->", "getParameter", "(", ...
Returns the html for the "My account" page. @return Response Response object containing the generated output
[ "Returns", "the", "html", "for", "the", "My", "account", "page", "." ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Controller/AccountController.php#L30-L42
aimeos/aimeos-symfony
Controller/AccountController.php
AccountController.downloadAction
public function downloadAction() { $response = $this->container->get( 'shop' )->get( 'account/download' )->getView()->response(); return Response::create( (string) $response->getBody(), $response->getStatusCode(), $response->getHeaders() ); }
php
public function downloadAction() { $response = $this->container->get( 'shop' )->get( 'account/download' )->getView()->response(); return Response::create( (string) $response->getBody(), $response->getStatusCode(), $response->getHeaders() ); }
[ "public", "function", "downloadAction", "(", ")", "{", "$", "response", "=", "$", "this", "->", "container", "->", "get", "(", "'shop'", ")", "->", "get", "(", "'account/download'", ")", "->", "getView", "(", ")", "->", "response", "(", ")", ";", "retu...
Returns the html for the "My account" download page. @return Response Response object containing the generated output
[ "Returns", "the", "html", "for", "the", "My", "account", "download", "page", "." ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Controller/AccountController.php#L50-L54
aimeos/aimeos-symfony
Controller/AccountController.php
AccountController.favoriteComponentAction
public function favoriteComponentAction() { $client = $this->container->get( 'shop' )->get( 'account/favorite' ); $this->container->get( 'twig' )->addGlobal( 'aiheader', (string) $client->getHeader() ); return new Response( (string) $client->getBody() ); }
php
public function favoriteComponentAction() { $client = $this->container->get( 'shop' )->get( 'account/favorite' ); $this->container->get( 'twig' )->addGlobal( 'aiheader', (string) $client->getHeader() ); return new Response( (string) $client->getBody() ); }
[ "public", "function", "favoriteComponentAction", "(", ")", "{", "$", "client", "=", "$", "this", "->", "container", "->", "get", "(", "'shop'", ")", "->", "get", "(", "'account/favorite'", ")", ";", "$", "this", "->", "container", "->", "get", "(", "'twi...
Returns the output of the account favorite component @return Response Response object containing the generated output
[ "Returns", "the", "output", "of", "the", "account", "favorite", "component" ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Controller/AccountController.php#L62-L68
aimeos/aimeos-symfony
Controller/CheckoutController.php
CheckoutController.confirmAction
public function confirmAction() { $params = []; $shop = $this->container->get( 'shop' ); foreach( $this->container->getParameter( 'aimeos_shop.page' )['checkout-confirm'] as $name ) { $params['aiheader'][$name] = $shop->get( $name )->getHeader(); $params['aibody'][$name] = $shop->get( $name )->getBody(); } $response = $this->render( 'AimeosShopBundle:Checkout:confirm.html.twig', $params ); $response->headers->set('Cache-Control', 'no-store'); return $response; }
php
public function confirmAction() { $params = []; $shop = $this->container->get( 'shop' ); foreach( $this->container->getParameter( 'aimeos_shop.page' )['checkout-confirm'] as $name ) { $params['aiheader'][$name] = $shop->get( $name )->getHeader(); $params['aibody'][$name] = $shop->get( $name )->getBody(); } $response = $this->render( 'AimeosShopBundle:Checkout:confirm.html.twig', $params ); $response->headers->set('Cache-Control', 'no-store'); return $response; }
[ "public", "function", "confirmAction", "(", ")", "{", "$", "params", "=", "[", "]", ";", "$", "shop", "=", "$", "this", "->", "container", "->", "get", "(", "'shop'", ")", ";", "foreach", "(", "$", "this", "->", "container", "->", "getParameter", "("...
Returns the html for the checkout confirmation page. @return Response Response object containing the generated output
[ "Returns", "the", "html", "for", "the", "checkout", "confirmation", "page", "." ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Controller/CheckoutController.php#L30-L44
aimeos/aimeos-symfony
Controller/JqadmController.php
JqadmController.fileAction
public function fileAction( $type ) { $contents = ''; $files = array(); $aimeos = $this->get( 'aimeos' )->get(); foreach( $aimeos->getCustomPaths( 'admin/jqadm' ) as $base => $paths ) { foreach( $paths as $path ) { $jsbAbsPath = $base . '/' . $path; $jsb2 = new \Aimeos\MW\Jsb2\Standard( $jsbAbsPath, dirname( $jsbAbsPath ) ); $files = array_merge( $files, $jsb2->getFiles( $type ) ); } } foreach( $files as $file ) { if( ( $content = file_get_contents( $file ) ) !== false ) { $contents .= $content; } } $response = new Response( $contents ); if( $type === 'js' ) { $response->headers->set( 'Content-Type', 'application/javascript' ); } elseif( $type === 'css' ) { $response->headers->set( 'Content-Type', 'text/css' ); } return $response; }
php
public function fileAction( $type ) { $contents = ''; $files = array(); $aimeos = $this->get( 'aimeos' )->get(); foreach( $aimeos->getCustomPaths( 'admin/jqadm' ) as $base => $paths ) { foreach( $paths as $path ) { $jsbAbsPath = $base . '/' . $path; $jsb2 = new \Aimeos\MW\Jsb2\Standard( $jsbAbsPath, dirname( $jsbAbsPath ) ); $files = array_merge( $files, $jsb2->getFiles( $type ) ); } } foreach( $files as $file ) { if( ( $content = file_get_contents( $file ) ) !== false ) { $contents .= $content; } } $response = new Response( $contents ); if( $type === 'js' ) { $response->headers->set( 'Content-Type', 'application/javascript' ); } elseif( $type === 'css' ) { $response->headers->set( 'Content-Type', 'text/css' ); } return $response; }
[ "public", "function", "fileAction", "(", "$", "type", ")", "{", "$", "contents", "=", "''", ";", "$", "files", "=", "array", "(", ")", ";", "$", "aimeos", "=", "$", "this", "->", "get", "(", "'aimeos'", ")", "->", "get", "(", ")", ";", "foreach",...
Returns the JS file content @param $type File type, i.e. "css" or "js" @return Response Response object
[ "Returns", "the", "JS", "file", "content" ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Controller/JqadmController.php#L32-L64
aimeos/aimeos-symfony
Controller/JqadmController.php
JqadmController.copyAction
public function copyAction( Request $request, $resource, $site = 'default' ) { $cntl = $this->createAdmin( $request, $site, $resource ); if( ( $html = $cntl->copy() ) == '' ) { return $cntl->getView()->response(); } return $this->getHtml( $html ); }
php
public function copyAction( Request $request, $resource, $site = 'default' ) { $cntl = $this->createAdmin( $request, $site, $resource ); if( ( $html = $cntl->copy() ) == '' ) { return $cntl->getView()->response(); } return $this->getHtml( $html ); }
[ "public", "function", "copyAction", "(", "Request", "$", "request", ",", "$", "resource", ",", "$", "site", "=", "'default'", ")", "{", "$", "cntl", "=", "$", "this", "->", "createAdmin", "(", "$", "request", ",", "$", "site", ",", "$", "resource", "...
Returns the HTML code for a copy of a resource object @param Request $request Symfony request object @param string $resource Resource location, e.g. "product" @param string $site Unique site code @return Response Generated output
[ "Returns", "the", "HTML", "code", "for", "a", "copy", "of", "a", "resource", "object" ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Controller/JqadmController.php#L75-L84
aimeos/aimeos-symfony
Controller/JqadmController.php
JqadmController.createAction
public function createAction( Request $request, $resource, $site = 'default' ) { $cntl = $this->createAdmin( $request, $site, $resource ); if( ( $html = $cntl->create() ) == '' ) { return $cntl->getView()->response(); } return $this->getHtml( $html ); }
php
public function createAction( Request $request, $resource, $site = 'default' ) { $cntl = $this->createAdmin( $request, $site, $resource ); if( ( $html = $cntl->create() ) == '' ) { return $cntl->getView()->response(); } return $this->getHtml( $html ); }
[ "public", "function", "createAction", "(", "Request", "$", "request", ",", "$", "resource", ",", "$", "site", "=", "'default'", ")", "{", "$", "cntl", "=", "$", "this", "->", "createAdmin", "(", "$", "request", ",", "$", "site", ",", "$", "resource", ...
Returns the HTML code for a new resource object @param Request $request Symfony request object @param string $resource Resource location, e.g. "product" @param string $site Unique site code @return Response Generated output
[ "Returns", "the", "HTML", "code", "for", "a", "new", "resource", "object" ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Controller/JqadmController.php#L95-L104
aimeos/aimeos-symfony
Controller/JqadmController.php
JqadmController.deleteAction
public function deleteAction( Request $request, $resource, $site = 'default' ) { $cntl = $this->createAdmin( $request, $site, $resource ); if( ( $html = $cntl->delete() ) == '' ) { return $cntl->getView()->response(); } return $this->getHtml( $html ); }
php
public function deleteAction( Request $request, $resource, $site = 'default' ) { $cntl = $this->createAdmin( $request, $site, $resource ); if( ( $html = $cntl->delete() ) == '' ) { return $cntl->getView()->response(); } return $this->getHtml( $html ); }
[ "public", "function", "deleteAction", "(", "Request", "$", "request", ",", "$", "resource", ",", "$", "site", "=", "'default'", ")", "{", "$", "cntl", "=", "$", "this", "->", "createAdmin", "(", "$", "request", ",", "$", "site", ",", "$", "resource", ...
Deletes the resource object or a list of resource objects @param Request $request Symfony request object @param string $resource Resource location, e.g. "product" @param string $site Unique site code @return Response Generated output
[ "Deletes", "the", "resource", "object", "or", "a", "list", "of", "resource", "objects" ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Controller/JqadmController.php#L115-L124
aimeos/aimeos-symfony
Controller/JqadmController.php
JqadmController.exportAction
public function exportAction( Request $request, $resource, $site = 'default' ) { $cntl = $this->createAdmin( $request, $site, $resource ); if( ( $html = $cntl->export() ) == '' ) { return $cntl->getView()->response(); } return $this->getHtml( $html ); }
php
public function exportAction( Request $request, $resource, $site = 'default' ) { $cntl = $this->createAdmin( $request, $site, $resource ); if( ( $html = $cntl->export() ) == '' ) { return $cntl->getView()->response(); } return $this->getHtml( $html ); }
[ "public", "function", "exportAction", "(", "Request", "$", "request", ",", "$", "resource", ",", "$", "site", "=", "'default'", ")", "{", "$", "cntl", "=", "$", "this", "->", "createAdmin", "(", "$", "request", ",", "$", "site", ",", "$", "resource", ...
Exports the requested resource object @param Request $request Symfony request object @param string $resource Resource location, e.g. "product" @param string $site Unique site code @return Response Generated output
[ "Exports", "the", "requested", "resource", "object" ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Controller/JqadmController.php#L135-L144
aimeos/aimeos-symfony
Controller/JqadmController.php
JqadmController.getAction
public function getAction( Request $request, $resource, $site = 'default' ) { $cntl = $this->createAdmin( $request, $site, $resource ); if( ( $html = $cntl->get() ) == '' ) { return $cntl->getView()->response(); } return $this->getHtml( $html ); }
php
public function getAction( Request $request, $resource, $site = 'default' ) { $cntl = $this->createAdmin( $request, $site, $resource ); if( ( $html = $cntl->get() ) == '' ) { return $cntl->getView()->response(); } return $this->getHtml( $html ); }
[ "public", "function", "getAction", "(", "Request", "$", "request", ",", "$", "resource", ",", "$", "site", "=", "'default'", ")", "{", "$", "cntl", "=", "$", "this", "->", "createAdmin", "(", "$", "request", ",", "$", "site", ",", "$", "resource", ")...
Returns the HTML code for the requested resource object @param Request $request Symfony request object @param string $resource Resource location, e.g. "product" @param string $site Unique site code @return Response Generated output
[ "Returns", "the", "HTML", "code", "for", "the", "requested", "resource", "object" ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Controller/JqadmController.php#L155-L164
aimeos/aimeos-symfony
Controller/JqadmController.php
JqadmController.saveAction
public function saveAction( Request $request, $resource, $site = 'default' ) { $cntl = $this->createAdmin( $request, $site, $resource ); if( ( $html = $cntl->save() ) == '' ) { return $cntl->getView()->response(); } return $this->getHtml( $html ); }
php
public function saveAction( Request $request, $resource, $site = 'default' ) { $cntl = $this->createAdmin( $request, $site, $resource ); if( ( $html = $cntl->save() ) == '' ) { return $cntl->getView()->response(); } return $this->getHtml( $html ); }
[ "public", "function", "saveAction", "(", "Request", "$", "request", ",", "$", "resource", ",", "$", "site", "=", "'default'", ")", "{", "$", "cntl", "=", "$", "this", "->", "createAdmin", "(", "$", "request", ",", "$", "site", ",", "$", "resource", "...
Saves a new resource object @param Request $request Symfony request object @param string $resource Resource location, e.g. "product" @param string $site Unique site code @return Response Generated output
[ "Saves", "a", "new", "resource", "object" ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Controller/JqadmController.php#L175-L184
aimeos/aimeos-symfony
Controller/JqadmController.php
JqadmController.searchAction
public function searchAction( Request $request, $resource, $site = 'default' ) { $cntl = $this->createAdmin( $request, $site, $resource ); if( ( $html = $cntl->search() ) == '' ) { return $cntl->getView()->response(); } return $this->getHtml( $html ); }
php
public function searchAction( Request $request, $resource, $site = 'default' ) { $cntl = $this->createAdmin( $request, $site, $resource ); if( ( $html = $cntl->search() ) == '' ) { return $cntl->getView()->response(); } return $this->getHtml( $html ); }
[ "public", "function", "searchAction", "(", "Request", "$", "request", ",", "$", "resource", ",", "$", "site", "=", "'default'", ")", "{", "$", "cntl", "=", "$", "this", "->", "createAdmin", "(", "$", "request", ",", "$", "site", ",", "$", "resource", ...
Returns the HTML code for a list of resource objects @param Request $request Symfony request object @param string $resource Resource location, e.g. "product" @param string $site Unique site code @return Response Generated output
[ "Returns", "the", "HTML", "code", "for", "a", "list", "of", "resource", "objects" ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Controller/JqadmController.php#L195-L204
aimeos/aimeos-symfony
Controller/JqadmController.php
JqadmController.createAdmin
protected function createAdmin( Request $request, $site, $resource ) { $lang = $request->get( 'lang', 'en' ); $aimeos = $this->get( 'aimeos' )->get(); $templatePaths = $aimeos->getCustomPaths( 'admin/jqadm/templates' ); $context = $this->get( 'aimeos.context' )->get( false, 'backend' ); $context->setI18n( $this->get( 'aimeos.i18n' )->get( array( $lang, 'en' ) ) ); $context->setLocale( $this->get( 'aimeos.locale' )->getBackend( $context, $site ) ); $view = $this->get( 'aimeos.view' )->create( $context, $templatePaths, $lang ); $view->aimeosType = 'Symfony'; $view->aimeosVersion = $this->get( 'aimeos' )->getVersion(); $view->aimeosExtensions = implode( ',', $aimeos->getExtensions() ); $context->setView( $view ); return \Aimeos\Admin\JQAdm::create( $context, $aimeos, $resource ); }
php
protected function createAdmin( Request $request, $site, $resource ) { $lang = $request->get( 'lang', 'en' ); $aimeos = $this->get( 'aimeos' )->get(); $templatePaths = $aimeos->getCustomPaths( 'admin/jqadm/templates' ); $context = $this->get( 'aimeos.context' )->get( false, 'backend' ); $context->setI18n( $this->get( 'aimeos.i18n' )->get( array( $lang, 'en' ) ) ); $context->setLocale( $this->get( 'aimeos.locale' )->getBackend( $context, $site ) ); $view = $this->get( 'aimeos.view' )->create( $context, $templatePaths, $lang ); $view->aimeosType = 'Symfony'; $view->aimeosVersion = $this->get( 'aimeos' )->getVersion(); $view->aimeosExtensions = implode( ',', $aimeos->getExtensions() ); $context->setView( $view ); return \Aimeos\Admin\JQAdm::create( $context, $aimeos, $resource ); }
[ "protected", "function", "createAdmin", "(", "Request", "$", "request", ",", "$", "site", ",", "$", "resource", ")", "{", "$", "lang", "=", "$", "request", "->", "get", "(", "'lang'", ",", "'en'", ")", ";", "$", "aimeos", "=", "$", "this", "->", "g...
Returns the resource controller @param Request $request Symfony request object @param string $site Unique site code @param string $resource Resource location, e.g. "product" @return \Aimeos\Admin\JQAdm\Iface Context item
[ "Returns", "the", "resource", "controller" ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Controller/JqadmController.php#L215-L235
aimeos/aimeos-symfony
Command/AccountCommand.php
AccountCommand.execute
protected function execute( InputInterface $input, OutputInterface $output ) { $code = $input->getArgument( 'email' ); if( ( $password = $input->getOption( 'password' ) ) === null ) { $helper = $this->getHelper( 'question' ); $question = new Question( 'Password' ); $question->setHidden( true ); $password = $helper->ask( $input, $output, $question ); } $context = $this->getContainer()->get( 'aimeos.context' )->get( false, 'command' ); $context->setEditor( 'aimeos:account' ); $localeManager = \Aimeos\MShop::create( $context, 'locale' ); $localeItem = $localeManager->bootstrap( $input->getArgument( 'site' ), '', '', false ); $context->setLocale( $localeItem ); $user = $this->createCustomerItem( $context, $code, $password ); if( $input->getOption( 'admin' ) ) { $this->addGroup( $input, $output, $context, $user, 'admin' ); } if( $input->getOption( 'editor' ) ) { $this->addGroup( $input, $output, $context, $user, 'editor' ); } if( $this->getContainer()->has( 'fos_user.user_manager' ) ) { $userManager = $this->getContainer()->get( 'fos_user.user_manager' ); if( ( $fosUser = $userManager->findUserByUsername( $code ) ) === null ) { throw new \RuntimeException( 'No user created' ); } $fosUser->setSuperAdmin( false ); if( $input->getOption( 'super' ) ) { $fosUser->setSuperAdmin( true ); } if( $input->getOption( 'admin' ) || $input->getOption( 'editor' ) ) { $fosUser->addRole( 'ROLE_ADMIN' ); } $userManager->updateUser( $fosUser ); } }
php
protected function execute( InputInterface $input, OutputInterface $output ) { $code = $input->getArgument( 'email' ); if( ( $password = $input->getOption( 'password' ) ) === null ) { $helper = $this->getHelper( 'question' ); $question = new Question( 'Password' ); $question->setHidden( true ); $password = $helper->ask( $input, $output, $question ); } $context = $this->getContainer()->get( 'aimeos.context' )->get( false, 'command' ); $context->setEditor( 'aimeos:account' ); $localeManager = \Aimeos\MShop::create( $context, 'locale' ); $localeItem = $localeManager->bootstrap( $input->getArgument( 'site' ), '', '', false ); $context->setLocale( $localeItem ); $user = $this->createCustomerItem( $context, $code, $password ); if( $input->getOption( 'admin' ) ) { $this->addGroup( $input, $output, $context, $user, 'admin' ); } if( $input->getOption( 'editor' ) ) { $this->addGroup( $input, $output, $context, $user, 'editor' ); } if( $this->getContainer()->has( 'fos_user.user_manager' ) ) { $userManager = $this->getContainer()->get( 'fos_user.user_manager' ); if( ( $fosUser = $userManager->findUserByUsername( $code ) ) === null ) { throw new \RuntimeException( 'No user created' ); } $fosUser->setSuperAdmin( false ); if( $input->getOption( 'super' ) ) { $fosUser->setSuperAdmin( true ); } if( $input->getOption( 'admin' ) || $input->getOption( 'editor' ) ) { $fosUser->addRole( 'ROLE_ADMIN' ); } $userManager->updateUser( $fosUser ); } }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "code", "=", "$", "input", "->", "getArgument", "(", "'email'", ")", ";", "if", "(", "(", "$", "password", "=", "$", "input", ...
Execute the console command. @param InputInterface $input Input object @param OutputInterface $output Output object
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Command/AccountCommand.php#L52-L101
aimeos/aimeos-symfony
Command/AccountCommand.php
AccountCommand.addGroup
protected function addGroup( InputInterface $input, OutputInterface $output, \Aimeos\MShop\Context\Item\Iface $context, \Aimeos\MShop\Customer\Item\Iface $user, $group ) { $output->writeln( sprintf( 'Add "%1$s" group to user "%2$s" for sites', $group, $user->getCode() ) ); $localeManager = \Aimeos\MShop::create( $context, 'locale' ); foreach( $this->getSiteItems( $context, $input ) as $siteItem ) { $localeItem = $localeManager->bootstrap( $siteItem->getCode(), '', '', false ); $lcontext = clone $context; $lcontext->setLocale( $localeItem ); $output->writeln( '- ' . $siteItem->getCode() ); $groupItem = $this->getGroupItem( $lcontext, $group ); $this->addListItem( $lcontext, $user->getId(), $groupItem->getId() ); } }
php
protected function addGroup( InputInterface $input, OutputInterface $output, \Aimeos\MShop\Context\Item\Iface $context, \Aimeos\MShop\Customer\Item\Iface $user, $group ) { $output->writeln( sprintf( 'Add "%1$s" group to user "%2$s" for sites', $group, $user->getCode() ) ); $localeManager = \Aimeos\MShop::create( $context, 'locale' ); foreach( $this->getSiteItems( $context, $input ) as $siteItem ) { $localeItem = $localeManager->bootstrap( $siteItem->getCode(), '', '', false ); $lcontext = clone $context; $lcontext->setLocale( $localeItem ); $output->writeln( '- ' . $siteItem->getCode() ); $groupItem = $this->getGroupItem( $lcontext, $group ); $this->addListItem( $lcontext, $user->getId(), $groupItem->getId() ); } }
[ "protected", "function", "addGroup", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ",", "\\", "Aimeos", "\\", "MShop", "\\", "Context", "\\", "Item", "\\", "Iface", "$", "context", ",", "\\", "Aimeos", "\\", "MShop", "\\", "Cu...
Adds the group to the given user @param InputInterface $input Input object @param OutputInterface $output Output object @param \Aimeos\MShop\Context\Item\Iface $context Aimeos context object @param \Aimeos\MShop\Customer\Item\Iface $user Aimeos customer object @param string $group Unique customer group code
[ "Adds", "the", "group", "to", "the", "given", "user" ]
train
https://github.com/aimeos/aimeos-symfony/blob/ed132ca3d5861043228d270e5c59c7cc4394e61e/Command/AccountCommand.php#L113-L132
laravel-admin-extensions/scheduling
src/SchedulingController.php
SchedulingController.index
public function index() { return Admin::content(function (Content $content) { $content->header('Task scheduling'); $scheduling = new Scheduling(); $content->body(view('laravel-admin-scheduling::index', [ 'events' => $scheduling->getTasks(), ])); }); }
php
public function index() { return Admin::content(function (Content $content) { $content->header('Task scheduling'); $scheduling = new Scheduling(); $content->body(view('laravel-admin-scheduling::index', [ 'events' => $scheduling->getTasks(), ])); }); }
[ "public", "function", "index", "(", ")", "{", "return", "Admin", "::", "content", "(", "function", "(", "Content", "$", "content", ")", "{", "$", "content", "->", "header", "(", "'Task scheduling'", ")", ";", "$", "scheduling", "=", "new", "Scheduling", ...
Index interface. @return Content
[ "Index", "interface", "." ]
train
https://github.com/laravel-admin-extensions/scheduling/blob/663ef072b65e8c01c004c3c4577a9428904ba78c/src/SchedulingController.php#L16-L27
laravel-admin-extensions/scheduling
src/SchedulingController.php
SchedulingController.runEvent
public function runEvent(Request $request) { $scheduling = new Scheduling(); try { $output = $scheduling->runTask($request->get('id')); return [ 'status' => true, 'message' => 'success', 'data' => $output, ]; } catch (\Exception $e) { return [ 'status' => false, 'message' => 'failed', 'data' => $e->getMessage(), ]; } }
php
public function runEvent(Request $request) { $scheduling = new Scheduling(); try { $output = $scheduling->runTask($request->get('id')); return [ 'status' => true, 'message' => 'success', 'data' => $output, ]; } catch (\Exception $e) { return [ 'status' => false, 'message' => 'failed', 'data' => $e->getMessage(), ]; } }
[ "public", "function", "runEvent", "(", "Request", "$", "request", ")", "{", "$", "scheduling", "=", "new", "Scheduling", "(", ")", ";", "try", "{", "$", "output", "=", "$", "scheduling", "->", "runTask", "(", "$", "request", "->", "get", "(", "'id'", ...
@param Request $request @return array
[ "@param", "Request", "$request" ]
train
https://github.com/laravel-admin-extensions/scheduling/blob/663ef072b65e8c01c004c3c4577a9428904ba78c/src/SchedulingController.php#L34-L53
laravel-admin-extensions/scheduling
src/Scheduling.php
Scheduling.getTasks
public function getTasks() { $tasks = []; foreach ($this->getKernelEvents() as $event) { $tasks[] = [ 'task' => $this->formatTask($event), 'expression' => $event->expression, 'nextRunDate' => $event->nextRunDate()->format('Y-m-d H:i:s'), 'description' => $event->description, 'readable' => CronSchedule::fromCronString($event->expression)->asNaturalLanguage(), ]; } return $tasks; }
php
public function getTasks() { $tasks = []; foreach ($this->getKernelEvents() as $event) { $tasks[] = [ 'task' => $this->formatTask($event), 'expression' => $event->expression, 'nextRunDate' => $event->nextRunDate()->format('Y-m-d H:i:s'), 'description' => $event->description, 'readable' => CronSchedule::fromCronString($event->expression)->asNaturalLanguage(), ]; } return $tasks; }
[ "public", "function", "getTasks", "(", ")", "{", "$", "tasks", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getKernelEvents", "(", ")", "as", "$", "event", ")", "{", "$", "tasks", "[", "]", "=", "[", "'task'", "=>", "$", "this", "->", ...
Get all formatted tasks. @throws \Exception @return array
[ "Get", "all", "formatted", "tasks", "." ]
train
https://github.com/laravel-admin-extensions/scheduling/blob/663ef072b65e8c01c004c3c4577a9428904ba78c/src/Scheduling.php#L36-L51
laravel-admin-extensions/scheduling
src/Scheduling.php
Scheduling.formatTask
protected function formatTask($event) { if ($event instanceof CallbackEvent) { return [ 'type' => 'closure', 'name' => 'Closure', ]; } if (Str::contains($event->command, '\'artisan\'')) { $exploded = explode(' ', $event->command); return [ 'type' => 'artisan', 'name' => 'artisan '.implode(' ', array_slice($exploded, 2)), ]; } return [ 'type' => 'command', 'name' => $event->command, ]; }
php
protected function formatTask($event) { if ($event instanceof CallbackEvent) { return [ 'type' => 'closure', 'name' => 'Closure', ]; } if (Str::contains($event->command, '\'artisan\'')) { $exploded = explode(' ', $event->command); return [ 'type' => 'artisan', 'name' => 'artisan '.implode(' ', array_slice($exploded, 2)), ]; } return [ 'type' => 'command', 'name' => $event->command, ]; }
[ "protected", "function", "formatTask", "(", "$", "event", ")", "{", "if", "(", "$", "event", "instanceof", "CallbackEvent", ")", "{", "return", "[", "'type'", "=>", "'closure'", ",", "'name'", "=>", "'Closure'", ",", "]", ";", "}", "if", "(", "Str", ":...
Format a giving task. @param $event @return array
[ "Format", "a", "giving", "task", "." ]
train
https://github.com/laravel-admin-extensions/scheduling/blob/663ef072b65e8c01c004c3c4577a9428904ba78c/src/Scheduling.php#L60-L82
laravel-admin-extensions/scheduling
src/Scheduling.php
Scheduling.runTask
public function runTask($id) { set_time_limit(0); /** @var \Illuminate\Console\Scheduling\Event $event */ $event = $this->getKernelEvents()[$id - 1]; $event->sendOutputTo($this->getOutputTo()); $event->run(app()); return $this->readOutput(); }
php
public function runTask($id) { set_time_limit(0); /** @var \Illuminate\Console\Scheduling\Event $event */ $event = $this->getKernelEvents()[$id - 1]; $event->sendOutputTo($this->getOutputTo()); $event->run(app()); return $this->readOutput(); }
[ "public", "function", "runTask", "(", "$", "id", ")", "{", "set_time_limit", "(", "0", ")", ";", "/** @var \\Illuminate\\Console\\Scheduling\\Event $event */", "$", "event", "=", "$", "this", "->", "getKernelEvents", "(", ")", "[", "$", "id", "-", "1", "]", ...
Run specific task. @param int $id @return string
[ "Run", "specific", "task", "." ]
train
https://github.com/laravel-admin-extensions/scheduling/blob/663ef072b65e8c01c004c3c4577a9428904ba78c/src/Scheduling.php#L91-L103
laravel-admin-extensions/scheduling
src/Scheduling.php
Scheduling.registerRoutes
protected static function registerRoutes() { parent::routes(function ($router) { /* @var \Illuminate\Routing\Router $router */ $router->get('scheduling', 'Encore\Admin\Scheduling\SchedulingController@index')->name('scheduling-index'); $router->post('scheduling/run', 'Encore\Admin\Scheduling\SchedulingController@runEvent')->name('scheduling-run'); }); }
php
protected static function registerRoutes() { parent::routes(function ($router) { /* @var \Illuminate\Routing\Router $router */ $router->get('scheduling', 'Encore\Admin\Scheduling\SchedulingController@index')->name('scheduling-index'); $router->post('scheduling/run', 'Encore\Admin\Scheduling\SchedulingController@runEvent')->name('scheduling-run'); }); }
[ "protected", "static", "function", "registerRoutes", "(", ")", "{", "parent", "::", "routes", "(", "function", "(", "$", "router", ")", "{", "/* @var \\Illuminate\\Routing\\Router $router */", "$", "router", "->", "get", "(", "'scheduling'", ",", "'Encore\\Admin\\Sc...
Register routes for laravel-admin. @return void
[ "Register", "routes", "for", "laravel", "-", "admin", "." ]
train
https://github.com/laravel-admin-extensions/scheduling/blob/663ef072b65e8c01c004c3c4577a9428904ba78c/src/Scheduling.php#L144-L151
marcj/php-rest-service
RestService/Client.php
Client.sendResponse
public function sendResponse($pHttpCode = '200', $pMessage) { $suppressStatusCode = isset($_GET['_suppress_status_code']) ? $_GET['_suppress_status_code'] : false; if ($this->controller->getHttpStatusCodes() && !$suppressStatusCode && php_sapi_name() !== 'cli' ) { $status = self::$statusCodes[intval($pHttpCode)]; header('HTTP/1.0 ' . ($status ? $pHttpCode . ' ' . $status : $pHttpCode), true, $pHttpCode); } elseif (php_sapi_name() !== 'cli') { header('HTTP/1.0 200 OK'); } $pMessage = array_reverse($pMessage, true); $pMessage['status'] = intval($pHttpCode); $pMessage = array_reverse($pMessage, true); $method = $this->getOutputFormatMethod($this->getOutputFormat()); echo $this->$method($pMessage); exit; }
php
public function sendResponse($pHttpCode = '200', $pMessage) { $suppressStatusCode = isset($_GET['_suppress_status_code']) ? $_GET['_suppress_status_code'] : false; if ($this->controller->getHttpStatusCodes() && !$suppressStatusCode && php_sapi_name() !== 'cli' ) { $status = self::$statusCodes[intval($pHttpCode)]; header('HTTP/1.0 ' . ($status ? $pHttpCode . ' ' . $status : $pHttpCode), true, $pHttpCode); } elseif (php_sapi_name() !== 'cli') { header('HTTP/1.0 200 OK'); } $pMessage = array_reverse($pMessage, true); $pMessage['status'] = intval($pHttpCode); $pMessage = array_reverse($pMessage, true); $method = $this->getOutputFormatMethod($this->getOutputFormat()); echo $this->$method($pMessage); exit; }
[ "public", "function", "sendResponse", "(", "$", "pHttpCode", "=", "'200'", ",", "$", "pMessage", ")", "{", "$", "suppressStatusCode", "=", "isset", "(", "$", "_GET", "[", "'_suppress_status_code'", "]", ")", "?", "$", "_GET", "[", "'_suppress_status_code'", ...
Sends the actual response. @param string $pHttpCode @param $pMessage
[ "Sends", "the", "actual", "response", "." ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Client.php#L129-L150
marcj/php-rest-service
RestService/Client.php
Client.getMethod
public function getMethod() { if ($this->method) { return $this->method; } $method = @$_SERVER['REQUEST_METHOD']; if (isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) $method = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']; if (isset($_GET['_method'])) $method = $_GET['_method']; else if (isset($_POST['_method'])) $method = $_POST['_method']; $method = strtolower($method); if (!in_array($method, $this->methods)) $method = 'get'; return $method; }
php
public function getMethod() { if ($this->method) { return $this->method; } $method = @$_SERVER['REQUEST_METHOD']; if (isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) $method = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']; if (isset($_GET['_method'])) $method = $_GET['_method']; else if (isset($_POST['_method'])) $method = $_POST['_method']; $method = strtolower($method); if (!in_array($method, $this->methods)) $method = 'get'; return $method; }
[ "public", "function", "getMethod", "(", ")", "{", "if", "(", "$", "this", "->", "method", ")", "{", "return", "$", "this", "->", "method", ";", "}", "$", "method", "=", "@", "$", "_SERVER", "[", "'REQUEST_METHOD'", "]", ";", "if", "(", "isset", "("...
Detect the method. @return string
[ "Detect", "the", "method", "." ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Client.php#L174-L196
marcj/php-rest-service
RestService/Client.php
Client.asJSON
public function asJSON($pMessage) { if (php_sapi_name() !== 'cli') header('Content-Type: application/json; charset=utf-8'); $result = $this->jsonFormat($pMessage); $this->setContentLength($result); return $result; }
php
public function asJSON($pMessage) { if (php_sapi_name() !== 'cli') header('Content-Type: application/json; charset=utf-8'); $result = $this->jsonFormat($pMessage); $this->setContentLength($result); return $result; }
[ "public", "function", "asJSON", "(", "$", "pMessage", ")", "{", "if", "(", "php_sapi_name", "(", ")", "!==", "'cli'", ")", "header", "(", "'Content-Type: application/json; charset=utf-8'", ")", ";", "$", "result", "=", "$", "this", "->", "jsonFormat", "(", "...
Converts $pMessage to pretty json. @param $pMessage @return string
[ "Converts", "$pMessage", "to", "pretty", "json", "." ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Client.php#L229-L238
marcj/php-rest-service
RestService/Client.php
Client.jsonFormat
public function jsonFormat($json) { if (!is_string($json)) $json = json_encode($json); $result = ''; $pos = 0; $strLen = strlen($json); $indentStr = ' '; $newLine = "\n"; $inEscapeMode = false; //if the last char is a valid \ char. $outOfQuotes = true; for ($i = 0; $i <= $strLen; $i++) { // Grab the next character in the string. $char = substr($json, $i, 1); // Are we inside a quoted string? if ($char == '"' && !$inEscapeMode) { $outOfQuotes = !$outOfQuotes; // If this character is the end of an element, // output a new line and indent the next line. } elseif (($char == '}' || $char == ']') && $outOfQuotes) { $result .= $newLine; $pos--; for ($j = 0; $j < $pos; $j++) { $result .= $indentStr; } } elseif ($char == ':' && $outOfQuotes) { $char .= ' '; } // Add the character to the result string. $result .= $char; // If the last character was the beginning of an element, // output a new line and indent the next line. if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) { $result .= $newLine; if ($char == '{' || $char == '[') { $pos++; } for ($j = 0; $j < $pos; $j++) { $result .= $indentStr; } } if ($char == '\\' && !$inEscapeMode) $inEscapeMode = true; else $inEscapeMode = false; } return $result; }
php
public function jsonFormat($json) { if (!is_string($json)) $json = json_encode($json); $result = ''; $pos = 0; $strLen = strlen($json); $indentStr = ' '; $newLine = "\n"; $inEscapeMode = false; //if the last char is a valid \ char. $outOfQuotes = true; for ($i = 0; $i <= $strLen; $i++) { // Grab the next character in the string. $char = substr($json, $i, 1); // Are we inside a quoted string? if ($char == '"' && !$inEscapeMode) { $outOfQuotes = !$outOfQuotes; // If this character is the end of an element, // output a new line and indent the next line. } elseif (($char == '}' || $char == ']') && $outOfQuotes) { $result .= $newLine; $pos--; for ($j = 0; $j < $pos; $j++) { $result .= $indentStr; } } elseif ($char == ':' && $outOfQuotes) { $char .= ' '; } // Add the character to the result string. $result .= $char; // If the last character was the beginning of an element, // output a new line and indent the next line. if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) { $result .= $newLine; if ($char == '{' || $char == '[') { $pos++; } for ($j = 0; $j < $pos; $j++) { $result .= $indentStr; } } if ($char == '\\' && !$inEscapeMode) $inEscapeMode = true; else $inEscapeMode = false; } return $result; }
[ "public", "function", "jsonFormat", "(", "$", "json", ")", "{", "if", "(", "!", "is_string", "(", "$", "json", ")", ")", "$", "json", "=", "json_encode", "(", "$", "json", ")", ";", "$", "result", "=", "''", ";", "$", "pos", "=", "0", ";", "$",...
Indents a flat JSON string to make it more human-readable. Original at http://recursive-design.com/blog/2008/03/11/format-json-with-php/ @param string $json The original JSON string to process. @return string Indented version of the original JSON string.
[ "Indents", "a", "flat", "JSON", "string", "to", "make", "it", "more", "human", "-", "readable", "." ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Client.php#L249-L305
marcj/php-rest-service
RestService/Client.php
Client.asXML
public function asXML($pMessage) { $xml = $this->toXml($pMessage); $xml = "<?xml version=\"1.0\"?>\n<response>\n$xml</response>\n"; $this->setContentLength($xml); return $xml; }
php
public function asXML($pMessage) { $xml = $this->toXml($pMessage); $xml = "<?xml version=\"1.0\"?>\n<response>\n$xml</response>\n"; $this->setContentLength($xml); return $xml; }
[ "public", "function", "asXML", "(", "$", "pMessage", ")", "{", "$", "xml", "=", "$", "this", "->", "toXml", "(", "$", "pMessage", ")", ";", "$", "xml", "=", "\"<?xml version=\\\"1.0\\\"?>\\n<response>\\n$xml</response>\\n\"", ";", "$", "this", "->", "setConten...
Converts $pMessage to xml. @param $pMessage @return string
[ "Converts", "$pMessage", "to", "xml", "." ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Client.php#L313-L321
marcj/php-rest-service
RestService/Client.php
Client.setupFormats
public function setupFormats() { //through HTTP_ACCEPT if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], '*/*') === false) { foreach ($this->outputFormats as $formatCode => $formatMethod) { if (strpos($_SERVER['HTTP_ACCEPT'], $formatCode) !== false) { $this->outputFormat = $formatCode; break; } } } //through uri suffix if (preg_match('/\.(\w+)$/i', $this->getUrl(), $matches)) { if (isset($this->outputFormats[$matches[1]])) { $this->outputFormat = $matches[1]; $url = $this->getUrl(); $this->setUrl(substr($url, 0, (strlen($this->outputFormat) * -1) - 1)); } } //through _format parametr if (isset($_GET['_format'])) { if (isset($this->outputFormats[$_GET['_format']])) { $this->outputFormat = $_GET['_format']; } } return $this; }
php
public function setupFormats() { //through HTTP_ACCEPT if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], '*/*') === false) { foreach ($this->outputFormats as $formatCode => $formatMethod) { if (strpos($_SERVER['HTTP_ACCEPT'], $formatCode) !== false) { $this->outputFormat = $formatCode; break; } } } //through uri suffix if (preg_match('/\.(\w+)$/i', $this->getUrl(), $matches)) { if (isset($this->outputFormats[$matches[1]])) { $this->outputFormat = $matches[1]; $url = $this->getUrl(); $this->setUrl(substr($url, 0, (strlen($this->outputFormat) * -1) - 1)); } } //through _format parametr if (isset($_GET['_format'])) { if (isset($this->outputFormats[$_GET['_format']])) { $this->outputFormat = $_GET['_format']; } } return $this; }
[ "public", "function", "setupFormats", "(", ")", "{", "//through HTTP_ACCEPT", "if", "(", "isset", "(", "$", "_SERVER", "[", "'HTTP_ACCEPT'", "]", ")", "&&", "strpos", "(", "$", "_SERVER", "[", "'HTTP_ACCEPT'", "]", ",", "'*/*'", ")", "===", "false", ")", ...
Setup formats. @return Client
[ "Setup", "formats", "." ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Client.php#L404-L433
marcj/php-rest-service
RestService/Server.php
Server.setClient
public function setClient($pClient) { if (is_string($pClient)) { $pClient = new $pClient($this); } $this->client = $pClient; $this->client->setupFormats(); return $this; }
php
public function setClient($pClient) { if (is_string($pClient)) { $pClient = new $pClient($this); } $this->client = $pClient; $this->client->setupFormats(); return $this; }
[ "public", "function", "setClient", "(", "$", "pClient", ")", "{", "if", "(", "is_string", "(", "$", "pClient", ")", ")", "{", "$", "pClient", "=", "new", "$", "pClient", "(", "$", "this", ")", ";", "}", "$", "this", "->", "client", "=", "$", "pCl...
Sets the client. @param Client|string $pClient @return Server $this
[ "Sets", "the", "client", "." ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Server.php#L395-L405
marcj/php-rest-service
RestService/Server.php
Server.sendBadRequest
public function sendBadRequest($pCode, $pMessage) { if (is_object($pMessage) && $pMessage->xdebug_message) $pMessage = $pMessage->xdebug_message; $msg = array('error' => $pCode, 'message' => $pMessage); if (!$this->getClient()) throw new \Exception('client_not_found_in_ServerController'); return $this->getClient()->sendResponse('400', $msg); }
php
public function sendBadRequest($pCode, $pMessage) { if (is_object($pMessage) && $pMessage->xdebug_message) $pMessage = $pMessage->xdebug_message; $msg = array('error' => $pCode, 'message' => $pMessage); if (!$this->getClient()) throw new \Exception('client_not_found_in_ServerController'); return $this->getClient()->sendResponse('400', $msg); }
[ "public", "function", "sendBadRequest", "(", "$", "pCode", ",", "$", "pMessage", ")", "{", "if", "(", "is_object", "(", "$", "pMessage", ")", "&&", "$", "pMessage", "->", "xdebug_message", ")", "$", "pMessage", "=", "$", "pMessage", "->", "xdebug_message",...
Sends a 'Bad Request' response to the client. @param $pCode @param $pMessage @throws \Exception @return string
[ "Sends", "a", "Bad", "Request", "response", "to", "the", "client", "." ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Server.php#L425-L431
marcj/php-rest-service
RestService/Server.php
Server.sendException
public function sendException($pException) { if ($this->sendExceptionFn) { call_user_func_array($this->sendExceptionFn, array($pException)); } $message = $pException->getMessage(); if (is_object($message) && $message->xdebug_message) $message = $message->xdebug_message; $msg = array('error' => get_class($pException), 'message' => $message); if ($this->debugMode) { $msg['file'] = $pException->getFile(); $msg['line'] = $pException->getLine(); $msg['trace'] = $pException->getTraceAsString(); } if (!$this->getClient()) throw new \Exception('Client not found in ServerController'); return $this->getClient()->sendResponse('500', $msg); }
php
public function sendException($pException) { if ($this->sendExceptionFn) { call_user_func_array($this->sendExceptionFn, array($pException)); } $message = $pException->getMessage(); if (is_object($message) && $message->xdebug_message) $message = $message->xdebug_message; $msg = array('error' => get_class($pException), 'message' => $message); if ($this->debugMode) { $msg['file'] = $pException->getFile(); $msg['line'] = $pException->getLine(); $msg['trace'] = $pException->getTraceAsString(); } if (!$this->getClient()) throw new \Exception('Client not found in ServerController'); return $this->getClient()->sendResponse('500', $msg); }
[ "public", "function", "sendException", "(", "$", "pException", ")", "{", "if", "(", "$", "this", "->", "sendExceptionFn", ")", "{", "call_user_func_array", "(", "$", "this", "->", "sendExceptionFn", ",", "array", "(", "$", "pException", ")", ")", ";", "}",...
Sends a exception response to the client. @param $pException @throws \Exception
[ "Sends", "a", "exception", "response", "to", "the", "client", "." ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Server.php#L453-L473
marcj/php-rest-service
RestService/Server.php
Server.addRoute
public function addRoute($pUri, $pCb, $pHttpMethod = '_all_') { $this->routes[$pUri][ $pHttpMethod ] = $pCb; return $this; }
php
public function addRoute($pUri, $pCb, $pHttpMethod = '_all_') { $this->routes[$pUri][ $pHttpMethod ] = $pCb; return $this; }
[ "public", "function", "addRoute", "(", "$", "pUri", ",", "$", "pCb", ",", "$", "pHttpMethod", "=", "'_all_'", ")", "{", "$", "this", "->", "routes", "[", "$", "pUri", "]", "[", "$", "pHttpMethod", "]", "=", "$", "pCb", ";", "return", "$", "this", ...
Adds a new route for all http methods (get, post, put, delete, options, head, patch). @param string $pUri @param callable|string $pCb The method name of the passed controller or a php callable. @param string $pHttpMethod If you want to limit to a HTTP method. @return Server
[ "Adds", "a", "new", "route", "for", "all", "http", "methods", "(", "get", "post", "put", "delete", "options", "head", "patch", ")", "." ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Server.php#L483-L488
marcj/php-rest-service
RestService/Server.php
Server.setClass
public function setClass($pClass) { if (is_string($pClass)) { $this->createControllerClass($pClass); } elseif (is_object($pClass)) { $this->controller = $pClass; } else { $this->controller = $this; } }
php
public function setClass($pClass) { if (is_string($pClass)) { $this->createControllerClass($pClass); } elseif (is_object($pClass)) { $this->controller = $pClass; } else { $this->controller = $this; } }
[ "public", "function", "setClass", "(", "$", "pClass", ")", "{", "if", "(", "is_string", "(", "$", "pClass", ")", ")", "{", "$", "this", "->", "createControllerClass", "(", "$", "pClass", ")", ";", "}", "elseif", "(", "is_object", "(", "$", "pClass", ...
Sets the controller class. @param string|object $pClass
[ "Sets", "the", "controller", "class", "." ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Server.php#L606-L615
marcj/php-rest-service
RestService/Server.php
Server.createControllerClass
protected function createControllerClass($pClassName) { if ($pClassName != '') { try { if ($this->controllerFactory) { $this->controller = call_user_func_array($this->controllerFactory, array( $pClassName, $this )); } else { $this->controller = new $pClassName($this); } if (get_parent_class($this->controller) == '\RestService\Server') { $this->controller->setClient($this->getClient()); } } catch (\Exception $e) { throw new \Exception('Error during initialisation of '.$pClassName.': '.$e, 0, $e); } } else { $this->controller = $this; } }
php
protected function createControllerClass($pClassName) { if ($pClassName != '') { try { if ($this->controllerFactory) { $this->controller = call_user_func_array($this->controllerFactory, array( $pClassName, $this )); } else { $this->controller = new $pClassName($this); } if (get_parent_class($this->controller) == '\RestService\Server') { $this->controller->setClient($this->getClient()); } } catch (\Exception $e) { throw new \Exception('Error during initialisation of '.$pClassName.': '.$e, 0, $e); } } else { $this->controller = $this; } }
[ "protected", "function", "createControllerClass", "(", "$", "pClassName", ")", "{", "if", "(", "$", "pClassName", "!=", "''", ")", "{", "try", "{", "if", "(", "$", "this", "->", "controllerFactory", ")", "{", "$", "this", "->", "controller", "=", "call_u...
Setup the controller class. @param string $pClassName @throws \Exception
[ "Setup", "the", "controller", "class", "." ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Server.php#L623-L644
marcj/php-rest-service
RestService/Server.php
Server.addSubController
public function addSubController($pTriggerUrl, $pControllerClass = '') { $this->normalizeUrl($pTriggerUrl); $base = $this->triggerUrl; if ($base == '/') $base = ''; $controller = new Server($base . $pTriggerUrl, $pControllerClass, $this); $this->controllers[] = $controller; return $controller; }
php
public function addSubController($pTriggerUrl, $pControllerClass = '') { $this->normalizeUrl($pTriggerUrl); $base = $this->triggerUrl; if ($base == '/') $base = ''; $controller = new Server($base . $pTriggerUrl, $pControllerClass, $this); $this->controllers[] = $controller; return $controller; }
[ "public", "function", "addSubController", "(", "$", "pTriggerUrl", ",", "$", "pControllerClass", "=", "''", ")", "{", "$", "this", "->", "normalizeUrl", "(", "$", "pTriggerUrl", ")", ";", "$", "base", "=", "$", "this", "->", "triggerUrl", ";", "if", "(",...
Attach a sub controller. @param string $pTriggerUrl @param mixed $pControllerClass A class name (autoloader required) or a instance of a class. @return Server new created Server. Use done() to switch the context back to the parent.
[ "Attach", "a", "sub", "controller", "." ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Server.php#L654-L666
marcj/php-rest-service
RestService/Server.php
Server.normalizeUrl
public function normalizeUrl(&$pUrl) { if ('/' === $pUrl) return; if (substr($pUrl, -1) == '/') $pUrl = substr($pUrl, 0, -1); if (substr($pUrl, 0, 1) != '/') $pUrl = '/' . $pUrl; }
php
public function normalizeUrl(&$pUrl) { if ('/' === $pUrl) return; if (substr($pUrl, -1) == '/') $pUrl = substr($pUrl, 0, -1); if (substr($pUrl, 0, 1) != '/') $pUrl = '/' . $pUrl; }
[ "public", "function", "normalizeUrl", "(", "&", "$", "pUrl", ")", "{", "if", "(", "'/'", "===", "$", "pUrl", ")", "return", ";", "if", "(", "substr", "(", "$", "pUrl", ",", "-", "1", ")", "==", "'/'", ")", "$", "pUrl", "=", "substr", "(", "$", ...
Normalize $pUrl. Cuts of the trailing slash. @param string $pUrl
[ "Normalize", "$pUrl", ".", "Cuts", "of", "the", "trailing", "slash", "." ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Server.php#L673-L678
marcj/php-rest-service
RestService/Server.php
Server.collectRoutes
public function collectRoutes() { if ($this->collectRoutesExclude == '*') return $this; $methods = get_class_methods($this->controller); foreach ($methods as $method) { if (in_array($method, $this->collectRoutesExclude)) continue; $info = explode('/', preg_replace('/([a-z]*)(([A-Z]+)([a-zA-Z0-9_]*))/', '$1/$2', $method)); $uri = $this->camelCase2Dashes((empty($info[1]) ? '' : $info[1])); $httpMethod = $info[0]; if ($httpMethod == 'all') { $httpMethod = '_all_'; } $reflectionMethod = new \ReflectionMethod($this->controller, $method); if ($reflectionMethod->isPrivate()) continue; $phpDocs = $this->getMethodMetaData($reflectionMethod); if (isset($phpDocs['url'])) { if (isset($phpDocs['url']['url'])) { //only one route $this->routes[$phpDocs['url']['url']][$httpMethod] = $method; } else { foreach($phpDocs['url'] as $urlAnnotation) { $this->routes[$urlAnnotation['url']][$httpMethod] = $method; } } } else { $this->routes[$uri][$httpMethod] = $method; } } return $this; }
php
public function collectRoutes() { if ($this->collectRoutesExclude == '*') return $this; $methods = get_class_methods($this->controller); foreach ($methods as $method) { if (in_array($method, $this->collectRoutesExclude)) continue; $info = explode('/', preg_replace('/([a-z]*)(([A-Z]+)([a-zA-Z0-9_]*))/', '$1/$2', $method)); $uri = $this->camelCase2Dashes((empty($info[1]) ? '' : $info[1])); $httpMethod = $info[0]; if ($httpMethod == 'all') { $httpMethod = '_all_'; } $reflectionMethod = new \ReflectionMethod($this->controller, $method); if ($reflectionMethod->isPrivate()) continue; $phpDocs = $this->getMethodMetaData($reflectionMethod); if (isset($phpDocs['url'])) { if (isset($phpDocs['url']['url'])) { //only one route $this->routes[$phpDocs['url']['url']][$httpMethod] = $method; } else { foreach($phpDocs['url'] as $urlAnnotation) { $this->routes[$urlAnnotation['url']][$httpMethod] = $method; } } } else { $this->routes[$uri][$httpMethod] = $method; } } return $this; }
[ "public", "function", "collectRoutes", "(", ")", "{", "if", "(", "$", "this", "->", "collectRoutesExclude", "==", "'*'", ")", "return", "$", "this", ";", "$", "methods", "=", "get_class_methods", "(", "$", "this", "->", "controller", ")", ";", "foreach", ...
Setup automatic routes. @return Server
[ "Setup", "automatic", "routes", "." ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Server.php#L704-L740
marcj/php-rest-service
RestService/Server.php
Server.simulateCall
public function simulateCall($pUri, $pMethod = 'get') { if (($idx = strpos($pUri, '?')) !== false) { parse_str(substr($pUri, $idx+1), $_GET); $pUri = substr($pUri, 0, $idx); } $this->getClient()->setUrl($pUri); $this->getClient()->setMethod($pMethod); return $this->run(); }
php
public function simulateCall($pUri, $pMethod = 'get') { if (($idx = strpos($pUri, '?')) !== false) { parse_str(substr($pUri, $idx+1), $_GET); $pUri = substr($pUri, 0, $idx); } $this->getClient()->setUrl($pUri); $this->getClient()->setMethod($pMethod); return $this->run(); }
[ "public", "function", "simulateCall", "(", "$", "pUri", ",", "$", "pMethod", "=", "'get'", ")", "{", "if", "(", "(", "$", "idx", "=", "strpos", "(", "$", "pUri", ",", "'?'", ")", ")", "!==", "false", ")", "{", "parse_str", "(", "substr", "(", "$"...
Simulates a HTTP Call. @param string $pUri @param string $pMethod The HTTP Method @return string
[ "Simulates", "a", "HTTP", "Call", "." ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Server.php#L749-L759
marcj/php-rest-service
RestService/Server.php
Server.run
public function run() { //check sub controller foreach ($this->controllers as $controller) { if ($result = $controller->run()) { return $result; } } $requestedUrl = $this->getClient()->getUrl(); $this->normalizeUrl($requestedUrl); //check if its in our area if (strpos($requestedUrl, $this->triggerUrl) !== 0) return; $endPos = $this->triggerUrl === '/' ? 1 : strlen($this->triggerUrl) + 1; $uri = substr($requestedUrl, $endPos); if (!$uri) $uri = ''; $route = false; $arguments = array(); $requiredMethod = $this->getClient()->getMethod(); //does the requested uri exist? list($callableMethod, $regexArguments, $method, $routeUri) = $this->findRoute($uri, $requiredMethod); if ((!$callableMethod || $method != 'options') && $requiredMethod == 'options') { $description = $this->describe($uri); $this->send($description); } if (!$callableMethod) { if (!$this->getParentController()) { if ($this->fallbackMethod) { $m = $this->fallbackMethod; $this->send($this->controller->$m()); } else { return $this->sendBadRequest('RouteNotFoundException', "There is no route for '$uri'."); } } else { return false; } } if ($method == '_all_') $arguments[] = $method; if (is_array($regexArguments)) { $arguments = array_merge($arguments, $regexArguments); } //open class and scan method if ($this->controller && is_string($callableMethod)) { $ref = new \ReflectionClass($this->controller); if (!method_exists($this->controller, $callableMethod)) { $this->sendBadRequest('MethodNotFoundException', "There is no method '$callableMethod' in ". get_class($this->controller)."."); } $reflectionMethod = $ref->getMethod($callableMethod); } else if (is_callable($callableMethod)) { $reflectionMethod = new \ReflectionFunction($callableMethod); } $params = $reflectionMethod->getParameters(); if ($method == '_all_') { //first parameter is $pMethod array_shift($params); } //remove regex arguments for ($i=0; $i<count($regexArguments); $i++) { array_shift($params); } //collect arguments foreach ($params as $param) { $name = $this->argumentName($param->getName()); if ($name == '_') { $thisArgs = array(); foreach ($_GET as $k => $v) { if (substr($k, 0, 1) == '_' && $k != '_suppress_status_code') $thisArgs[$k] = $v; } $arguments[] = $thisArgs; } else { if (!$param->isOptional() && !isset($_GET[$name]) && !isset($_POST[$name])) { return $this->sendBadRequest('MissingRequiredArgumentException', sprintf("Argument '%s' is missing.", $name)); } $arguments[] = isset($_GET[$name]) ? $_GET[$name] : (isset($_POST[$name]) ? $_POST[$name] : $param->getDefaultValue()); } } if ($this->checkAccessFn) { $args[] = $this->getClient()->getUrl(); $args[] = $route; $args[] = $arguments; try { call_user_func_array($this->checkAccessFn, $args); } catch (\Exception $e) { $this->sendException($e); } } //fire method $object = $this->controller; return $this->fireMethod($callableMethod, $object, $arguments); }
php
public function run() { //check sub controller foreach ($this->controllers as $controller) { if ($result = $controller->run()) { return $result; } } $requestedUrl = $this->getClient()->getUrl(); $this->normalizeUrl($requestedUrl); //check if its in our area if (strpos($requestedUrl, $this->triggerUrl) !== 0) return; $endPos = $this->triggerUrl === '/' ? 1 : strlen($this->triggerUrl) + 1; $uri = substr($requestedUrl, $endPos); if (!$uri) $uri = ''; $route = false; $arguments = array(); $requiredMethod = $this->getClient()->getMethod(); //does the requested uri exist? list($callableMethod, $regexArguments, $method, $routeUri) = $this->findRoute($uri, $requiredMethod); if ((!$callableMethod || $method != 'options') && $requiredMethod == 'options') { $description = $this->describe($uri); $this->send($description); } if (!$callableMethod) { if (!$this->getParentController()) { if ($this->fallbackMethod) { $m = $this->fallbackMethod; $this->send($this->controller->$m()); } else { return $this->sendBadRequest('RouteNotFoundException', "There is no route for '$uri'."); } } else { return false; } } if ($method == '_all_') $arguments[] = $method; if (is_array($regexArguments)) { $arguments = array_merge($arguments, $regexArguments); } //open class and scan method if ($this->controller && is_string($callableMethod)) { $ref = new \ReflectionClass($this->controller); if (!method_exists($this->controller, $callableMethod)) { $this->sendBadRequest('MethodNotFoundException', "There is no method '$callableMethod' in ". get_class($this->controller)."."); } $reflectionMethod = $ref->getMethod($callableMethod); } else if (is_callable($callableMethod)) { $reflectionMethod = new \ReflectionFunction($callableMethod); } $params = $reflectionMethod->getParameters(); if ($method == '_all_') { //first parameter is $pMethod array_shift($params); } //remove regex arguments for ($i=0; $i<count($regexArguments); $i++) { array_shift($params); } //collect arguments foreach ($params as $param) { $name = $this->argumentName($param->getName()); if ($name == '_') { $thisArgs = array(); foreach ($_GET as $k => $v) { if (substr($k, 0, 1) == '_' && $k != '_suppress_status_code') $thisArgs[$k] = $v; } $arguments[] = $thisArgs; } else { if (!$param->isOptional() && !isset($_GET[$name]) && !isset($_POST[$name])) { return $this->sendBadRequest('MissingRequiredArgumentException', sprintf("Argument '%s' is missing.", $name)); } $arguments[] = isset($_GET[$name]) ? $_GET[$name] : (isset($_POST[$name]) ? $_POST[$name] : $param->getDefaultValue()); } } if ($this->checkAccessFn) { $args[] = $this->getClient()->getUrl(); $args[] = $route; $args[] = $arguments; try { call_user_func_array($this->checkAccessFn, $args); } catch (\Exception $e) { $this->sendException($e); } } //fire method $object = $this->controller; return $this->fireMethod($callableMethod, $object, $arguments); }
[ "public", "function", "run", "(", ")", "{", "//check sub controller", "foreach", "(", "$", "this", "->", "controllers", "as", "$", "controller", ")", "{", "if", "(", "$", "result", "=", "$", "controller", "->", "run", "(", ")", ")", "{", "return", "$",...
Fire the magic! Searches the method and sends the data to the client. @return mixed
[ "Fire", "the", "magic!" ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Server.php#L768-L882
marcj/php-rest-service
RestService/Server.php
Server.describe
public function describe($pUri = null, $pOnlyRoutes = false) { $definition = array(); if (!$pOnlyRoutes) { $definition['parameters'] = array( '_method' => array('description' => 'Can be used as HTTP METHOD if the client does not support HTTP methods.', 'type' => 'string', 'values' => 'GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH'), '_suppress_status_code' => array('description' => 'Suppress the HTTP status code.', 'type' => 'boolean', 'values' => '1, 0'), '_format' => array('description' => 'Format of generated data. Can be added as suffix .json .xml', 'type' => 'string', 'values' => 'json, xml'), ); } $definition['controller'] = array( 'entryPoint' => $this->getTriggerUrl() ); foreach ($this->routes as $routeUri => $routeMethods) { $matches = array(); if (!$pUri || ($pUri && preg_match('|^'.$routeUri.'$|', $pUri, $matches))) { if ($matches) { array_shift($matches); } $def = array(); $def['uri'] = $this->getTriggerUrl().'/'.$routeUri; foreach ($routeMethods as $method => $phpMethod) { if (is_string($phpMethod)) { $ref = new \ReflectionClass($this->controller); $refMethod = $ref->getMethod($phpMethod); } else { $refMethod = new \ReflectionFunction($phpMethod); } $def['methods'][strtoupper($method)] = $this->getMethodMetaData($refMethod, $matches); } $definition['controller']['routes'][$routeUri] = $def; } } if (!$pUri) { foreach ($this->controllers as $controller) { $definition['subController'][$controller->getTriggerUrl()] = $controller->describe(false, true); } } return $definition; }
php
public function describe($pUri = null, $pOnlyRoutes = false) { $definition = array(); if (!$pOnlyRoutes) { $definition['parameters'] = array( '_method' => array('description' => 'Can be used as HTTP METHOD if the client does not support HTTP methods.', 'type' => 'string', 'values' => 'GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH'), '_suppress_status_code' => array('description' => 'Suppress the HTTP status code.', 'type' => 'boolean', 'values' => '1, 0'), '_format' => array('description' => 'Format of generated data. Can be added as suffix .json .xml', 'type' => 'string', 'values' => 'json, xml'), ); } $definition['controller'] = array( 'entryPoint' => $this->getTriggerUrl() ); foreach ($this->routes as $routeUri => $routeMethods) { $matches = array(); if (!$pUri || ($pUri && preg_match('|^'.$routeUri.'$|', $pUri, $matches))) { if ($matches) { array_shift($matches); } $def = array(); $def['uri'] = $this->getTriggerUrl().'/'.$routeUri; foreach ($routeMethods as $method => $phpMethod) { if (is_string($phpMethod)) { $ref = new \ReflectionClass($this->controller); $refMethod = $ref->getMethod($phpMethod); } else { $refMethod = new \ReflectionFunction($phpMethod); } $def['methods'][strtoupper($method)] = $this->getMethodMetaData($refMethod, $matches); } $definition['controller']['routes'][$routeUri] = $def; } } if (!$pUri) { foreach ($this->controllers as $controller) { $definition['subController'][$controller->getTriggerUrl()] = $controller->describe(false, true); } } return $definition; }
[ "public", "function", "describe", "(", "$", "pUri", "=", "null", ",", "$", "pOnlyRoutes", "=", "false", ")", "{", "$", "definition", "=", "array", "(", ")", ";", "if", "(", "!", "$", "pOnlyRoutes", ")", "{", "$", "definition", "[", "'parameters'", "]...
Describe a route or the whole controller with all routes. @param string $pUri @param boolean $pOnlyRoutes @return array
[ "Describe", "a", "route", "or", "the", "whole", "controller", "with", "all", "routes", "." ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Server.php#L914-L965
marcj/php-rest-service
RestService/Server.php
Server.getMethodMetaData
public function getMethodMetaData(\ReflectionFunctionAbstract $pMethod, $pRegMatches = null) { $file = $pMethod->getFileName(); $startLine = $pMethod->getStartLine(); $fh = fopen($file, 'r'); if (!$fh) return false; $lineNr = 1; $lines = array(); while (($buffer = fgets($fh)) !== false) { if ($lineNr == $startLine) break; $lines[$lineNr] = $buffer; $lineNr++; } fclose($fh); $phpDoc = ''; $blockStarted = false; while ($line = array_pop($lines)) { if ($blockStarted) { $phpDoc = $line.$phpDoc; //if start comment block: /* if (preg_match('/\s*\t*\/\*/', $line)) { break; } continue; } else { //we are not in a comment block. //if class def, array def or close bracked from fn comes above //then we dont have phpdoc if (preg_match('/^\s*\t*[a-zA-Z_&\s]*(\$|{|})/', $line)) { break; } } $trimmed = trim($line); if ($trimmed == '') continue; //if end comment block: */ if (preg_match('/\*\//', $line)) { $phpDoc = $line.$phpDoc; $blockStarted = true; //one line php doc? if (preg_match('/\s*\t*\/\*/', $line)) { break; } } } $phpDoc = $this->parsePhpDoc($phpDoc); $refParams = $pMethod->getParameters(); $params = array(); $fillPhpDocParam = !isset($phpDoc['param']); foreach ($refParams as $param) { $params[$param->getName()] = $param; if ($fillPhpDocParam) { $phpDoc['param'][] = array( 'name' => $param->getName(), 'type' => $param->isArray()?'array':'mixed' ); } } $parameters = array(); if (isset($phpDoc['param'])) { if (is_array($phpDoc['param']) && is_string(key($phpDoc['param']))) $phpDoc['param'] = array($phpDoc['param']); $c = 0; foreach ($phpDoc['param'] as $phpDocParam) { $param = $params[$phpDocParam['name']]; if (!$param) continue; $parameter = array( 'type' => $phpDocParam['type'] ); if ($pRegMatches && is_array($pRegMatches) && $pRegMatches[$c]) { $parameter['fromRegex'] = '$'.($c+1); } $parameter['required'] = !$param->isOptional(); if ($param->isDefaultValueAvailable()) { $parameter['default'] = str_replace(array("\n", ' '), '', var_export($param->getDefaultValue(), true)); } $parameters[$this->argumentName($phpDocParam['name'])] = $parameter; $c++; } } if (!isset($phpDoc['return'])) $phpDoc['return'] = array('type' => 'mixed'); $result = array( 'parameters' => $parameters, 'return' => $phpDoc['return'] ); if (isset($phpDoc['description'])) $result['description'] = $phpDoc['description']; if (isset($phpDoc['url'])) $result['url'] = $phpDoc['url']; return $result; }
php
public function getMethodMetaData(\ReflectionFunctionAbstract $pMethod, $pRegMatches = null) { $file = $pMethod->getFileName(); $startLine = $pMethod->getStartLine(); $fh = fopen($file, 'r'); if (!$fh) return false; $lineNr = 1; $lines = array(); while (($buffer = fgets($fh)) !== false) { if ($lineNr == $startLine) break; $lines[$lineNr] = $buffer; $lineNr++; } fclose($fh); $phpDoc = ''; $blockStarted = false; while ($line = array_pop($lines)) { if ($blockStarted) { $phpDoc = $line.$phpDoc; //if start comment block: /* if (preg_match('/\s*\t*\/\*/', $line)) { break; } continue; } else { //we are not in a comment block. //if class def, array def or close bracked from fn comes above //then we dont have phpdoc if (preg_match('/^\s*\t*[a-zA-Z_&\s]*(\$|{|})/', $line)) { break; } } $trimmed = trim($line); if ($trimmed == '') continue; //if end comment block: */ if (preg_match('/\*\//', $line)) { $phpDoc = $line.$phpDoc; $blockStarted = true; //one line php doc? if (preg_match('/\s*\t*\/\*/', $line)) { break; } } } $phpDoc = $this->parsePhpDoc($phpDoc); $refParams = $pMethod->getParameters(); $params = array(); $fillPhpDocParam = !isset($phpDoc['param']); foreach ($refParams as $param) { $params[$param->getName()] = $param; if ($fillPhpDocParam) { $phpDoc['param'][] = array( 'name' => $param->getName(), 'type' => $param->isArray()?'array':'mixed' ); } } $parameters = array(); if (isset($phpDoc['param'])) { if (is_array($phpDoc['param']) && is_string(key($phpDoc['param']))) $phpDoc['param'] = array($phpDoc['param']); $c = 0; foreach ($phpDoc['param'] as $phpDocParam) { $param = $params[$phpDocParam['name']]; if (!$param) continue; $parameter = array( 'type' => $phpDocParam['type'] ); if ($pRegMatches && is_array($pRegMatches) && $pRegMatches[$c]) { $parameter['fromRegex'] = '$'.($c+1); } $parameter['required'] = !$param->isOptional(); if ($param->isDefaultValueAvailable()) { $parameter['default'] = str_replace(array("\n", ' '), '', var_export($param->getDefaultValue(), true)); } $parameters[$this->argumentName($phpDocParam['name'])] = $parameter; $c++; } } if (!isset($phpDoc['return'])) $phpDoc['return'] = array('type' => 'mixed'); $result = array( 'parameters' => $parameters, 'return' => $phpDoc['return'] ); if (isset($phpDoc['description'])) $result['description'] = $phpDoc['description']; if (isset($phpDoc['url'])) $result['url'] = $phpDoc['url']; return $result; }
[ "public", "function", "getMethodMetaData", "(", "\\", "ReflectionFunctionAbstract", "$", "pMethod", ",", "$", "pRegMatches", "=", "null", ")", "{", "$", "file", "=", "$", "pMethod", "->", "getFileName", "(", ")", ";", "$", "startLine", "=", "$", "pMethod", ...
Fetches all meta data informations as params, return type etc. @param \ReflectionMethod $pMethod @param array $pRegMatches @return array
[ "Fetches", "all", "meta", "data", "informations", "as", "params", "return", "type", "etc", "." ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Server.php#L974-L1087
marcj/php-rest-service
RestService/Server.php
Server.parsePhpDoc
public function parsePhpDoc($pString) { preg_match('#^/\*\*(.*)\*/#s', trim($pString), $comment); if (0 === count($comment)) return array(); $comment = trim($comment[1]); preg_match_all('/^\s*\*(.*)/m', $comment, $lines); $lines = $lines[1]; $tags = array(); $currentTag = ''; $currentData = ''; foreach ($lines as $line) { $line = trim($line); if (substr($line, 0, 1) == '@') { if ($currentTag) $tags[$currentTag][] = $currentData; else $tags['description'] = $currentData; $currentData = ''; preg_match('/@([a-zA-Z_]*)/', $line, $match); $currentTag = $match[1]; } $currentData = trim($currentData.' '.$line); } if ($currentTag) $tags[$currentTag][] = $currentData; else $tags['description'] = $currentData; //parse tags $regex = array( 'param' => array('/^@param\s*\t*([a-zA-Z_\\\[\]]*)\s*\t*\$([a-zA-Z_]*)\s*\t*(.*)/', array('type', 'name', 'description')), 'url' => array('/^@url\s*\t*(.+)/', array('url')), 'return' => array('/^@return\s*\t*([a-zA-Z_\\\[\]]*)\s*\t*(.*)/', array('type', 'description')), ); foreach ($tags as $tag => &$data) { if ($tag == 'description') continue; foreach ($data as &$item) { if (isset($regex[$tag])) { preg_match($regex[$tag][0], $item, $match); $item = array(); $c = count($match); for ($i =1; $i < $c; $i++) { if (isset($regex[$tag][1][$i-1])) { $item[$regex[$tag][1][$i-1]] = $match[$i]; } } } } if (count($data) == 1) $data = $data[0]; } return $tags; }
php
public function parsePhpDoc($pString) { preg_match('#^/\*\*(.*)\*/#s', trim($pString), $comment); if (0 === count($comment)) return array(); $comment = trim($comment[1]); preg_match_all('/^\s*\*(.*)/m', $comment, $lines); $lines = $lines[1]; $tags = array(); $currentTag = ''; $currentData = ''; foreach ($lines as $line) { $line = trim($line); if (substr($line, 0, 1) == '@') { if ($currentTag) $tags[$currentTag][] = $currentData; else $tags['description'] = $currentData; $currentData = ''; preg_match('/@([a-zA-Z_]*)/', $line, $match); $currentTag = $match[1]; } $currentData = trim($currentData.' '.$line); } if ($currentTag) $tags[$currentTag][] = $currentData; else $tags['description'] = $currentData; //parse tags $regex = array( 'param' => array('/^@param\s*\t*([a-zA-Z_\\\[\]]*)\s*\t*\$([a-zA-Z_]*)\s*\t*(.*)/', array('type', 'name', 'description')), 'url' => array('/^@url\s*\t*(.+)/', array('url')), 'return' => array('/^@return\s*\t*([a-zA-Z_\\\[\]]*)\s*\t*(.*)/', array('type', 'description')), ); foreach ($tags as $tag => &$data) { if ($tag == 'description') continue; foreach ($data as &$item) { if (isset($regex[$tag])) { preg_match($regex[$tag][0], $item, $match); $item = array(); $c = count($match); for ($i =1; $i < $c; $i++) { if (isset($regex[$tag][1][$i-1])) { $item[$regex[$tag][1][$i-1]] = $match[$i]; } } } } if (count($data) == 1) $data = $data[0]; } return $tags; }
[ "public", "function", "parsePhpDoc", "(", "$", "pString", ")", "{", "preg_match", "(", "'#^/\\*\\*(.*)\\*/#s'", ",", "trim", "(", "$", "pString", ")", ",", "$", "comment", ")", ";", "if", "(", "0", "===", "count", "(", "$", "comment", ")", ")", "return...
Parse phpDoc string and returns an array. @param string $pString @return array
[ "Parse", "phpDoc", "string", "and", "returns", "an", "array", "." ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Server.php#L1095-L1158
marcj/php-rest-service
RestService/Server.php
Server.argumentName
public function argumentName($pName) { if (ctype_lower(substr($pName, 0, 1)) && ctype_upper(substr($pName, 1, 1))) { return strtolower(substr($pName, 1, 1)).substr($pName, 2); } return $pName; }
php
public function argumentName($pName) { if (ctype_lower(substr($pName, 0, 1)) && ctype_upper(substr($pName, 1, 1))) { return strtolower(substr($pName, 1, 1)).substr($pName, 2); } return $pName; }
[ "public", "function", "argumentName", "(", "$", "pName", ")", "{", "if", "(", "ctype_lower", "(", "substr", "(", "$", "pName", ",", "0", ",", "1", ")", ")", "&&", "ctype_upper", "(", "substr", "(", "$", "pName", ",", "1", ",", "1", ")", ")", ")",...
If the name is a camelcased one whereas the first char is lowercased, then we remove the first char and set first char to lower case. @param string $pName @return string
[ "If", "the", "name", "is", "a", "camelcased", "one", "whereas", "the", "first", "char", "is", "lowercased", "then", "we", "remove", "the", "first", "char", "and", "set", "first", "char", "to", "lower", "case", "." ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Server.php#L1167-L1172
marcj/php-rest-service
RestService/Server.php
Server.findRoute
public function findRoute($pUri, $pMethod = '_all_') { if (isset($this->routes[$pUri][$pMethod]) && $method = $this->routes[$pUri][$pMethod]) { return array($method, array(), $pMethod, $pUri); } elseif ($pMethod != '_all_' && isset($this->routes[$pUri]['_all_']) && $method = $this->routes[$pUri]['_all_']) { return array($method, array(), $pMethod, $pUri); } else { //maybe we have a regex uri foreach ($this->routes as $routeUri => $routeMethods) { if (preg_match('|^'.$routeUri.'$|', $pUri, $matches)) { if (!isset($routeMethods[$pMethod])) { if (isset($routeMethods['_all_'])) $pMethod = '_all_'; else continue; } array_shift($matches); foreach ($matches as $match) { $arguments[] = $match; } return array($routeMethods[$pMethod], $arguments, $pMethod, $routeUri); } } } return false; }
php
public function findRoute($pUri, $pMethod = '_all_') { if (isset($this->routes[$pUri][$pMethod]) && $method = $this->routes[$pUri][$pMethod]) { return array($method, array(), $pMethod, $pUri); } elseif ($pMethod != '_all_' && isset($this->routes[$pUri]['_all_']) && $method = $this->routes[$pUri]['_all_']) { return array($method, array(), $pMethod, $pUri); } else { //maybe we have a regex uri foreach ($this->routes as $routeUri => $routeMethods) { if (preg_match('|^'.$routeUri.'$|', $pUri, $matches)) { if (!isset($routeMethods[$pMethod])) { if (isset($routeMethods['_all_'])) $pMethod = '_all_'; else continue; } array_shift($matches); foreach ($matches as $match) { $arguments[] = $match; } return array($routeMethods[$pMethod], $arguments, $pMethod, $routeUri); } } } return false; }
[ "public", "function", "findRoute", "(", "$", "pUri", ",", "$", "pMethod", "=", "'_all_'", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "routes", "[", "$", "pUri", "]", "[", "$", "pMethod", "]", ")", "&&", "$", "method", "=", "$", "this",...
Find and return the route for $pUri. @param string $pUri @param string $pMethod limit to method. @return array|boolean
[ "Find", "and", "return", "the", "route", "for", "$pUri", "." ]
train
https://github.com/marcj/php-rest-service/blob/5fb617a6ca415995b26cbc47242311c521a8baba/RestService/Server.php#L1181-L1212
MarkBaker/PHPMatrix
classes/src/Operators/Addition.php
Addition.execute
public function execute($value) { if (is_array($value)) { $value = new Matrix($value); } if (is_object($value) && ($value instanceof Matrix)) { return $this->addMatrix($value); } elseif (is_numeric($value)) { return $this->addScalar($value); } throw new Exception('Invalid argument for addition'); }
php
public function execute($value) { if (is_array($value)) { $value = new Matrix($value); } if (is_object($value) && ($value instanceof Matrix)) { return $this->addMatrix($value); } elseif (is_numeric($value)) { return $this->addScalar($value); } throw new Exception('Invalid argument for addition'); }
[ "public", "function", "execute", "(", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "value", "=", "new", "Matrix", "(", "$", "value", ")", ";", "}", "if", "(", "is_object", "(", "$", "value", ")", "&&", "...
Execute the addition @param mixed $value The matrix or numeric value to add to the current base value @throws Exception If the provided argument is not appropriate for the operation @return $this The operation object, allowing multiple additions to be chained
[ "Execute", "the", "addition" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Operators/Addition.php#L17-L30
MarkBaker/PHPMatrix
classes/src/Operators/Addition.php
Addition.addScalar
protected function addScalar($value) { for ($row = 0; $row < $this->rows; ++$row) { for ($column = 0; $column < $this->columns; ++$column) { $this->matrix[$row][$column] += $value; } } return $this; }
php
protected function addScalar($value) { for ($row = 0; $row < $this->rows; ++$row) { for ($column = 0; $column < $this->columns; ++$column) { $this->matrix[$row][$column] += $value; } } return $this; }
[ "protected", "function", "addScalar", "(", "$", "value", ")", "{", "for", "(", "$", "row", "=", "0", ";", "$", "row", "<", "$", "this", "->", "rows", ";", "++", "$", "row", ")", "{", "for", "(", "$", "column", "=", "0", ";", "$", "column", "<...
Execute the addition for a scalar @param mixed $value The numeric value to add to the current base value @return $this The operation object, allowing multiple additions to be chained
[ "Execute", "the", "addition", "for", "a", "scalar" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Operators/Addition.php#L38-L47
MarkBaker/PHPMatrix
classes/src/Operators/Division.php
Division.execute
public function execute($value) { if (is_array($value)) { $value = new Matrix($value); } if (is_object($value) && ($value instanceof Matrix)) { try { $value = Functions::inverse($value); } catch (Exception $e) { throw new Exception('Division can only be calculated using a matrix with a non-zero determinant'); } return $this->multiplyMatrix($value); } elseif (is_numeric($value)) { return $this->multiplyScalar(1 / $value); } throw new Exception('Invalid argument for division'); }
php
public function execute($value) { if (is_array($value)) { $value = new Matrix($value); } if (is_object($value) && ($value instanceof Matrix)) { try { $value = Functions::inverse($value); } catch (Exception $e) { throw new Exception('Division can only be calculated using a matrix with a non-zero determinant'); } return $this->multiplyMatrix($value); } elseif (is_numeric($value)) { return $this->multiplyScalar(1 / $value); } throw new Exception('Invalid argument for division'); }
[ "public", "function", "execute", "(", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "value", "=", "new", "Matrix", "(", "$", "value", ")", ";", "}", "if", "(", "is_object", "(", "$", "value", ")", "&&", "...
Execute the division @param mixed $value The matrix or numeric value to divide the current base value by @throws Exception If the provided argument is not appropriate for the operation @return $this The operation object, allowing multiple divisions to be chained
[ "Execute", "the", "division" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Operators/Division.php#L18-L37
MarkBaker/PHPMatrix
classes/src/Operators/Operator.php
Operator.validateMatchingDimensions
protected function validateMatchingDimensions(Matrix $matrix) { if (($this->rows != $matrix->rows) || ($this->columns != $matrix->columns)) { throw new Exception('Matrices have mismatched dimensions'); } }
php
protected function validateMatchingDimensions(Matrix $matrix) { if (($this->rows != $matrix->rows) || ($this->columns != $matrix->columns)) { throw new Exception('Matrices have mismatched dimensions'); } }
[ "protected", "function", "validateMatchingDimensions", "(", "Matrix", "$", "matrix", ")", "{", "if", "(", "(", "$", "this", "->", "rows", "!=", "$", "matrix", "->", "rows", ")", "||", "(", "$", "this", "->", "columns", "!=", "$", "matrix", "->", "colum...
Compare the dimensions of the matrices being operated on to see if they are valid for addition/subtraction @param Matrix $matrix The second Matrix object on which the operation will be performed @throws Exception
[ "Compare", "the", "dimensions", "of", "the", "matrices", "being", "operated", "on", "to", "see", "if", "they", "are", "valid", "for", "addition", "/", "subtraction" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Operators/Operator.php#L49-L54
MarkBaker/PHPMatrix
classes/src/Operators/DirectSum.php
DirectSum.execute
public function execute($value) { if (is_array($value)) { $value = new Matrix($value); } if (is_object($value) && ($value instanceof Matrix)) { return $this->directSumMatrix($value); } throw new Exception('Invalid argument for addition'); }
php
public function execute($value) { if (is_array($value)) { $value = new Matrix($value); } if (is_object($value) && ($value instanceof Matrix)) { return $this->directSumMatrix($value); } throw new Exception('Invalid argument for addition'); }
[ "public", "function", "execute", "(", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "value", "=", "new", "Matrix", "(", "$", "value", ")", ";", "}", "if", "(", "is_object", "(", "$", "value", ")", "&&", "...
Execute the addition @param mixed $value The matrix or numeric value to add to the current base value @throws Exception If the provided argument is not appropriate for the operation @return $this The operation object, allowing multiple additions to be chained
[ "Execute", "the", "addition" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Operators/DirectSum.php#L17-L28
MarkBaker/PHPMatrix
classes/src/Operators/DirectSum.php
DirectSum.directSumMatrix
protected function directSumMatrix(Matrix $value) { $originalColumnCount = count($this->matrix[0]); $originalRowCount = count($this->matrix); $additionalColumnCount = $value->columns; $additionalRowCount = $value->rows; $value = $value->toArray(); for ($row = 0; $row < $this->rows; ++$row) { $this->matrix[$row] = array_merge($this->matrix[$row], array_fill(0, $additionalColumnCount, 0)); } $this->matrix = array_merge( $this->matrix, array_fill(0, $additionalRowCount, array_fill(0, $originalColumnCount, 0)) ); for ($row = $originalRowCount; $row < $originalRowCount + $additionalRowCount; ++$row) { array_splice( $this->matrix[$row], $originalColumnCount, $additionalColumnCount, $value[$row - $originalRowCount] ); } return $this; }
php
protected function directSumMatrix(Matrix $value) { $originalColumnCount = count($this->matrix[0]); $originalRowCount = count($this->matrix); $additionalColumnCount = $value->columns; $additionalRowCount = $value->rows; $value = $value->toArray(); for ($row = 0; $row < $this->rows; ++$row) { $this->matrix[$row] = array_merge($this->matrix[$row], array_fill(0, $additionalColumnCount, 0)); } $this->matrix = array_merge( $this->matrix, array_fill(0, $additionalRowCount, array_fill(0, $originalColumnCount, 0)) ); for ($row = $originalRowCount; $row < $originalRowCount + $additionalRowCount; ++$row) { array_splice( $this->matrix[$row], $originalColumnCount, $additionalColumnCount, $value[$row - $originalRowCount] ); } return $this; }
[ "protected", "function", "directSumMatrix", "(", "Matrix", "$", "value", ")", "{", "$", "originalColumnCount", "=", "count", "(", "$", "this", "->", "matrix", "[", "0", "]", ")", ";", "$", "originalRowCount", "=", "count", "(", "$", "this", "->", "matrix...
Execute the direct sum for a matrix @param Matrix $value The numeric value to concatenate/direct sum with the current base value @return $this The operation object, allowing multiple additions to be chained @throws Exception If the provided argument is not appropriate for the operation
[ "Execute", "the", "direct", "sum", "for", "a", "matrix" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Operators/DirectSum.php#L37-L64
MarkBaker/PHPMatrix
classes/src/Matrix.php
Matrix.buildFromArray
protected function buildFromArray(array $grid) { $this->rows = count($grid); $columns = array_reduce( $grid, function ($carry, $value) { return max($carry, is_array($value) ? count($value) : 1); }, 0 ); $this->columns = $columns; array_walk( $grid, function (&$value) use ($columns) { if (!is_array($value)) { $value = [$value]; } $value = array_pad(array_values($value), $columns, null); } ); $this->grid = $grid; }
php
protected function buildFromArray(array $grid) { $this->rows = count($grid); $columns = array_reduce( $grid, function ($carry, $value) { return max($carry, is_array($value) ? count($value) : 1); }, 0 ); $this->columns = $columns; array_walk( $grid, function (&$value) use ($columns) { if (!is_array($value)) { $value = [$value]; } $value = array_pad(array_values($value), $columns, null); } ); $this->grid = $grid; }
[ "protected", "function", "buildFromArray", "(", "array", "$", "grid", ")", "{", "$", "this", "->", "rows", "=", "count", "(", "$", "grid", ")", ";", "$", "columns", "=", "array_reduce", "(", "$", "grid", ",", "function", "(", "$", "carry", ",", "$", ...
/* Create a new Matrix object from an array of values @param array $grid
[ "/", "*", "Create", "a", "new", "Matrix", "object", "from", "an", "array", "of", "values" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Matrix.php#L57-L80
MarkBaker/PHPMatrix
classes/src/Matrix.php
Matrix.validateRowInRange
protected function validateRowInRange($row) { $row = static::validateRow($row); if ($row > $this->rows) { throw new Exception('Requested Row exceeds matrix size'); } return $row; }
php
protected function validateRowInRange($row) { $row = static::validateRow($row); if ($row > $this->rows) { throw new Exception('Requested Row exceeds matrix size'); } return $row; }
[ "protected", "function", "validateRowInRange", "(", "$", "row", ")", "{", "$", "row", "=", "static", "::", "validateRow", "(", "$", "row", ")", ";", "if", "(", "$", "row", ">", "$", "this", "->", "rows", ")", "{", "throw", "new", "Exception", "(", ...
Validate that a row number falls within the set of rows for this matrix @param $row @return int @throws Exception
[ "Validate", "that", "a", "row", "number", "falls", "within", "the", "set", "of", "rows", "for", "this", "matrix" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Matrix.php#L121-L129
MarkBaker/PHPMatrix
classes/src/Matrix.php
Matrix.validateColumnInRange
protected function validateColumnInRange($column) { $column = static::validateColumn($column); if ($column > $this->columns) { throw new Exception('Requested Column exceeds matrix size'); } return $column; }
php
protected function validateColumnInRange($column) { $column = static::validateColumn($column); if ($column > $this->columns) { throw new Exception('Requested Column exceeds matrix size'); } return $column; }
[ "protected", "function", "validateColumnInRange", "(", "$", "column", ")", "{", "$", "column", "=", "static", "::", "validateColumn", "(", "$", "column", ")", ";", "if", "(", "$", "column", ">", "$", "this", "->", "columns", ")", "{", "throw", "new", "...
Validate that a column number falls within the set of columns for this matrix @param $column @return int @throws Exception
[ "Validate", "that", "a", "column", "number", "falls", "within", "the", "set", "of", "columns", "for", "this", "matrix" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Matrix.php#L138-L146
MarkBaker/PHPMatrix
classes/src/Matrix.php
Matrix.getRows
public function getRows($row, $rowCount = 1) { $row = $this->validateRowInRange($row); if ($rowCount == 0) { $rowCount = $this->rows - $row + 1; } return new static(array_slice($this->grid, $row - 1, $rowCount)); }
php
public function getRows($row, $rowCount = 1) { $row = $this->validateRowInRange($row); if ($rowCount == 0) { $rowCount = $this->rows - $row + 1; } return new static(array_slice($this->grid, $row - 1, $rowCount)); }
[ "public", "function", "getRows", "(", "$", "row", ",", "$", "rowCount", "=", "1", ")", "{", "$", "row", "=", "$", "this", "->", "validateRowInRange", "(", "$", "row", ")", ";", "if", "(", "$", "rowCount", "==", "0", ")", "{", "$", "rowCount", "="...
Return a new matrix as a subset of rows from this matrix, starting at row number $row, and $rowCount rows A $rowCount value of 0 will return all rows of the matrix from $row A negative $rowCount value will return rows until that many rows from the end of the matrix Note that row numbers start from 1, not from 0 @param $row @param int $rowCount @return static @throws Exception
[ "Return", "a", "new", "matrix", "as", "a", "subset", "of", "rows", "from", "this", "matrix", "starting", "at", "row", "number", "$row", "and", "$rowCount", "rows", "A", "$rowCount", "value", "of", "0", "will", "return", "all", "rows", "of", "the", "matri...
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Matrix.php#L160-L168
MarkBaker/PHPMatrix
classes/src/Matrix.php
Matrix.getColumns
public function getColumns($column, $columnCount = 1) { $column = $this->validateColumnInRange($column); if ($columnCount < 1) { $columnCount = $this->columns + $columnCount - $column + 1; } $grid = []; for ($i = $column - 1; $i < $column + $columnCount - 1; ++$i) { $grid[] = array_column($this->grid, $i); } return (new static($grid))->transpose(); }
php
public function getColumns($column, $columnCount = 1) { $column = $this->validateColumnInRange($column); if ($columnCount < 1) { $columnCount = $this->columns + $columnCount - $column + 1; } $grid = []; for ($i = $column - 1; $i < $column + $columnCount - 1; ++$i) { $grid[] = array_column($this->grid, $i); } return (new static($grid))->transpose(); }
[ "public", "function", "getColumns", "(", "$", "column", ",", "$", "columnCount", "=", "1", ")", "{", "$", "column", "=", "$", "this", "->", "validateColumnInRange", "(", "$", "column", ")", ";", "if", "(", "$", "columnCount", "<", "1", ")", "{", "$",...
Return a new matrix as a subset of columns from this matrix, starting at column number $column, and $columnCount columns A $columnCount value of 0 will return all columns of the matrix from $column A negative $columnCount value will return columns until that many columns from the end of the matrix Note that column numbers start from 1, not from 0 @param $column @param int $columnCount @return static @throws Exception
[ "Return", "a", "new", "matrix", "as", "a", "subset", "of", "columns", "from", "this", "matrix", "starting", "at", "column", "number", "$column", "and", "$columnCount", "columns", "A", "$columnCount", "value", "of", "0", "will", "return", "all", "columns", "o...
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Matrix.php#L182-L195
MarkBaker/PHPMatrix
classes/src/Matrix.php
Matrix.dropRows
public function dropRows($row, $rowCount = 1) { $this->validateRowInRange($row); if ($rowCount == 0) { $rowCount = $this->rows - $row + 1; } $grid = $this->grid; array_splice($grid, $row - 1, $rowCount); return new static($grid); }
php
public function dropRows($row, $rowCount = 1) { $this->validateRowInRange($row); if ($rowCount == 0) { $rowCount = $this->rows - $row + 1; } $grid = $this->grid; array_splice($grid, $row - 1, $rowCount); return new static($grid); }
[ "public", "function", "dropRows", "(", "$", "row", ",", "$", "rowCount", "=", "1", ")", "{", "$", "this", "->", "validateRowInRange", "(", "$", "row", ")", ";", "if", "(", "$", "rowCount", "==", "0", ")", "{", "$", "rowCount", "=", "$", "this", "...
Return a new matrix as a subset of rows from this matrix, dropping rows starting at row number $row, and $rowCount rows A negative $rowCount value will drop rows until that many rows from the end of the matrix A $rowCount value of 0 will remove all rows of the matrix from $row Note that row numbers start from 1, not from 0 @param $row @param int $rowCount @return static @throws Exception
[ "Return", "a", "new", "matrix", "as", "a", "subset", "of", "rows", "from", "this", "matrix", "dropping", "rows", "starting", "at", "row", "number", "$row", "and", "$rowCount", "rows", "A", "negative", "$rowCount", "value", "will", "drop", "rows", "until", ...
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Matrix.php#L210-L221
MarkBaker/PHPMatrix
classes/src/Matrix.php
Matrix.dropColumns
public function dropColumns($column, $columnCount = 1) { $this->validateColumnInRange($column); if ($columnCount < 1) { $columnCount = $this->columns + $columnCount - $column + 1; } $grid = $this->grid; array_walk( $grid, function (&$row) use ($column, $columnCount) { array_splice($row, $column - 1, $columnCount); } ); return new static($grid); }
php
public function dropColumns($column, $columnCount = 1) { $this->validateColumnInRange($column); if ($columnCount < 1) { $columnCount = $this->columns + $columnCount - $column + 1; } $grid = $this->grid; array_walk( $grid, function (&$row) use ($column, $columnCount) { array_splice($row, $column - 1, $columnCount); } ); return new static($grid); }
[ "public", "function", "dropColumns", "(", "$", "column", ",", "$", "columnCount", "=", "1", ")", "{", "$", "this", "->", "validateColumnInRange", "(", "$", "column", ")", ";", "if", "(", "$", "columnCount", "<", "1", ")", "{", "$", "columnCount", "=", ...
Return a new matrix as a subset of columns from this matrix, dropping columns starting at column number $column, and $columnCount columns A negative $columnCount value will drop columns until that many columns from the end of the matrix A $columnCount value of 0 will remove all columns of the matrix from $column Note that column numbers start from 1, not from 0 @param $column @param int $columnCount @return static @throws Exception
[ "Return", "a", "new", "matrix", "as", "a", "subset", "of", "columns", "from", "this", "matrix", "dropping", "columns", "starting", "at", "column", "number", "$column", "and", "$columnCount", "columns", "A", "negative", "$columnCount", "value", "will", "drop", ...
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Matrix.php#L236-L252
MarkBaker/PHPMatrix
classes/src/Matrix.php
Matrix.getValue
public function getValue($row, $column) { $row = $this->validateRowInRange($row); $column = $this->validateColumnInRange($column); return $this->grid[$row - 1][$column - 1]; }
php
public function getValue($row, $column) { $row = $this->validateRowInRange($row); $column = $this->validateColumnInRange($column); return $this->grid[$row - 1][$column - 1]; }
[ "public", "function", "getValue", "(", "$", "row", ",", "$", "column", ")", "{", "$", "row", "=", "$", "this", "->", "validateRowInRange", "(", "$", "row", ")", ";", "$", "column", "=", "$", "this", "->", "validateColumnInRange", "(", "$", "column", ...
Return a value from this matrix, from the "cell" identified by the row and column numbers Note that row and column numbers start from 1, not from 0 @param $row @param $column @return static @throws Exception
[ "Return", "a", "value", "from", "this", "matrix", "from", "the", "cell", "identified", "by", "the", "row", "and", "column", "numbers", "Note", "that", "row", "and", "column", "numbers", "start", "from", "1", "not", "from", "0" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Matrix.php#L263-L269
MarkBaker/PHPMatrix
classes/src/Matrix.php
Matrix.rows
public function rows() { foreach ($this->grid as $i => $row) { yield $i + 1 => ($this->columns == 1) ? $row[0] : new static([$row]); } }
php
public function rows() { foreach ($this->grid as $i => $row) { yield $i + 1 => ($this->columns == 1) ? $row[0] : new static([$row]); } }
[ "public", "function", "rows", "(", ")", "{", "foreach", "(", "$", "this", "->", "grid", "as", "$", "i", "=>", "$", "row", ")", "{", "yield", "$", "i", "+", "1", "=>", "(", "$", "this", "->", "columns", "==", "1", ")", "?", "$", "row", "[", ...
Returns a Generator that will yield each row of the matrix in turn as a vector matrix or the value of each cell if the matrix is a vector @return \Generator|Matrix[]|mixed[]
[ "Returns", "a", "Generator", "that", "will", "yield", "each", "row", "of", "the", "matrix", "in", "turn", "as", "a", "vector", "matrix", "or", "the", "value", "of", "each", "cell", "if", "the", "matrix", "is", "a", "vector" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Matrix.php#L277-L284
MarkBaker/PHPMatrix
classes/src/Matrix.php
Matrix.columns
public function columns() { for ($i = 0; $i < $this->columns; ++$i) { yield $i + 1 => ($this->rows == 1) ? $this->grid[0][$i] : new static(array_column($this->grid, $i)); } }
php
public function columns() { for ($i = 0; $i < $this->columns; ++$i) { yield $i + 1 => ($this->rows == 1) ? $this->grid[0][$i] : new static(array_column($this->grid, $i)); } }
[ "public", "function", "columns", "(", ")", "{", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "this", "->", "columns", ";", "++", "$", "i", ")", "{", "yield", "$", "i", "+", "1", "=>", "(", "$", "this", "->", "rows", "==", "1", ...
Returns a Generator that will yield each column of the matrix in turn as a vector matrix or the value of each cell if the matrix is a vector @return \Generator|Matrix[]|mixed[]
[ "Returns", "a", "Generator", "that", "will", "yield", "each", "column", "of", "the", "matrix", "in", "turn", "as", "a", "vector", "matrix", "or", "the", "value", "of", "each", "cell", "if", "the", "matrix", "is", "a", "vector" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Matrix.php#L292-L299
MarkBaker/PHPMatrix
classes/src/Functions.php
Functions.getCofactors
private static function getCofactors(Matrix $matrix) { $cofactors = self::getMinors($matrix); $dimensions = $matrix->rows; $cof = 1; for ($i = 0; $i < $dimensions; ++$i) { $cofs = $cof; for ($j = 0; $j < $dimensions; ++$j) { $cofactors[$i][$j] *= $cofs; $cofs = -$cofs; } $cof = -$cof; } return new Matrix($cofactors); }
php
private static function getCofactors(Matrix $matrix) { $cofactors = self::getMinors($matrix); $dimensions = $matrix->rows; $cof = 1; for ($i = 0; $i < $dimensions; ++$i) { $cofs = $cof; for ($j = 0; $j < $dimensions; ++$j) { $cofactors[$i][$j] *= $cofs; $cofs = -$cofs; } $cof = -$cof; } return new Matrix($cofactors); }
[ "private", "static", "function", "getCofactors", "(", "Matrix", "$", "matrix", ")", "{", "$", "cofactors", "=", "self", "::", "getMinors", "(", "$", "matrix", ")", ";", "$", "dimensions", "=", "$", "matrix", "->", "rows", ";", "$", "cof", "=", "1", "...
Calculate the cofactors of the matrix @param Matrix $matrix The matrix whose cofactors we wish to calculate @return Matrix
[ "Calculate", "the", "cofactors", "of", "the", "matrix" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Functions.php#L45-L61
MarkBaker/PHPMatrix
classes/src/Functions.php
Functions.getDeterminant
private static function getDeterminant(Matrix $matrix) { $dimensions = $matrix->rows; if ($dimensions == 1) { return $matrix->getValue(1, 1); } elseif ($dimensions == 2) { return $matrix->getValue(1, 1) * $matrix->getValue(2, 2) - $matrix->getValue(1, 2) * $matrix->getValue(2, 1); } $determinant = 0; for ($i = 1; $i <= $dimensions; ++$i) { $det = $matrix->getValue(1, $i) * self::getDeterminantSegment($matrix, 0, $i-1); if (($i % 2) == 0) { $determinant -= $det; } else { $determinant += $det; } } return $determinant; }
php
private static function getDeterminant(Matrix $matrix) { $dimensions = $matrix->rows; if ($dimensions == 1) { return $matrix->getValue(1, 1); } elseif ($dimensions == 2) { return $matrix->getValue(1, 1) * $matrix->getValue(2, 2) - $matrix->getValue(1, 2) * $matrix->getValue(2, 1); } $determinant = 0; for ($i = 1; $i <= $dimensions; ++$i) { $det = $matrix->getValue(1, $i) * self::getDeterminantSegment($matrix, 0, $i-1); if (($i % 2) == 0) { $determinant -= $det; } else { $determinant += $det; } } return $determinant; }
[ "private", "static", "function", "getDeterminant", "(", "Matrix", "$", "matrix", ")", "{", "$", "dimensions", "=", "$", "matrix", "->", "rows", ";", "if", "(", "$", "dimensions", "==", "1", ")", "{", "return", "$", "matrix", "->", "getValue", "(", "1",...
Calculate the determinant of the matrix @param Matrix $matrix The matrix whose determinant we wish to calculate @return float
[ "Calculate", "the", "determinant", "of", "the", "matrix" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Functions.php#L99-L119
MarkBaker/PHPMatrix
classes/src/Functions.php
Functions.antidiagonal
public static function antidiagonal(Matrix $matrix) { if (!$matrix->isSquare()) { throw new Exception('Anti-Diagonal can only be extracted from a square matrix'); } $dimensions = $matrix->rows; $grid = Builder::createFilledMatrix(0, $dimensions, $dimensions) ->toArray(); for ($i = 0; $i < $dimensions; ++$i) { $grid[$i][$dimensions - $i - 1] = $matrix->getValue($i + 1, $dimensions - $i); } return new Matrix($grid); }
php
public static function antidiagonal(Matrix $matrix) { if (!$matrix->isSquare()) { throw new Exception('Anti-Diagonal can only be extracted from a square matrix'); } $dimensions = $matrix->rows; $grid = Builder::createFilledMatrix(0, $dimensions, $dimensions) ->toArray(); for ($i = 0; $i < $dimensions; ++$i) { $grid[$i][$dimensions - $i - 1] = $matrix->getValue($i + 1, $dimensions - $i); } return new Matrix($grid); }
[ "public", "static", "function", "antidiagonal", "(", "Matrix", "$", "matrix", ")", "{", "if", "(", "!", "$", "matrix", "->", "isSquare", "(", ")", ")", "{", "throw", "new", "Exception", "(", "'Anti-Diagonal can only be extracted from a square matrix'", ")", ";",...
Return the antidiagonal of this matrix @param Matrix $matrix The matrix whose antidiagonal we wish to calculate @return Matrix @throws Exception
[ "Return", "the", "antidiagonal", "of", "this", "matrix" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Functions.php#L168-L183
MarkBaker/PHPMatrix
classes/src/Functions.php
Functions.identity
public static function identity(Matrix $matrix) { if (!$matrix->isSquare()) { throw new Exception('Identity can only be created for a square matrix'); } $dimensions = $matrix->rows; return Builder::createIdentityMatrix($dimensions); }
php
public static function identity(Matrix $matrix) { if (!$matrix->isSquare()) { throw new Exception('Identity can only be created for a square matrix'); } $dimensions = $matrix->rows; return Builder::createIdentityMatrix($dimensions); }
[ "public", "static", "function", "identity", "(", "Matrix", "$", "matrix", ")", "{", "if", "(", "!", "$", "matrix", "->", "isSquare", "(", ")", ")", "{", "throw", "new", "Exception", "(", "'Identity can only be created for a square matrix'", ")", ";", "}", "$...
Return the identity matrix The identity matrix, or sometimes ambiguously called a unit matrix, of size n is the n × n square matrix with ones on the main diagonal and zeros elsewhere @param Matrix $matrix The matrix whose identity we wish to calculate @return Matrix @throws Exception
[ "Return", "the", "identity", "matrix", "The", "identity", "matrix", "or", "sometimes", "ambiguously", "called", "a", "unit", "matrix", "of", "size", "n", "is", "the", "n", "×", "n", "square", "matrix", "with", "ones", "on", "the", "main", "diagonal", "and"...
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Functions.php#L194-L203
MarkBaker/PHPMatrix
classes/src/Functions.php
Functions.inverse
public static function inverse(Matrix $matrix) { if (!$matrix->isSquare()) { throw new Exception('Inverse can only be calculated for a square matrix'); } $determinant = self::getDeterminant($matrix); if ($determinant == 0.0) { throw new Exception('Inverse can only be calculated for a matrix with a non-zero determinant'); } if ($matrix->rows == 1) { return new Matrix([[1 / $matrix->getValue(1, 1)]]); } return self::getAdjoint($matrix) ->multiply(1 / $determinant); }
php
public static function inverse(Matrix $matrix) { if (!$matrix->isSquare()) { throw new Exception('Inverse can only be calculated for a square matrix'); } $determinant = self::getDeterminant($matrix); if ($determinant == 0.0) { throw new Exception('Inverse can only be calculated for a matrix with a non-zero determinant'); } if ($matrix->rows == 1) { return new Matrix([[1 / $matrix->getValue(1, 1)]]); } return self::getAdjoint($matrix) ->multiply(1 / $determinant); }
[ "public", "static", "function", "inverse", "(", "Matrix", "$", "matrix", ")", "{", "if", "(", "!", "$", "matrix", "->", "isSquare", "(", ")", ")", "{", "throw", "new", "Exception", "(", "'Inverse can only be calculated for a square matrix'", ")", ";", "}", "...
Return the inverse of this matrix @param Matrix $matrix The matrix whose inverse we wish to calculate @return Matrix @throws Exception
[ "Return", "the", "inverse", "of", "this", "matrix" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Functions.php#L212-L229
MarkBaker/PHPMatrix
classes/src/Functions.php
Functions.getMinors
protected static function getMinors(Matrix $matrix) { $minors = $matrix->toArray(); $dimensions = $matrix->rows; if ($dimensions == 1) { return $minors; } for ($i = 0; $i < $dimensions; ++$i) { for ($j = 0; $j < $dimensions; ++$j) { $minors[$i][$j] = self::getDeterminantSegment($matrix, $i, $j); } } return $minors; }
php
protected static function getMinors(Matrix $matrix) { $minors = $matrix->toArray(); $dimensions = $matrix->rows; if ($dimensions == 1) { return $minors; } for ($i = 0; $i < $dimensions; ++$i) { for ($j = 0; $j < $dimensions; ++$j) { $minors[$i][$j] = self::getDeterminantSegment($matrix, $i, $j); } } return $minors; }
[ "protected", "static", "function", "getMinors", "(", "Matrix", "$", "matrix", ")", "{", "$", "minors", "=", "$", "matrix", "->", "toArray", "(", ")", ";", "$", "dimensions", "=", "$", "matrix", "->", "rows", ";", "if", "(", "$", "dimensions", "==", "...
Calculate the minors of the matrix @param Matrix $matrix The matrix whose minors we wish to calculate @return array[]
[ "Calculate", "the", "minors", "of", "the", "matrix" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Functions.php#L237-L252
MarkBaker/PHPMatrix
classes/src/Functions.php
Functions.minors
public static function minors(Matrix $matrix) { if (!$matrix->isSquare()) { throw new Exception('Minors can only be calculated for a square matrix'); } return new Matrix(self::getMinors($matrix)); }
php
public static function minors(Matrix $matrix) { if (!$matrix->isSquare()) { throw new Exception('Minors can only be calculated for a square matrix'); } return new Matrix(self::getMinors($matrix)); }
[ "public", "static", "function", "minors", "(", "Matrix", "$", "matrix", ")", "{", "if", "(", "!", "$", "matrix", "->", "isSquare", "(", ")", ")", "{", "throw", "new", "Exception", "(", "'Minors can only be calculated for a square matrix'", ")", ";", "}", "re...
Return the minors of the matrix The minor of a matrix A is the determinant of some smaller square matrix, cut down from A by removing one or more of its rows or columns. Minors obtained by removing just one row and one column from square matrices (first minors) are required for calculating matrix cofactors, which in turn are useful for computing both the determinant and inverse of square matrices. @param Matrix $matrix The matrix whose minors we wish to calculate @return Matrix @throws Exception
[ "Return", "the", "minors", "of", "the", "matrix", "The", "minor", "of", "a", "matrix", "A", "is", "the", "determinant", "of", "some", "smaller", "square", "matrix", "cut", "down", "from", "A", "by", "removing", "one", "or", "more", "of", "its", "rows", ...
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Functions.php#L266-L273
MarkBaker/PHPMatrix
classes/src/Functions.php
Functions.trace
public static function trace(Matrix $matrix) { if (!$matrix->isSquare()) { throw new Exception('Trace can only be extracted from a square matrix'); } $dimensions = $matrix->rows; $result = 0; for ($i = 1; $i <= $dimensions; ++$i) { $result += $matrix->getValue($i, $i); } return $result; }
php
public static function trace(Matrix $matrix) { if (!$matrix->isSquare()) { throw new Exception('Trace can only be extracted from a square matrix'); } $dimensions = $matrix->rows; $result = 0; for ($i = 1; $i <= $dimensions; ++$i) { $result += $matrix->getValue($i, $i); } return $result; }
[ "public", "static", "function", "trace", "(", "Matrix", "$", "matrix", ")", "{", "if", "(", "!", "$", "matrix", "->", "isSquare", "(", ")", ")", "{", "throw", "new", "Exception", "(", "'Trace can only be extracted from a square matrix'", ")", ";", "}", "$", ...
Return the trace of this matrix The trace is defined as the sum of the elements on the main diagonal (the diagonal from the upper left to the lower right) of the matrix @param Matrix $matrix The matrix whose trace we wish to calculate @return float @throws Exception
[ "Return", "the", "trace", "of", "this", "matrix", "The", "trace", "is", "defined", "as", "the", "sum", "of", "the", "elements", "on", "the", "main", "diagonal", "(", "the", "diagonal", "from", "the", "upper", "left", "to", "the", "lower", "right", ")", ...
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Functions.php#L284-L297
MarkBaker/PHPMatrix
classes/src/Functions.php
Functions.transpose
public static function transpose(Matrix $matrix) { $grid = call_user_func_array( 'array_map', array_merge( [null], $matrix->toArray() ) ); return new Matrix($grid); }
php
public static function transpose(Matrix $matrix) { $grid = call_user_func_array( 'array_map', array_merge( [null], $matrix->toArray() ) ); return new Matrix($grid); }
[ "public", "static", "function", "transpose", "(", "Matrix", "$", "matrix", ")", "{", "$", "grid", "=", "call_user_func_array", "(", "'array_map'", ",", "array_merge", "(", "[", "null", "]", ",", "$", "matrix", "->", "toArray", "(", ")", ")", ")", ";", ...
Return the transpose of this matrix @param Matrix $matrix The matrix whose transpose we wish to calculate @return Matrix @throws Exception
[ "Return", "the", "transpose", "of", "this", "matrix" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Functions.php#L306-L317
MarkBaker/PHPMatrix
classes/src/Operators/Subtraction.php
Subtraction.execute
public function execute($value) { if (is_array($value)) { $value = new Matrix($value); } if (is_object($value) && ($value instanceof Matrix)) { return $this->subtractMatrix($value); } elseif (is_numeric($value)) { return $this->subtractScalar($value); } throw new Exception('Invalid argument for subtraction'); }
php
public function execute($value) { if (is_array($value)) { $value = new Matrix($value); } if (is_object($value) && ($value instanceof Matrix)) { return $this->subtractMatrix($value); } elseif (is_numeric($value)) { return $this->subtractScalar($value); } throw new Exception('Invalid argument for subtraction'); }
[ "public", "function", "execute", "(", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "value", "=", "new", "Matrix", "(", "$", "value", ")", ";", "}", "if", "(", "is_object", "(", "$", "value", ")", "&&", "...
Execute the subtraction @param mixed $value The matrix or numeric value to subtract from the current base value @throws Exception If the provided argument is not appropriate for the operation @return $this The operation object, allowing multiple subtractions to be chained
[ "Execute", "the", "subtraction" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Operators/Subtraction.php#L17-L30
MarkBaker/PHPMatrix
classes/src/Operators/Subtraction.php
Subtraction.subtractScalar
protected function subtractScalar($value) { for ($row = 0; $row < $this->rows; ++$row) { for ($column = 0; $column < $this->columns; ++$column) { $this->matrix[$row][$column] -= $value; } } return $this; }
php
protected function subtractScalar($value) { for ($row = 0; $row < $this->rows; ++$row) { for ($column = 0; $column < $this->columns; ++$column) { $this->matrix[$row][$column] -= $value; } } return $this; }
[ "protected", "function", "subtractScalar", "(", "$", "value", ")", "{", "for", "(", "$", "row", "=", "0", ";", "$", "row", "<", "$", "this", "->", "rows", ";", "++", "$", "row", ")", "{", "for", "(", "$", "column", "=", "0", ";", "$", "column",...
Execute the subtraction for a scalar @param mixed $value The numeric value to subtracted from the current base value @return $this The operation object, allowing multiple additions to be chained
[ "Execute", "the", "subtraction", "for", "a", "scalar" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Operators/Subtraction.php#L38-L47
MarkBaker/PHPMatrix
classes/src/Operators/Subtraction.php
Subtraction.subtractMatrix
protected function subtractMatrix(Matrix $value) { $this->validateMatchingDimensions($value); for ($row = 0; $row < $this->rows; ++$row) { for ($column = 0; $column < $this->columns; ++$column) { $this->matrix[$row][$column] -= $value->getValue($row + 1, $column + 1); } } return $this; }
php
protected function subtractMatrix(Matrix $value) { $this->validateMatchingDimensions($value); for ($row = 0; $row < $this->rows; ++$row) { for ($column = 0; $column < $this->columns; ++$column) { $this->matrix[$row][$column] -= $value->getValue($row + 1, $column + 1); } } return $this; }
[ "protected", "function", "subtractMatrix", "(", "Matrix", "$", "value", ")", "{", "$", "this", "->", "validateMatchingDimensions", "(", "$", "value", ")", ";", "for", "(", "$", "row", "=", "0", ";", "$", "row", "<", "$", "this", "->", "rows", ";", "+...
Execute the subtraction for a matrix @param Matrix $value The numeric value to subtract from the current base value @return $this The operation object, allowing multiple subtractions to be chained @throws Exception If the provided argument is not appropriate for the operation
[ "Execute", "the", "subtraction", "for", "a", "matrix" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Operators/Subtraction.php#L56-L67
MarkBaker/PHPMatrix
classes/src/Operators/Multiplication.php
Multiplication.execute
public function execute($value) { if (is_array($value)) { $value = new Matrix($value); } if (is_object($value) && ($value instanceof Matrix)) { return $this->multiplyMatrix($value); } elseif (is_numeric($value)) { return $this->multiplyScalar($value); } throw new Exception('Invalid argument for multiplication'); }
php
public function execute($value) { if (is_array($value)) { $value = new Matrix($value); } if (is_object($value) && ($value instanceof Matrix)) { return $this->multiplyMatrix($value); } elseif (is_numeric($value)) { return $this->multiplyScalar($value); } throw new Exception('Invalid argument for multiplication'); }
[ "public", "function", "execute", "(", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "value", "=", "new", "Matrix", "(", "$", "value", ")", ";", "}", "if", "(", "is_object", "(", "$", "value", ")", "&&", "...
Execute the multiplication @param mixed $value The matrix or numeric value to multiply the current base value by @throws Exception If the provided argument is not appropriate for the operation @return $this The operation object, allowing multiple multiplications to be chained
[ "Execute", "the", "multiplication" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Operators/Multiplication.php#L18-L31
MarkBaker/PHPMatrix
classes/src/Operators/Multiplication.php
Multiplication.multiplyScalar
protected function multiplyScalar($value) { for ($row = 0; $row < $this->rows; ++$row) { for ($column = 0; $column < $this->columns; ++$column) { $this->matrix[$row][$column] *= $value; } } return $this; }
php
protected function multiplyScalar($value) { for ($row = 0; $row < $this->rows; ++$row) { for ($column = 0; $column < $this->columns; ++$column) { $this->matrix[$row][$column] *= $value; } } return $this; }
[ "protected", "function", "multiplyScalar", "(", "$", "value", ")", "{", "for", "(", "$", "row", "=", "0", ";", "$", "row", "<", "$", "this", "->", "rows", ";", "++", "$", "row", ")", "{", "for", "(", "$", "column", "=", "0", ";", "$", "column",...
Execute the multiplication for a scalar @param mixed $value The numeric value to multiply with the current base value @return $this The operation object, allowing multiple mutiplications to be chained
[ "Execute", "the", "multiplication", "for", "a", "scalar" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Operators/Multiplication.php#L39-L48
MarkBaker/PHPMatrix
classes/src/Operators/Multiplication.php
Multiplication.multiplyMatrix
protected function multiplyMatrix(Matrix $value) { $this->validateReflectingDimensions($value); $newRows = $this->rows; $newColumns = $value->columns; $matrix = Builder::createFilledMatrix(0, $newRows, $newColumns) ->toArray(); for ($row = 0; $row < $newRows; ++$row) { for ($column = 0; $column < $newColumns; ++$column) { $columnData = $value->getColumns($column + 1)->toArray(); foreach ($this->matrix[$row] as $key => $valueData) { $matrix[$row][$column] += $valueData * $columnData[$key][0]; } } } $this->matrix = $matrix; return $this; }
php
protected function multiplyMatrix(Matrix $value) { $this->validateReflectingDimensions($value); $newRows = $this->rows; $newColumns = $value->columns; $matrix = Builder::createFilledMatrix(0, $newRows, $newColumns) ->toArray(); for ($row = 0; $row < $newRows; ++$row) { for ($column = 0; $column < $newColumns; ++$column) { $columnData = $value->getColumns($column + 1)->toArray(); foreach ($this->matrix[$row] as $key => $valueData) { $matrix[$row][$column] += $valueData * $columnData[$key][0]; } } } $this->matrix = $matrix; return $this; }
[ "protected", "function", "multiplyMatrix", "(", "Matrix", "$", "value", ")", "{", "$", "this", "->", "validateReflectingDimensions", "(", "$", "value", ")", ";", "$", "newRows", "=", "$", "this", "->", "rows", ";", "$", "newColumns", "=", "$", "value", "...
Execute the multiplication for a matrix @param Matrix $value The numeric value to multiply with the current base value @return $this The operation object, allowing multiple mutiplications to be chained @throws Exception If the provided argument is not appropriate for the operation
[ "Execute", "the", "multiplication", "for", "a", "matrix" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Operators/Multiplication.php#L57-L76
MarkBaker/PHPMatrix
classes/Autoloader.php
Autoloader.Load
public static function Load($pClassName) { if ((class_exists($pClassName, false)) || (strpos($pClassName, 'Matrix\\') !== 0)) { // Either already loaded, or not a Matrix class request return false; } $pClassFilePath = __DIR__ . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . str_replace(['Matrix\\', '\\'], ['', '/'], $pClassName) . '.php'; if ((file_exists($pClassFilePath) === false) || (is_readable($pClassFilePath) === false)) { // Can't load return false; } require($pClassFilePath); }
php
public static function Load($pClassName) { if ((class_exists($pClassName, false)) || (strpos($pClassName, 'Matrix\\') !== 0)) { // Either already loaded, or not a Matrix class request return false; } $pClassFilePath = __DIR__ . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . str_replace(['Matrix\\', '\\'], ['', '/'], $pClassName) . '.php'; if ((file_exists($pClassFilePath) === false) || (is_readable($pClassFilePath) === false)) { // Can't load return false; } require($pClassFilePath); }
[ "public", "static", "function", "Load", "(", "$", "pClassName", ")", "{", "if", "(", "(", "class_exists", "(", "$", "pClassName", ",", "false", ")", ")", "||", "(", "strpos", "(", "$", "pClassName", ",", "'Matrix\\\\'", ")", "!==", "0", ")", ")", "{"...
Autoload a class identified by name @param string $pClassName Name of the object to load
[ "Autoload", "a", "class", "identified", "by", "name" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/Autoloader.php#L35-L52
MarkBaker/PHPMatrix
classes/src/Builder.php
Builder.createFilledMatrix
public static function createFilledMatrix($value, $rows, $columns = null) { if ($columns === null) { $columns = $rows; } $rows = Matrix::validateRow($rows); $columns = Matrix::validateColumn($columns); return new Matrix( array_fill( 0, $rows, array_fill( 0, $columns, $value ) ) ); }
php
public static function createFilledMatrix($value, $rows, $columns = null) { if ($columns === null) { $columns = $rows; } $rows = Matrix::validateRow($rows); $columns = Matrix::validateColumn($columns); return new Matrix( array_fill( 0, $rows, array_fill( 0, $columns, $value ) ) ); }
[ "public", "static", "function", "createFilledMatrix", "(", "$", "value", ",", "$", "rows", ",", "$", "columns", "=", "null", ")", "{", "if", "(", "$", "columns", "===", "null", ")", "{", "$", "columns", "=", "$", "rows", ";", "}", "$", "rows", "=",...
Create a new matrix of specified dimensions, and filled with a specified value If the column argument isn't provided, then a square matrix will be created @param $value @param $rows @param null $columns @return Matrix @throws Exception
[ "Create", "a", "new", "matrix", "of", "specified", "dimensions", "and", "filled", "with", "a", "specified", "value", "If", "the", "column", "argument", "isn", "t", "provided", "then", "a", "square", "matrix", "will", "be", "created" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Builder.php#L29-L49
MarkBaker/PHPMatrix
classes/src/Builder.php
Builder.createIdentityMatrix
public static function createIdentityMatrix($dimensions) { $grid = static::createFilledMatrix(null, $dimensions)->toArray(); for ($x = 0; $x < $dimensions; ++$x) { $grid[$x][$x] = 1; } return new Matrix($grid); }
php
public static function createIdentityMatrix($dimensions) { $grid = static::createFilledMatrix(null, $dimensions)->toArray(); for ($x = 0; $x < $dimensions; ++$x) { $grid[$x][$x] = 1; } return new Matrix($grid); }
[ "public", "static", "function", "createIdentityMatrix", "(", "$", "dimensions", ")", "{", "$", "grid", "=", "static", "::", "createFilledMatrix", "(", "null", ",", "$", "dimensions", ")", "->", "toArray", "(", ")", ";", "for", "(", "$", "x", "=", "0", ...
Create a new identity matrix of specified dimensions This will always be a square matrix, with the number of rows and columns matching the provided dimension @param int $dimensions @return Matrix @throws Exception
[ "Create", "a", "new", "identity", "matrix", "of", "specified", "dimensions", "This", "will", "always", "be", "a", "square", "matrix", "with", "the", "number", "of", "rows", "and", "columns", "matching", "the", "provided", "dimension" ]
train
https://github.com/MarkBaker/PHPMatrix/blob/52e108da3002a2dd7a73624d28e690e43deb3396/classes/src/Builder.php#L59-L68
Ocramius/GeneratedHydrator
src/GeneratedHydrator/Factory/HydratorFactory.php
HydratorFactory.getHydratorClass
public function getHydratorClass() : string { $inflector = $this->configuration->getClassNameInflector(); $realClassName = $inflector->getUserClassName($this->configuration->getHydratedClassName()); $hydratorClassName = $inflector->getGeneratedClassName($realClassName, ['factory' => static::class]); if (! class_exists($hydratorClassName) && $this->configuration->doesAutoGenerateProxies()) { $generator = $this->configuration->getHydratorGenerator(); $originalClass = new ReflectionClass($realClassName); $generatedAst = $generator->generate($originalClass); $traverser = new NodeTraverser(); $traverser->addVisitor(new ClassRenamerVisitor($originalClass, $hydratorClassName)); $this->configuration->getGeneratorStrategy()->generate($traverser->traverse($generatedAst)); $this->configuration->getGeneratedClassAutoloader()->__invoke($hydratorClassName); } return $hydratorClassName; }
php
public function getHydratorClass() : string { $inflector = $this->configuration->getClassNameInflector(); $realClassName = $inflector->getUserClassName($this->configuration->getHydratedClassName()); $hydratorClassName = $inflector->getGeneratedClassName($realClassName, ['factory' => static::class]); if (! class_exists($hydratorClassName) && $this->configuration->doesAutoGenerateProxies()) { $generator = $this->configuration->getHydratorGenerator(); $originalClass = new ReflectionClass($realClassName); $generatedAst = $generator->generate($originalClass); $traverser = new NodeTraverser(); $traverser->addVisitor(new ClassRenamerVisitor($originalClass, $hydratorClassName)); $this->configuration->getGeneratorStrategy()->generate($traverser->traverse($generatedAst)); $this->configuration->getGeneratedClassAutoloader()->__invoke($hydratorClassName); } return $hydratorClassName; }
[ "public", "function", "getHydratorClass", "(", ")", ":", "string", "{", "$", "inflector", "=", "$", "this", "->", "configuration", "->", "getClassNameInflector", "(", ")", ";", "$", "realClassName", "=", "$", "inflector", "->", "getUserClassName", "(", "$", ...
Retrieves the generated hydrator FQCN @throws InvalidGeneratedClassesDirectoryException
[ "Retrieves", "the", "generated", "hydrator", "FQCN" ]
train
https://github.com/Ocramius/GeneratedHydrator/blob/ad230228c71c32279af94ed1484b907cd403886f/src/GeneratedHydrator/Factory/HydratorFactory.php#L32-L51
Ocramius/GeneratedHydrator
benchmarks/GeneratedHydratorBenchmark/ZendHydrationBench.php
ZendHydrationBench.createData
private function createData() : void { $this->data = [ 'foo' => 'some foo string', 'bar' => 42, 'baz' => new DateTime(), 'someFooProperty' => [12, 13, 14], 'someBarProperty' => 12354.4578, 'someBazProperty' => new stdClass(), 'foo1' => 'some foo string', 'bar1' => 42, 'baz1' => new DateTime(), 'someFooProperty1' => [12, 13, 14], 'someBarProperty1' => 12354.4578, 'someBazProperty1' => new stdClass(), 'foo2' => 'some foo string', 'bar2' => 42, 'baz2' => new DateTime(), 'someFooProperty2' => [12, 13, 14], 'someBarProperty2' => 12354.4578, 'someBazProperty2' => new stdClass(), ]; }
php
private function createData() : void { $this->data = [ 'foo' => 'some foo string', 'bar' => 42, 'baz' => new DateTime(), 'someFooProperty' => [12, 13, 14], 'someBarProperty' => 12354.4578, 'someBazProperty' => new stdClass(), 'foo1' => 'some foo string', 'bar1' => 42, 'baz1' => new DateTime(), 'someFooProperty1' => [12, 13, 14], 'someBarProperty1' => 12354.4578, 'someBazProperty1' => new stdClass(), 'foo2' => 'some foo string', 'bar2' => 42, 'baz2' => new DateTime(), 'someFooProperty2' => [12, 13, 14], 'someBarProperty2' => 12354.4578, 'someBazProperty2' => new stdClass(), ]; }
[ "private", "function", "createData", "(", ")", ":", "void", "{", "$", "this", "->", "data", "=", "[", "'foo'", "=>", "'some foo string'", ",", "'bar'", "=>", "42", ",", "'baz'", "=>", "new", "DateTime", "(", ")", ",", "'someFooProperty'", "=>", "[", "1...
Populate test data array
[ "Populate", "test", "data", "array" ]
train
https://github.com/Ocramius/GeneratedHydrator/blob/ad230228c71c32279af94ed1484b907cd403886f/benchmarks/GeneratedHydratorBenchmark/ZendHydrationBench.php#L60-L82
Ocramius/GeneratedHydrator
src/GeneratedHydrator/ClassGenerator/DefaultHydratorGenerator.php
DefaultHydratorGenerator.generate
public function generate(ReflectionClass $originalClass) : array { $ast = [new Class_($originalClass->getShortName())]; $namespace = $originalClass->getNamespaceName(); if ($namespace) { $ast = [new Namespace_(new Name(explode('\\', $namespace)), $ast)]; } $implementor = new NodeTraverser(); $implementor->addVisitor(new HydratorMethodsVisitor($originalClass)); $implementor->addVisitor(new ClassImplementorVisitor($originalClass->getName(), [HydratorInterface::class])); return $implementor->traverse($ast); }
php
public function generate(ReflectionClass $originalClass) : array { $ast = [new Class_($originalClass->getShortName())]; $namespace = $originalClass->getNamespaceName(); if ($namespace) { $ast = [new Namespace_(new Name(explode('\\', $namespace)), $ast)]; } $implementor = new NodeTraverser(); $implementor->addVisitor(new HydratorMethodsVisitor($originalClass)); $implementor->addVisitor(new ClassImplementorVisitor($originalClass->getName(), [HydratorInterface::class])); return $implementor->traverse($ast); }
[ "public", "function", "generate", "(", "ReflectionClass", "$", "originalClass", ")", ":", "array", "{", "$", "ast", "=", "[", "new", "Class_", "(", "$", "originalClass", "->", "getShortName", "(", ")", ")", "]", ";", "$", "namespace", "=", "$", "original...
Generates an AST of {@see \PhpParser\Node[]} out of a given reflection class and a map of properties to be used to @return Node[]
[ "Generates", "an", "AST", "of", "{", "@see", "\\", "PhpParser", "\\", "Node", "[]", "}", "out", "of", "a", "given", "reflection", "class", "and", "a", "map", "of", "properties", "to", "be", "used", "to" ]
train
https://github.com/Ocramius/GeneratedHydrator/blob/ad230228c71c32279af94ed1484b907cd403886f/src/GeneratedHydrator/ClassGenerator/DefaultHydratorGenerator.php#L32-L46
Ocramius/GeneratedHydrator
benchmarks/GeneratedHydratorBenchmark/HydrationBench.php
HydrationBench.createHydrator
protected function createHydrator(string $class) : void { $config = new Configuration($class); $hydratorClass = $config->createFactory()->getHydratorClass(); $this->hydrator = new $hydratorClass(); }
php
protected function createHydrator(string $class) : void { $config = new Configuration($class); $hydratorClass = $config->createFactory()->getHydratorClass(); $this->hydrator = new $hydratorClass(); }
[ "protected", "function", "createHydrator", "(", "string", "$", "class", ")", ":", "void", "{", "$", "config", "=", "new", "Configuration", "(", "$", "class", ")", ";", "$", "hydratorClass", "=", "$", "config", "->", "createFactory", "(", ")", "->", "getH...
Create and set the hydrator
[ "Create", "and", "set", "the", "hydrator" ]
train
https://github.com/Ocramius/GeneratedHydrator/blob/ad230228c71c32279af94ed1484b907cd403886f/benchmarks/GeneratedHydratorBenchmark/HydrationBench.php#L29-L35
symfony/polyfill-php56
Php56.php
Php56.ldap_escape
public static function ldap_escape($subject, $ignore = '', $flags = 0) { static $charMaps = null; if (null === $charMaps) { $charMaps = array( self::LDAP_ESCAPE_FILTER => array('\\', '*', '(', ')', "\x00"), self::LDAP_ESCAPE_DN => array('\\', ',', '=', '+', '<', '>', ';', '"', '#', "\r"), ); $charMaps[0] = array(); for ($i = 0; $i < 256; ++$i) { $charMaps[0][\chr($i)] = sprintf('\\%02x', $i); } for ($i = 0, $l = \count($charMaps[self::LDAP_ESCAPE_FILTER]); $i < $l; ++$i) { $chr = $charMaps[self::LDAP_ESCAPE_FILTER][$i]; unset($charMaps[self::LDAP_ESCAPE_FILTER][$i]); $charMaps[self::LDAP_ESCAPE_FILTER][$chr] = $charMaps[0][$chr]; } for ($i = 0, $l = \count($charMaps[self::LDAP_ESCAPE_DN]); $i < $l; ++$i) { $chr = $charMaps[self::LDAP_ESCAPE_DN][$i]; unset($charMaps[self::LDAP_ESCAPE_DN][$i]); $charMaps[self::LDAP_ESCAPE_DN][$chr] = $charMaps[0][$chr]; } } // Create the base char map to escape $flags = (int) $flags; $charMap = array(); if ($flags & self::LDAP_ESCAPE_FILTER) { $charMap += $charMaps[self::LDAP_ESCAPE_FILTER]; } if ($flags & self::LDAP_ESCAPE_DN) { $charMap += $charMaps[self::LDAP_ESCAPE_DN]; } if (!$charMap) { $charMap = $charMaps[0]; } // Remove any chars to ignore from the list $ignore = (string) $ignore; for ($i = 0, $l = \strlen($ignore); $i < $l; ++$i) { unset($charMap[$ignore[$i]]); } // Do the main replacement $result = strtr($subject, $charMap); // Encode leading/trailing spaces if self::LDAP_ESCAPE_DN is passed if ($flags & self::LDAP_ESCAPE_DN) { if (' ' === $result[0]) { $result = '\\20'.substr($result, 1); } if (' ' === $result[\strlen($result) - 1]) { $result = substr($result, 0, -1).'\\20'; } } return $result; }
php
public static function ldap_escape($subject, $ignore = '', $flags = 0) { static $charMaps = null; if (null === $charMaps) { $charMaps = array( self::LDAP_ESCAPE_FILTER => array('\\', '*', '(', ')', "\x00"), self::LDAP_ESCAPE_DN => array('\\', ',', '=', '+', '<', '>', ';', '"', '#', "\r"), ); $charMaps[0] = array(); for ($i = 0; $i < 256; ++$i) { $charMaps[0][\chr($i)] = sprintf('\\%02x', $i); } for ($i = 0, $l = \count($charMaps[self::LDAP_ESCAPE_FILTER]); $i < $l; ++$i) { $chr = $charMaps[self::LDAP_ESCAPE_FILTER][$i]; unset($charMaps[self::LDAP_ESCAPE_FILTER][$i]); $charMaps[self::LDAP_ESCAPE_FILTER][$chr] = $charMaps[0][$chr]; } for ($i = 0, $l = \count($charMaps[self::LDAP_ESCAPE_DN]); $i < $l; ++$i) { $chr = $charMaps[self::LDAP_ESCAPE_DN][$i]; unset($charMaps[self::LDAP_ESCAPE_DN][$i]); $charMaps[self::LDAP_ESCAPE_DN][$chr] = $charMaps[0][$chr]; } } // Create the base char map to escape $flags = (int) $flags; $charMap = array(); if ($flags & self::LDAP_ESCAPE_FILTER) { $charMap += $charMaps[self::LDAP_ESCAPE_FILTER]; } if ($flags & self::LDAP_ESCAPE_DN) { $charMap += $charMaps[self::LDAP_ESCAPE_DN]; } if (!$charMap) { $charMap = $charMaps[0]; } // Remove any chars to ignore from the list $ignore = (string) $ignore; for ($i = 0, $l = \strlen($ignore); $i < $l; ++$i) { unset($charMap[$ignore[$i]]); } // Do the main replacement $result = strtr($subject, $charMap); // Encode leading/trailing spaces if self::LDAP_ESCAPE_DN is passed if ($flags & self::LDAP_ESCAPE_DN) { if (' ' === $result[0]) { $result = '\\20'.substr($result, 1); } if (' ' === $result[\strlen($result) - 1]) { $result = substr($result, 0, -1).'\\20'; } } return $result; }
[ "public", "static", "function", "ldap_escape", "(", "$", "subject", ",", "$", "ignore", "=", "''", ",", "$", "flags", "=", "0", ")", "{", "static", "$", "charMaps", "=", "null", ";", "if", "(", "null", "===", "$", "charMaps", ")", "{", "$", "charMa...
Stub implementation of the {@link ldap_escape()} function of the ldap extension. Escape strings for safe use in LDAP filters and DNs. @author Chris Wright <ldapi@daverandom.com> @param string $subject @param string $ignore @param int $flags @return string @see http://stackoverflow.com/a/8561604
[ "Stub", "implementation", "of", "the", "{", "@link", "ldap_escape", "()", "}", "function", "of", "the", "ldap", "extension", "." ]
train
https://github.com/symfony/polyfill-php56/blob/f4dddbc5c3471e1b700a147a20ae17cdb72dbe42/Php56.php#L70-L137
steverhoades/oauth2-openid-connect-server
src/ClaimExtractor.php
ClaimExtractor.extract
public function extract(array $scopes, array $claims) { $claimData = []; $keys = array_keys($claims); foreach ($scopes as $scope) { $scopeName = ($scope instanceof ScopeEntityInterface) ? $scope->getIdentifier() : $scope; $claimSet = $this->getClaimSet($scopeName); if (null === $claimSet) { continue; } $intersected = array_intersect($claimSet->getClaims(), $keys); if (empty($intersected)) { continue; } $data = array_filter($claims, function($key) use ($intersected) { return in_array($key, $intersected); }, ARRAY_FILTER_USE_KEY ); $claimData = array_merge($claimData, $data); } return $claimData; }
php
public function extract(array $scopes, array $claims) { $claimData = []; $keys = array_keys($claims); foreach ($scopes as $scope) { $scopeName = ($scope instanceof ScopeEntityInterface) ? $scope->getIdentifier() : $scope; $claimSet = $this->getClaimSet($scopeName); if (null === $claimSet) { continue; } $intersected = array_intersect($claimSet->getClaims(), $keys); if (empty($intersected)) { continue; } $data = array_filter($claims, function($key) use ($intersected) { return in_array($key, $intersected); }, ARRAY_FILTER_USE_KEY ); $claimData = array_merge($claimData, $data); } return $claimData; }
[ "public", "function", "extract", "(", "array", "$", "scopes", ",", "array", "$", "claims", ")", "{", "$", "claimData", "=", "[", "]", ";", "$", "keys", "=", "array_keys", "(", "$", "claims", ")", ";", "foreach", "(", "$", "scopes", "as", "$", "scop...
For given scopes and aggregated claims get all claims that have been configured on the extractor. @param array $scopes @param array $claims @return array
[ "For", "given", "scopes", "and", "aggregated", "claims", "get", "all", "claims", "that", "have", "been", "configured", "on", "the", "extractor", "." ]
train
https://github.com/steverhoades/oauth2-openid-connect-server/blob/aa994a82e846f0030c364b3fd5ea8f3b640c3e73/src/ClaimExtractor.php#L117-L147
chillerlan/php-qrcode
src/Output/QRMarkup.php
QRMarkup.svg
protected function svg():string{ $matrix = $this->matrix->matrix(); $svg = \sprintf($this->svgHeader, $this->options->cssClass, $this->options->svgViewBoxSize ?? $this->moduleCount) .$this->options->eol .'<defs>'.$this->options->svgDefs.'</defs>' .$this->options->eol; foreach($this->moduleValues as $M_TYPE => $value){ $path = ''; foreach($matrix as $y => $row){ //we'll combine active blocks within a single row as a lightweight compression technique $start = null; $count = 0; foreach($row as $x => $module){ if($module === $M_TYPE){ $count++; if($start === null){ $start = $x; } if($row[$x + 1] ?? false){ continue; } } if($count > 0){ $len = $count; $path .= 'M' .$start. ' ' .$y. ' h'.$len.' v1 h-'.$len.'Z '; // reset count $count = 0; $start = null; } } } if(!empty($path)){ $svg .= '<path class="qr-'.$M_TYPE.' '.$this->options->cssClass.'" stroke="transparent" fill="'.$value.'" fill-opacity="'.$this->options->svgOpacity.'" d="'.$path.'" />'; } } // close svg $svg .= '</svg>'.$this->options->eol; // if saving to file, append the correct headers if($this->options->cachefile){ return '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'.$this->options->eol.$svg; } return $svg; }
php
protected function svg():string{ $matrix = $this->matrix->matrix(); $svg = \sprintf($this->svgHeader, $this->options->cssClass, $this->options->svgViewBoxSize ?? $this->moduleCount) .$this->options->eol .'<defs>'.$this->options->svgDefs.'</defs>' .$this->options->eol; foreach($this->moduleValues as $M_TYPE => $value){ $path = ''; foreach($matrix as $y => $row){ //we'll combine active blocks within a single row as a lightweight compression technique $start = null; $count = 0; foreach($row as $x => $module){ if($module === $M_TYPE){ $count++; if($start === null){ $start = $x; } if($row[$x + 1] ?? false){ continue; } } if($count > 0){ $len = $count; $path .= 'M' .$start. ' ' .$y. ' h'.$len.' v1 h-'.$len.'Z '; // reset count $count = 0; $start = null; } } } if(!empty($path)){ $svg .= '<path class="qr-'.$M_TYPE.' '.$this->options->cssClass.'" stroke="transparent" fill="'.$value.'" fill-opacity="'.$this->options->svgOpacity.'" d="'.$path.'" />'; } } // close svg $svg .= '</svg>'.$this->options->eol; // if saving to file, append the correct headers if($this->options->cachefile){ return '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'.$this->options->eol.$svg; } return $svg; }
[ "protected", "function", "svg", "(", ")", ":", "string", "{", "$", "matrix", "=", "$", "this", "->", "matrix", "->", "matrix", "(", ")", ";", "$", "svg", "=", "\\", "sprintf", "(", "$", "this", "->", "svgHeader", ",", "$", "this", "->", "options", ...
@link https://github.com/codemasher/php-qrcode/pull/5 @return string
[ "@link", "https", ":", "//", "github", ".", "com", "/", "codemasher", "/", "php", "-", "qrcode", "/", "pull", "/", "5" ]
train
https://github.com/chillerlan/php-qrcode/blob/35d28ee6437c16219b2b93c912d3998de0c90fe6/src/Output/QRMarkup.php#L85-L143
chillerlan/php-qrcode
src/Output/QRImagick.php
QRImagick.dump
public function dump(string $file = null):string{ $file = $file ?? $this->options->cachefile; $imagick = new Imagick; $imagick->newImage( $this->length, $this->length, new ImagickPixel($this->options->imagickBG ?? 'transparent'), $this->options->imagickFormat ); $imageData = $this->drawImage($imagick); if($file !== null){ $this->saveToFile($imageData, $file); } return $imageData; }
php
public function dump(string $file = null):string{ $file = $file ?? $this->options->cachefile; $imagick = new Imagick; $imagick->newImage( $this->length, $this->length, new ImagickPixel($this->options->imagickBG ?? 'transparent'), $this->options->imagickFormat ); $imageData = $this->drawImage($imagick); if($file !== null){ $this->saveToFile($imageData, $file); } return $imageData; }
[ "public", "function", "dump", "(", "string", "$", "file", "=", "null", ")", ":", "string", "{", "$", "file", "=", "$", "file", "??", "$", "this", "->", "options", "->", "cachefile", ";", "$", "imagick", "=", "new", "Imagick", ";", "$", "imagick", "...
@param string|null $file @return string
[ "@param", "string|null", "$file" ]
train
https://github.com/chillerlan/php-qrcode/blob/35d28ee6437c16219b2b93c912d3998de0c90fe6/src/Output/QRImagick.php#L49-L67
chillerlan/php-qrcode
src/Output/QRImagick.php
QRImagick.drawImage
protected function drawImage(Imagick $imagick):string{ $draw = new ImagickDraw; foreach($this->matrix->matrix() as $y => $row){ foreach($row as $x => $M_TYPE){ $draw->setStrokeColor($this->moduleValues[$M_TYPE]); $draw->setFillColor($this->moduleValues[$M_TYPE]); $draw->rectangle( $x * $this->scale, $y * $this->scale, ($x + 1) * $this->scale, ($y + 1) * $this->scale ); } } $imagick->drawImage($draw); return (string)$imagick; }
php
protected function drawImage(Imagick $imagick):string{ $draw = new ImagickDraw; foreach($this->matrix->matrix() as $y => $row){ foreach($row as $x => $M_TYPE){ $draw->setStrokeColor($this->moduleValues[$M_TYPE]); $draw->setFillColor($this->moduleValues[$M_TYPE]); $draw->rectangle( $x * $this->scale, $y * $this->scale, ($x + 1) * $this->scale, ($y + 1) * $this->scale ); } } $imagick->drawImage($draw); return (string)$imagick; }
[ "protected", "function", "drawImage", "(", "Imagick", "$", "imagick", ")", ":", "string", "{", "$", "draw", "=", "new", "ImagickDraw", ";", "foreach", "(", "$", "this", "->", "matrix", "->", "matrix", "(", ")", "as", "$", "y", "=>", "$", "row", ")", ...
@param \Imagick $imagick @return string
[ "@param", "\\", "Imagick", "$imagick" ]
train
https://github.com/chillerlan/php-qrcode/blob/35d28ee6437c16219b2b93c912d3998de0c90fe6/src/Output/QRImagick.php#L74-L94
chillerlan/php-qrcode
src/Output/QRImage.php
QRImage.dump
public function dump(string $file = null):string{ $this->image = \imagecreatetruecolor($this->length, $this->length); $this->background = \imagecolorallocate($this->image, ...$this->options->imageTransparencyBG); if((bool)$this->options->imageTransparent && \in_array($this->options->outputType, $this::TRANSPARENCY_TYPES, true)){ \imagecolortransparent($this->image, $this->background); } \imagefilledrectangle($this->image, 0, 0, $this->length, $this->length, $this->background); foreach($this->matrix->matrix() as $y => $row){ foreach($row as $x => $M_TYPE){ $this->setPixel($x, $y, $this->moduleValues[$M_TYPE]); } } $imageData = $this->dumpImage($file); if((bool)$this->options->imageBase64){ $imageData = 'data:image/'.$this->options->outputType.';base64,'.\base64_encode($imageData); } return $imageData; }
php
public function dump(string $file = null):string{ $this->image = \imagecreatetruecolor($this->length, $this->length); $this->background = \imagecolorallocate($this->image, ...$this->options->imageTransparencyBG); if((bool)$this->options->imageTransparent && \in_array($this->options->outputType, $this::TRANSPARENCY_TYPES, true)){ \imagecolortransparent($this->image, $this->background); } \imagefilledrectangle($this->image, 0, 0, $this->length, $this->length, $this->background); foreach($this->matrix->matrix() as $y => $row){ foreach($row as $x => $M_TYPE){ $this->setPixel($x, $y, $this->moduleValues[$M_TYPE]); } } $imageData = $this->dumpImage($file); if((bool)$this->options->imageBase64){ $imageData = 'data:image/'.$this->options->outputType.';base64,'.\base64_encode($imageData); } return $imageData; }
[ "public", "function", "dump", "(", "string", "$", "file", "=", "null", ")", ":", "string", "{", "$", "this", "->", "image", "=", "\\", "imagecreatetruecolor", "(", "$", "this", "->", "length", ",", "$", "this", "->", "length", ")", ";", "$", "this", ...
@param string|null $file @return string
[ "@param", "string|null", "$file" ]
train
https://github.com/chillerlan/php-qrcode/blob/35d28ee6437c16219b2b93c912d3998de0c90fe6/src/Output/QRImage.php#L72-L95