repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
PHPColibri/framework
Mail/Mail.php
Mail.send
public static function send(string $to, string $subject, string $view, array $viewVars = [], $builder = null, $from = 'default') { $message = static::createMessage($to, $subject, $from); if (is_callable($builder)) { $builder($message); } $message->setBody(static::view($view, $viewVars)); self::getMailer()->send($message); }
php
public static function send(string $to, string $subject, string $view, array $viewVars = [], $builder = null, $from = 'default') { $message = static::createMessage($to, $subject, $from); if (is_callable($builder)) { $builder($message); } $message->setBody(static::view($view, $viewVars)); self::getMailer()->send($message); }
@param string $to @param string $subject @param string $view @param array $viewVars @param callable $builder @param string $from @throws \Swift_SwiftException
https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Mail/Mail.php#L35-L44
PHPColibri/framework
Mail/Mail.php
Mail.view
protected static function view(string $name, array $vars): string { static $path = null; $path = $path ?? ( self::$config['views'] ?? realpath(dirname(__DIR__ . '/../../../application/') . 'views/mail') ); return (new PhpTemplate("$path/$name.php")) ->setVars($vars) ->compile() ; }
php
protected static function view(string $name, array $vars): string { static $path = null; $path = $path ?? ( self::$config['views'] ?? realpath(dirname(__DIR__ . '/../../../application/') . 'views/mail') ); return (new PhpTemplate("$path/$name.php")) ->setVars($vars) ->compile() ; }
@param string $name @param array $vars @return string
https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Mail/Mail.php#L82-L93
PHPColibri/framework
Mail/Mail.php
Mail.createMessage
protected static function createMessage(string $to, string $subject, string $from = 'default'): Swift_Message { $fromName = $from === 'default' ? self::$config['from']['default'] : $from; $from = self::$config['from'][$fromName]; return (new Swift_Message()) ->setContentType('text/html') ->setSubject($subject) ->setFrom([$from['address'] => $from['name']]) ->setTo($to) ; }
php
protected static function createMessage(string $to, string $subject, string $from = 'default'): Swift_Message { $fromName = $from === 'default' ? self::$config['from']['default'] : $from; $from = self::$config['from'][$fromName]; return (new Swift_Message()) ->setContentType('text/html') ->setSubject($subject) ->setFrom([$from['address'] => $from['name']]) ->setTo($to) ; }
@param string $to @param string $subject @param string $from @return \Swift_Message @throws \Swift_DependencyException @throws \Swift_SwiftException
https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Mail/Mail.php#L105-L116
fxpio/fxp-gluon
Block/Type/TableListType.php
TableListType.addChild
public function addChild(BlockInterface $child, BlockInterface $block, array $options) { if (BlockUtil::isBlockType($child, [TableColumnListSortableType::class])) { $block->getData()->addColumn($child); } elseif (!BlockUtil::isBlockType($child, [TableHeaderType::class, TableColumnSelectType::class, TablePagerType::class, TableColumnListAdapterType::class])) { $msg = 'The "%s" child block (name: "%s") must be a "%s" or "%s" block type ("%s" type given)'; throw new InvalidConfigurationException(sprintf($msg, \get_class($block->getConfig()->getType()->getInnerType()), $child->getName(), TableColumnListAdapterType::class, TableColumnListSortableType::class, \get_class($child->getConfig()->getType()->getInnerType()))); } }
php
public function addChild(BlockInterface $child, BlockInterface $block, array $options) { if (BlockUtil::isBlockType($child, [TableColumnListSortableType::class])) { $block->getData()->addColumn($child); } elseif (!BlockUtil::isBlockType($child, [TableHeaderType::class, TableColumnSelectType::class, TablePagerType::class, TableColumnListAdapterType::class])) { $msg = 'The "%s" child block (name: "%s") must be a "%s" or "%s" block type ("%s" type given)'; throw new InvalidConfigurationException(sprintf($msg, \get_class($block->getConfig()->getType()->getInnerType()), $child->getName(), TableColumnListAdapterType::class, TableColumnListSortableType::class, \get_class($child->getConfig()->getType()->getInnerType()))); } }
{@inheritdoc}
https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Type/TableListType.php#L43-L53
fxpio/fxp-gluon
Block/Type/TableListType.php
TableListType.removeChild
public function removeChild(BlockInterface $child, BlockInterface $block, array $options) { if (!BlockUtil::isBlockType($child, TableColumnListSortableType::class)) { $block->getData()->removeColumn($child->getName()); } }
php
public function removeChild(BlockInterface $child, BlockInterface $block, array $options) { if (!BlockUtil::isBlockType($child, TableColumnListSortableType::class)) { $block->getData()->removeColumn($child->getName()); } }
{@inheritdoc}
https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Type/TableListType.php#L58-L63
fxpio/fxp-gluon
Block/Type/TableListType.php
TableListType.buildView
public function buildView(BlockView $view, BlockInterface $block, array $options) { BlockUtil::addAttributeClass($view, 'table-list'); if ($options['multi_selectable']) { BlockUtil::addAttributeClass($view, 'table-list-multiple'); } }
php
public function buildView(BlockView $view, BlockInterface $block, array $options) { BlockUtil::addAttributeClass($view, 'table-list'); if ($options['multi_selectable']) { BlockUtil::addAttributeClass($view, 'table-list-multiple'); } }
{@inheritdoc}
https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Type/TableListType.php#L68-L75
fxpio/fxp-gluon
Block/Type/TableListType.php
TableListType.finishView
public function finishView(BlockView $view, BlockInterface $block, array $options) { if (!isset($view->vars['pager'])) { return; } /* @var BlockView[] $sortColumns */ $sortColumns = []; foreach ($view->children as $name => $child) { if (\in_array('table_column_list_sort', $child->vars['block_prefixes'])) { $sortColumns[] = $child; unset($view->children[$name]); } } if (\count($sortColumns) > 0) { /* @var BlockFactoryInterface $factory */ $factory = $block->getConfig()->getAttribute('block_factory'); $sortDropdown = $factory->create(DropdownType::class, null, ['ripple' => true, 'wrapper' => false, 'attr' => ['class' => 'table-pager-list-sort-menu']]); foreach ($sortColumns as $sortColumn) { $colOptions = [ 'label' => $sortColumn->vars['label'], 'translation_domain' => $sortColumn->vars['translation_domain'], 'link_attr' => array_replace($sortColumn->vars['label_attr'], [ 'data-col-name' => $sortColumn->vars['name'], ]), ]; $sortDropdown->add($sortColumn->vars['name'], DropdownItemType::class, $colOptions); } $view->vars['pager']->vars['sort_columns'] = $sortDropdown; } }
php
public function finishView(BlockView $view, BlockInterface $block, array $options) { if (!isset($view->vars['pager'])) { return; } /* @var BlockView[] $sortColumns */ $sortColumns = []; foreach ($view->children as $name => $child) { if (\in_array('table_column_list_sort', $child->vars['block_prefixes'])) { $sortColumns[] = $child; unset($view->children[$name]); } } if (\count($sortColumns) > 0) { /* @var BlockFactoryInterface $factory */ $factory = $block->getConfig()->getAttribute('block_factory'); $sortDropdown = $factory->create(DropdownType::class, null, ['ripple' => true, 'wrapper' => false, 'attr' => ['class' => 'table-pager-list-sort-menu']]); foreach ($sortColumns as $sortColumn) { $colOptions = [ 'label' => $sortColumn->vars['label'], 'translation_domain' => $sortColumn->vars['translation_domain'], 'link_attr' => array_replace($sortColumn->vars['label_attr'], [ 'data-col-name' => $sortColumn->vars['name'], ]), ]; $sortDropdown->add($sortColumn->vars['name'], DropdownItemType::class, $colOptions); } $view->vars['pager']->vars['sort_columns'] = $sortDropdown; } }
{@inheritdoc}
https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Type/TableListType.php#L80-L114
Synapse-Cmf/synapse-cmf
src/Synapse/Cmf/Bundle/DependencyInjection/SynapseCmfExtension.php
SynapseCmfExtension.load
public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); // publish into parameters to allow listening $container->setParameter('synapse.media_store.physical_path', $config['media']['store']['physical_path']); $container->setParameter('synapse.media_store.web_path', $config['media']['store']['web_path']); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); // register components into memory if (!empty($config['components'])) { $componentData = array(); foreach ($config['components'] as $name => $data) { if (empty($data)) { continue; } $componentData[] = array( 'id' => $name, 'name' => $name, 'controller' => $data['controller'], 'template_path' => $data['template_path'], 'form_type' => $data['form'], ); } $container->getDefinition('synapse.component_type.in_memory_loader') ->addMethodCall('registerData', array($componentData)) ; $container->setParameter('synapse.component_types', array_keys($config['components'])); } // register content types into memory if (!empty($config['content_types'])) { $contentTypeData = array(); $contentTypeNames = array(); foreach ($config['content_types'] as $class => $data) { $contentTypeData[] = array( 'id' => $data['alias'], 'name' => $data['alias'], 'contentClass' => $class, 'contentProvider' => new Reference($data['provider']), ); $contentTypeNames[] = $data['alias']; } $container->getDefinition('synapse.content_type.in_memory_loader') ->addMethodCall('registerData', array($contentTypeData)) ; $container->setParameter('synapse.content_types', $contentTypeNames); } // forms enabled ? if (!empty($config['forms']['enabled'])) { $loader->load('services/forms.xml'); } }
php
public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); // publish into parameters to allow listening $container->setParameter('synapse.media_store.physical_path', $config['media']['store']['physical_path']); $container->setParameter('synapse.media_store.web_path', $config['media']['store']['web_path']); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); // register components into memory if (!empty($config['components'])) { $componentData = array(); foreach ($config['components'] as $name => $data) { if (empty($data)) { continue; } $componentData[] = array( 'id' => $name, 'name' => $name, 'controller' => $data['controller'], 'template_path' => $data['template_path'], 'form_type' => $data['form'], ); } $container->getDefinition('synapse.component_type.in_memory_loader') ->addMethodCall('registerData', array($componentData)) ; $container->setParameter('synapse.component_types', array_keys($config['components'])); } // register content types into memory if (!empty($config['content_types'])) { $contentTypeData = array(); $contentTypeNames = array(); foreach ($config['content_types'] as $class => $data) { $contentTypeData[] = array( 'id' => $data['alias'], 'name' => $data['alias'], 'contentClass' => $class, 'contentProvider' => new Reference($data['provider']), ); $contentTypeNames[] = $data['alias']; } $container->getDefinition('synapse.content_type.in_memory_loader') ->addMethodCall('registerData', array($contentTypeData)) ; $container->setParameter('synapse.content_types', $contentTypeNames); } // forms enabled ? if (!empty($config['forms']['enabled'])) { $loader->load('services/forms.xml'); } }
{@inheritdoc}
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Bundle/DependencyInjection/SynapseCmfExtension.php#L22-L78
krupni/yii-eoauth
src/EOAuthUtils.php
EOAuthUtils.GetRequestToken
public static function GetRequestToken(OAuthConsumer $consumer, $scope, $endpoint, $applicationName, $callbackUrl) { $signatureMethod = new OAuthSignatureMethod_HMAC_SHA1(); // Set parameters. $params = array(); $params['scope'] = $scope; if (isset($applicationName)) { $params['xoauth_displayname'] = $applicationName; } if (isset($callbackUrl)) { $params['oauth_callback'] = $callbackUrl; } // Create and sign request. $request = OAuthRequest::from_consumer_and_token($consumer, NULL, 'GET', $endpoint, $params); $request->sign_request($signatureMethod, $consumer, NULL); // Get token. return self::GetTokenFromUrl($request->to_url()); }
php
public static function GetRequestToken(OAuthConsumer $consumer, $scope, $endpoint, $applicationName, $callbackUrl) { $signatureMethod = new OAuthSignatureMethod_HMAC_SHA1(); // Set parameters. $params = array(); $params['scope'] = $scope; if (isset($applicationName)) { $params['xoauth_displayname'] = $applicationName; } if (isset($callbackUrl)) { $params['oauth_callback'] = $callbackUrl; } // Create and sign request. $request = OAuthRequest::from_consumer_and_token($consumer, NULL, 'GET', $endpoint, $params); $request->sign_request($signatureMethod, $consumer, NULL); // Get token. return self::GetTokenFromUrl($request->to_url()); }
Using the consumer and scope provided, a request is made to the endpoint to generate an OAuth request token. @param OAuthConsumer $consumer the consumer @param string $scope the scope of the application to authorize @param string $endpoint the OAuth endpoint to make the request against @param string $applicationName optional name of the application to display on the authorization redirect page @param string $callbackUrl optional callback URL @return OAuthToken a request token @see http://code.google.com/apis/accounts/docs/OAuth_ref.html#RequestToken
https://github.com/krupni/yii-eoauth/blob/182bcaaea73c87d90635c2201213273f40cfab26/src/EOAuthUtils.php#L35-L56
krupni/yii-eoauth
src/EOAuthUtils.php
EOAuthUtils.GetAccessToken
public static function GetAccessToken(OAuthConsumer $consumer, OAuthToken $token, $verifier, $endpoint) { $signatureMethod = new OAuthSignatureMethod_HMAC_SHA1(); // Set parameters. $params = array(); $params['oauth_verifier'] = $verifier; // Create and sign request. $request = OAuthRequest::from_consumer_and_token($consumer, $token, 'GET', $endpoint, $params); $request->sign_request($signatureMethod, $consumer, $token); // Get token. return self::GetTokenFromUrl($request->to_url()); }
php
public static function GetAccessToken(OAuthConsumer $consumer, OAuthToken $token, $verifier, $endpoint) { $signatureMethod = new OAuthSignatureMethod_HMAC_SHA1(); // Set parameters. $params = array(); $params['oauth_verifier'] = $verifier; // Create and sign request. $request = OAuthRequest::from_consumer_and_token($consumer, $token, 'GET', $endpoint, $params); $request->sign_request($signatureMethod, $consumer, $token); // Get token. return self::GetTokenFromUrl($request->to_url()); }
Using the provided consumer and authorized request token, a request is made to the endpoint to generate an OAuth access token. @param OAuthConsumer $consumer the consumer @param OAuthToken $token the authorized request token @param string $verifier the OAuth verifier code returned with the callback @param string $endpoint the OAuth endpoint to make the request against @return OAuthToken an access token @see http://code.google.com/apis/accounts/docs/OAuth_ref.html#AccessToken
https://github.com/krupni/yii-eoauth/blob/182bcaaea73c87d90635c2201213273f40cfab26/src/EOAuthUtils.php#L80-L95
krupni/yii-eoauth
src/EOAuthUtils.php
EOAuthUtils.GetTokenFromUrl
private static function GetTokenFromUrl($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $response = curl_exec($ch); $headers = curl_getinfo($ch); curl_close($ch); if ($headers['http_code'] != 200) { throw new OAuthException($response); } return self::GetTokenFromQueryString($response); }
php
private static function GetTokenFromUrl($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $response = curl_exec($ch); $headers = curl_getinfo($ch); curl_close($ch); if ($headers['http_code'] != 200) { throw new OAuthException($response); } return self::GetTokenFromQueryString($response); }
Makes an HTTP request to the given URL and extracts the returned OAuth token. @param string $url the URL to make the request to @return OAuthToken the returned token
https://github.com/krupni/yii-eoauth/blob/182bcaaea73c87d90635c2201213273f40cfab26/src/EOAuthUtils.php#L103-L118
chilimatic/chilimatic-framework
lib/database/sql/mysql/MySQLClone.php
MySQLClone.init
public function init($main_db, $clone_db, $table_list = null) { try { if (empty($main_db) && empty($clone_db)) return false; if (!$this->select_db((string)$main_db)) { throw new DatabaseException('Could not select Main Database ' . $main_db); } $this->clone_dbname = $clone_db; $this->main_dbname = $main_db; $sql = "SHOW DATABASES"; if (($this->database_list = $this->fetch_simple_list($this->query((string)$sql))) == false) { throw new DatabaseException('No Databases on the Main Server'); } $this->clone_exists = (!in_array($clone_db, $this->database_list)) ? false : true; if (empty($table_list)) { $sql = "SHOW TABLES"; $this->table_list = $this->fetch_simple_list($this->query($sql)); } elseif (!is_array($table_list)) { $this->table_list = array( $table_list ); } else { $this->table_list = $table_list; } if ($this->clone_exists === false && !$this->clone_database($main_db, $clone_db)) { throw new DatabaseException('Couldnt replicate database'); } foreach ($this->table_list as $table_name) { if ($this->clone_exists) { $sql = ($this->force_rebuild) ? "DROP TABLE `{$clone_db}`.`{$table_name}`" : "TRUNCATE `{$clone_db}`.`{$table_name}`"; $this->query($sql); } $sql = "CREATE TABLE `{$clone_db}`.`{$table_name}` LIKE `{$main_db}`.`{$table_name}`"; if (!$this->query($sql)) continue; $sql = "INSERT INTO `{$clone_db}`.`{$table_name}` SELECT * FROM `{$main_db}`.`{$table_name}`"; if (!$this->query($sql)) continue; } } catch (DatabaseException $e) { throw $e; } return true; }
php
public function init($main_db, $clone_db, $table_list = null) { try { if (empty($main_db) && empty($clone_db)) return false; if (!$this->select_db((string)$main_db)) { throw new DatabaseException('Could not select Main Database ' . $main_db); } $this->clone_dbname = $clone_db; $this->main_dbname = $main_db; $sql = "SHOW DATABASES"; if (($this->database_list = $this->fetch_simple_list($this->query((string)$sql))) == false) { throw new DatabaseException('No Databases on the Main Server'); } $this->clone_exists = (!in_array($clone_db, $this->database_list)) ? false : true; if (empty($table_list)) { $sql = "SHOW TABLES"; $this->table_list = $this->fetch_simple_list($this->query($sql)); } elseif (!is_array($table_list)) { $this->table_list = array( $table_list ); } else { $this->table_list = $table_list; } if ($this->clone_exists === false && !$this->clone_database($main_db, $clone_db)) { throw new DatabaseException('Couldnt replicate database'); } foreach ($this->table_list as $table_name) { if ($this->clone_exists) { $sql = ($this->force_rebuild) ? "DROP TABLE `{$clone_db}`.`{$table_name}`" : "TRUNCATE `{$clone_db}`.`{$table_name}`"; $this->query($sql); } $sql = "CREATE TABLE `{$clone_db}`.`{$table_name}` LIKE `{$main_db}`.`{$table_name}`"; if (!$this->query($sql)) continue; $sql = "INSERT INTO `{$clone_db}`.`{$table_name}` SELECT * FROM `{$main_db}`.`{$table_name}`"; if (!$this->query($sql)) continue; } } catch (DatabaseException $e) { throw $e; } return true; }
starts the cloning process @param $main_db string @param $clone_db string @param $table_list array|string @throws \chilimatic\exception\DatabaseException @throws \Exception @return boolean
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/mysql/MySQLClone.php#L77-L129
chilimatic/chilimatic-framework
lib/database/sql/mysql/MySQLClone.php
MySQLClone.clone_database
public function clone_database($main_db = null, $clone_db = null) { if (empty($this->db)) { throw new DatabaseException('Clone or Main database not connected'); } if (empty($main_db) || empty($clone_db)) { throw new DatabaseException('clone names havent been set'); } $sql = "SHOW CREATE DATABASE `$main_db`"; $result = $this->fetch_assoc($this->query($sql)); $create_sql = str_replace($main_db, $clone_db, $result['Create Database']); if (empty($create_sql)) { throw new DatabaseException('Create database statement is empty!'); } return $this->query($create_sql); }
php
public function clone_database($main_db = null, $clone_db = null) { if (empty($this->db)) { throw new DatabaseException('Clone or Main database not connected'); } if (empty($main_db) || empty($clone_db)) { throw new DatabaseException('clone names havent been set'); } $sql = "SHOW CREATE DATABASE `$main_db`"; $result = $this->fetch_assoc($this->query($sql)); $create_sql = str_replace($main_db, $clone_db, $result['Create Database']); if (empty($create_sql)) { throw new DatabaseException('Create database statement is empty!'); } return $this->query($create_sql); }
clones the specific database @param $main_db string @param $clone_db string @return bool @throws DatabaseException @throws \Exception
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/mysql/MySQLClone.php#L142-L163
jtallant/skimpy-engine
src/File/FrontMatter.php
FrontMatter.addTerm
public function addTerm(Term $term) { if (false === $this->terms->contains($term)) { $this->terms->add($term); } return $this; }
php
public function addTerm(Term $term) { if (false === $this->terms->contains($term)) { $this->terms->add($term); } return $this; }
@param Term $term @return $this
https://github.com/jtallant/skimpy-engine/blob/2fce5bc16f8745e54fd66a1c291fcea47fc1b4b2/src/File/FrontMatter.php#L219-L226
jtallant/skimpy-engine
src/File/FrontMatter.php
FrontMatter.has
public function has($prop) { if (false === property_exists($this, $prop)) { throw new \RuntimeException( 'Incorrect usage of FrontMatter::has($prop). '. "FrontMatter has no property $prop to confirm is not null." ); } $method = 'get'.ucfirst($prop); return false === is_null($this->$method()); }
php
public function has($prop) { if (false === property_exists($this, $prop)) { throw new \RuntimeException( 'Incorrect usage of FrontMatter::has($prop). '. "FrontMatter has no property $prop to confirm is not null." ); } $method = 'get'.ucfirst($prop); return false === is_null($this->$method()); }
Does front matter have a value for property $prop? @param string $pop @return bool @throws \RuntimeException
https://github.com/jtallant/skimpy-engine/blob/2fce5bc16f8745e54fd66a1c291fcea47fc1b4b2/src/File/FrontMatter.php#L267-L279
x2ts/x2ts
src/db/orm/ReferenceBatchLoader.php
ReferenceBatchLoader.batchLoadFor
public function batchLoadFor($models, $subWiths) { $ids = []; foreach ($models as $model) { $id = $model->properties[$this->prop]; if (is_string($id)) { $ids[] = "'$id'"; } elseif (is_int($id)) { $ids[] = $id; } elseif ($id !== null) { X::logger()->warn('Unsupported reference type ' . gettype($id) . ' of ' . get_class($model) . '->' . $this->prop . ' (PK: ' . $model->pk . ')' ); } } if (count($ids) === 0) { return; } $idStr = implode(',', $ids); /** @var Model[] $foreignModels */ $foreignModels = $this->model ->with(...$subWiths) ->many("`{$this->model->pkName}` IN ($idStr)"); $map = []; foreach ($foreignModels as $foreignModel) { $map[$foreignModel->pk] = $foreignModel; } foreach ($models as $model) { $model->{$this->name} = $map[$model->properties[$this->prop]] ?? null; } }
php
public function batchLoadFor($models, $subWiths) { $ids = []; foreach ($models as $model) { $id = $model->properties[$this->prop]; if (is_string($id)) { $ids[] = "'$id'"; } elseif (is_int($id)) { $ids[] = $id; } elseif ($id !== null) { X::logger()->warn('Unsupported reference type ' . gettype($id) . ' of ' . get_class($model) . '->' . $this->prop . ' (PK: ' . $model->pk . ')' ); } } if (count($ids) === 0) { return; } $idStr = implode(',', $ids); /** @var Model[] $foreignModels */ $foreignModels = $this->model ->with(...$subWiths) ->many("`{$this->model->pkName}` IN ($idStr)"); $map = []; foreach ($foreignModels as $foreignModel) { $map[$foreignModel->pk] = $foreignModel; } foreach ($models as $model) { $model->{$this->name} = $map[$model->properties[$this->prop]] ?? null; } }
@param Model[] $models @param array $subWiths @return void @throws UnresolvableRelationException @throws \TypeError
https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/db/orm/ReferenceBatchLoader.php#L35-L65
chilimatic/chilimatic-framework
lib/route/map/MapObject.php
MapObject.call
public function call($param = null) { // get the class within the correct namespace // initiate object $object = $this->prepareObject(new $this->class()); $return = new \SplFixedArray(2); $return[1] = $object; if (!empty($this->method)) { if (!empty($param) && !empty($this->param)) { $return[0] = $object->{$this->method}(array_merge((array)$this->param, (array)$param)); return $return; } $return[0] = $object->{$this->method}(); return $return; } return $return; }
php
public function call($param = null) { // get the class within the correct namespace // initiate object $object = $this->prepareObject(new $this->class()); $return = new \SplFixedArray(2); $return[1] = $object; if (!empty($this->method)) { if (!empty($param) && !empty($this->param)) { $return[0] = $object->{$this->method}(array_merge((array)$this->param, (array)$param)); return $return; } $return[0] = $object->{$this->method}(); return $return; } return $return; }
executes route @param null $param @return mixed
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/route/map/MapObject.php#L83-L104
chilimatic/chilimatic-framework
lib/route/map/MapObject.php
MapObject.prepareObject
public function prepareObject($object) { $tokenList = $this->getMethodTokenList(); for ($i = 0, $c = count($tokenList); $i < $c; $i++) { if ($this->reflection->hasMethod(self::SETTER_PREFIX . ucfirst($tokenList[$i]['property']))) { $m = self::SETTER_PREFIX . ucfirst($tokenList[$i]['property']); if ($tokenList[$i]['type'] == RouteMethodAnnotaionParser::TYPE_CLASS) { $value = new $tokenList[$i]['value'](); } else { $value = $tokenList[$i]['value']; } $object->$m($value); } } return $object; }
php
public function prepareObject($object) { $tokenList = $this->getMethodTokenList(); for ($i = 0, $c = count($tokenList); $i < $c; $i++) { if ($this->reflection->hasMethod(self::SETTER_PREFIX . ucfirst($tokenList[$i]['property']))) { $m = self::SETTER_PREFIX . ucfirst($tokenList[$i]['property']); if ($tokenList[$i]['type'] == RouteMethodAnnotaionParser::TYPE_CLASS) { $value = new $tokenList[$i]['value'](); } else { $value = $tokenList[$i]['value']; } $object->$m($value); } } return $object; }
@param $object @return mixed
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/route/map/MapObject.php#L111-L128
alphacomm/alpharpc
src/AlphaRPC/Client/Protocol/ExecuteResponse.php
ExecuteResponse.fromMessage
public static function fromMessage(Message $msg) { $request_id = $msg->shift(); $result = $msg->shift() ?: ''; return new self($request_id, $result); }
php
public static function fromMessage(Message $msg) { $request_id = $msg->shift(); $result = $msg->shift() ?: ''; return new self($request_id, $result); }
Creates an instance of this class based on the Message. @param Message $msg @return ExecuteResponse
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Client/Protocol/ExecuteResponse.php#L40-L46
ben-gibson/foursquare-venue-client
src/Factory/Photo/PhotoGroupFactory.php
PhotoGroupFactory.create
public function create(Description $description) { return new PhotoGroup( $description->getMandatoryProperty('name'), $description->getMandatoryProperty('type'), $this->getPhotos($description) ); }
php
public function create(Description $description) { return new PhotoGroup( $description->getMandatoryProperty('name'), $description->getMandatoryProperty('type'), $this->getPhotos($description) ); }
Create a tip group from a description. @param Description $description The photo group description. @return PhotoGroup
https://github.com/ben-gibson/foursquare-venue-client/blob/ce5e7c308f87d5ccc28ab8d27a9cb51bd106d969/src/Factory/Photo/PhotoGroupFactory.php#L33-L40
ben-gibson/foursquare-venue-client
src/Factory/Photo/PhotoGroupFactory.php
PhotoGroupFactory.getPhotos
private function getPhotos(Description $description) { return array_map( function (\stdClass $photoDescription) { return $this->photoFactory->create(new Description($photoDescription)); }, $description->getOptionalProperty('items', []) ); }
php
private function getPhotos(Description $description) { return array_map( function (\stdClass $photoDescription) { return $this->photoFactory->create(new Description($photoDescription)); }, $description->getOptionalProperty('items', []) ); }
Get the venue photos. @param Description $description The photo group description. @return Photo[]
https://github.com/ben-gibson/foursquare-venue-client/blob/ce5e7c308f87d5ccc28ab8d27a9cb51bd106d969/src/Factory/Photo/PhotoGroupFactory.php#L49-L57
chilimatic/chilimatic-framework
lib/session/engine/Factory.php
Factory.make
public static function make($engineName, $config = null) { // namespace needed for dynamic loading ;) php is sometime pretty weird $session_name = (string)__NAMESPACE__ . (string)'\\' . (string)ucfirst($engineName); if (!class_exists($session_name, true)) { throw new InvalidArgumentException('Session Engine ' . $session_name . ' does not exist'); } return new $session_name($config); }
php
public static function make($engineName, $config = null) { // namespace needed for dynamic loading ;) php is sometime pretty weird $session_name = (string)__NAMESPACE__ . (string)'\\' . (string)ucfirst($engineName); if (!class_exists($session_name, true)) { throw new InvalidArgumentException('Session Engine ' . $session_name . ' does not exist'); } return new $session_name($config); }
@param string $engineName @param array $config @return GenericEngine|null @throws InvalidArgumentException
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/session/engine/Factory.php#L24-L35
andyburton/Sonic-Framework
src/Message.php
Message.get
public static function get ($status = FALSE) { // If no status return all messages if ($status === FALSE) { return self::$messages; } // Return messages for a specific status if (isset (self::$messages[$status])) { return self::$messages[$status]; } else { return array (); } }
php
public static function get ($status = FALSE) { // If no status return all messages if ($status === FALSE) { return self::$messages; } // Return messages for a specific status if (isset (self::$messages[$status])) { return self::$messages[$status]; } else { return array (); } }
Return messages @param mixed $status Message status to return @return array
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Message.php#L39-L60
andyburton/Sonic-Framework
src/Message.php
Message.getString
public static function getString ($status = FALSE, $tagStart = NULL, $tagEnd = "\n") { // Get messages $arr = self::get ($status); // Set message string $str = ''; foreach ($arr as $msg) { $str .= $tagStart . $msg . $tagEnd; } // Return message return $str; }
php
public static function getString ($status = FALSE, $tagStart = NULL, $tagEnd = "\n") { // Get messages $arr = self::get ($status); // Set message string $str = ''; foreach ($arr as $msg) { $str .= $tagStart . $msg . $tagEnd; } // Return message return $str; }
Return messages as a string @param mixed $status Message status to return @param string $tagStart Opening tag for each message @param string $tagEnd Closing tag for each message @return string
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Message.php#L71-L91
andyburton/Sonic-Framework
src/Message.php
Message.reset
public static function reset ($status = FALSE) { // If no status reset all messages if ($status === FALSE) { self::$messages = array (); } // Reset messages for a specific status if (isset (self::$messages[$status])) { self::$messages[$status] = array (); } }
php
public static function reset ($status = FALSE) { // If no status reset all messages if ($status === FALSE) { self::$messages = array (); } // Reset messages for a specific status if (isset (self::$messages[$status])) { self::$messages[$status] = array (); } }
Reset messages @param mixed $status Message status to reset @return void
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Message.php#L100-L117
andyburton/Sonic-Framework
src/Message.php
Message.count
public static function count ($status = FALSE) { // If no status return all messages if ($status === FALSE) { return count (self::$messages); } // Return messages for a specific status if (isset (self::$messages[$status])) { return count (self::$messages[$status]); } else { return 0; } }
php
public static function count ($status = FALSE) { // If no status return all messages if ($status === FALSE) { return count (self::$messages); } // Return messages for a specific status if (isset (self::$messages[$status])) { return count (self::$messages[$status]); } else { return 0; } }
Return number of messages @param mixed $status Message status to count @return integer
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Message.php#L126-L147
smartboxgroup/camel-config-bundle
DependencyInjection/FlowsBuilderCompilerPass.php
FlowsBuilderCompilerPass.getBasicDefinition
public function getBasicDefinition($class) { if (!class_exists($class)) { throw new \InvalidArgumentException("$class is not a valid class name"); } $definition = new Definition($class, []); $traits = $this->classUsesDeep($class); foreach ($traits as $trait) { switch ($trait) { case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesEvaluator': $definition->addMethodCall('setEvaluator', [new Reference('smartesb.util.evaluator')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesSerializer': $definition->addMethodCall('setSerializer', [new Reference('jms_serializer')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesValidator': $definition->addMethodCall('setValidator', [new Reference('validator')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesEventDispatcher': $definition->addMethodCall('setEventDispatcher', [new Reference('event_dispatcher')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesEndpointFactory': $definition->addMethodCall('setEndpointFactory', [new Reference('smartesb.endpoint_factory')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesEndpointRouter': $definition->addMethodCall('setEndpointsRouter', [new Reference('smartesb.router.endpoints')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\MessageFactoryAware': $definition->addMethodCall('setMessageFactory', [new Reference('smartesb.message_factory')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesCacheService': $definition->addMethodCall('setCacheService', [new Reference('smartcore.cache_service')]); break; case 'Symfony\Component\DependencyInjection\ContainerAwareTrait': $definition->addMethodCall('setContainer', [new Reference('service_container')]); break; } } return $definition; }
php
public function getBasicDefinition($class) { if (!class_exists($class)) { throw new \InvalidArgumentException("$class is not a valid class name"); } $definition = new Definition($class, []); $traits = $this->classUsesDeep($class); foreach ($traits as $trait) { switch ($trait) { case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesEvaluator': $definition->addMethodCall('setEvaluator', [new Reference('smartesb.util.evaluator')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesSerializer': $definition->addMethodCall('setSerializer', [new Reference('jms_serializer')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesValidator': $definition->addMethodCall('setValidator', [new Reference('validator')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesEventDispatcher': $definition->addMethodCall('setEventDispatcher', [new Reference('event_dispatcher')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesEndpointFactory': $definition->addMethodCall('setEndpointFactory', [new Reference('smartesb.endpoint_factory')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesEndpointRouter': $definition->addMethodCall('setEndpointsRouter', [new Reference('smartesb.router.endpoints')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\MessageFactoryAware': $definition->addMethodCall('setMessageFactory', [new Reference('smartesb.message_factory')]); break; case 'Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits\UsesCacheService': $definition->addMethodCall('setCacheService', [new Reference('smartcore.cache_service')]); break; case 'Symfony\Component\DependencyInjection\ContainerAwareTrait': $definition->addMethodCall('setContainer', [new Reference('service_container')]); break; } } return $definition; }
Creates a basic service definition for the given class, injecting the typical dependencies according with the traits the class uses. @return Definition
https://github.com/smartboxgroup/camel-config-bundle/blob/f38505c50a446707b8e8f79ecaa1addd0a6cca11/DependencyInjection/FlowsBuilderCompilerPass.php#L123-L173
smartboxgroup/camel-config-bundle
DependencyInjection/FlowsBuilderCompilerPass.php
FlowsBuilderCompilerPass.getDefinitionService
protected function getDefinitionService($nodeName) { /** @var ProcessorDefinitionInterface $definition */ $definition = $this->container->get('smartesb.registry.processor_definitions')->findDefinition($nodeName); $definition->setBuilder($this); return $definition; }
php
protected function getDefinitionService($nodeName) { /** @var ProcessorDefinitionInterface $definition */ $definition = $this->container->get('smartesb.registry.processor_definitions')->findDefinition($nodeName); $definition->setBuilder($this); return $definition; }
@param $nodeName @return ProcessorDefinitionInterface @throws \Exception
https://github.com/smartboxgroup/camel-config-bundle/blob/f38505c50a446707b8e8f79ecaa1addd0a6cca11/DependencyInjection/FlowsBuilderCompilerPass.php#L182-L190
smartboxgroup/camel-config-bundle
DependencyInjection/FlowsBuilderCompilerPass.php
FlowsBuilderCompilerPass.generateNextUniqueReproducibleIdForContext
public function generateNextUniqueReproducibleIdForContext($contextId) { if (!array_key_exists($contextId, $this->registeredNamesPerContext)) { $this->registeredNamesPerContext[$contextId] = []; } $index = count($this->registeredNamesPerContext[$contextId]); $id = 'v'.$this->currentLoadingVersion.'.'.sha1($contextId.'_'.$index); $this->registeredNamesPerContext[$contextId][] = $id; return $id; }
php
public function generateNextUniqueReproducibleIdForContext($contextId) { if (!array_key_exists($contextId, $this->registeredNamesPerContext)) { $this->registeredNamesPerContext[$contextId] = []; } $index = count($this->registeredNamesPerContext[$contextId]); $id = 'v'.$this->currentLoadingVersion.'.'.sha1($contextId.'_'.$index); $this->registeredNamesPerContext[$contextId][] = $id; return $id; }
@param $contextId @return string
https://github.com/smartboxgroup/camel-config-bundle/blob/f38505c50a446707b8e8f79ecaa1addd0a6cca11/DependencyInjection/FlowsBuilderCompilerPass.php#L197-L209
smartboxgroup/camel-config-bundle
DependencyInjection/FlowsBuilderCompilerPass.php
FlowsBuilderCompilerPass.registerItinerary
public function registerItinerary(Definition $definition, $name) { $id = self::ITINERARY_ID_PREFIX.'v'.$this->currentLoadingVersion.'.'.$name; // Avoid name duplicities if (in_array($id, $this->registeredNames)) { throw new InvalidConfigurationException('Itinerary name used twice: '.$id); } $this->registeredNames[] = $id; $this->container->setDefinition($id, $definition); $definition->setProperty('id', $id); $definition->setArguments([$name]); return new Reference($id); }
php
public function registerItinerary(Definition $definition, $name) { $id = self::ITINERARY_ID_PREFIX.'v'.$this->currentLoadingVersion.'.'.$name; // Avoid name duplicities if (in_array($id, $this->registeredNames)) { throw new InvalidConfigurationException('Itinerary name used twice: '.$id); } $this->registeredNames[] = $id; $this->container->setDefinition($id, $definition); $definition->setProperty('id', $id); $definition->setArguments([$name]); return new Reference($id); }
@param Definition $definition @param string $name @return Reference
https://github.com/smartboxgroup/camel-config-bundle/blob/f38505c50a446707b8e8f79ecaa1addd0a6cca11/DependencyInjection/FlowsBuilderCompilerPass.php#L217-L232
smartboxgroup/camel-config-bundle
DependencyInjection/FlowsBuilderCompilerPass.php
FlowsBuilderCompilerPass.registerProcessor
public function registerProcessor(Definition $definition, $id) { if ($this->container->has($id)) { throw new InvalidConfigurationException('Processor id used twice: '.$id); } $this->container->setDefinition($id, $definition); $definition->setProperty('id', $id); return new Reference($id); }
php
public function registerProcessor(Definition $definition, $id) { if ($this->container->has($id)) { throw new InvalidConfigurationException('Processor id used twice: '.$id); } $this->container->setDefinition($id, $definition); $definition->setProperty('id', $id); return new Reference($id); }
@param Definition $definition @return Reference
https://github.com/smartboxgroup/camel-config-bundle/blob/f38505c50a446707b8e8f79ecaa1addd0a6cca11/DependencyInjection/FlowsBuilderCompilerPass.php#L251-L261
smartboxgroup/camel-config-bundle
DependencyInjection/FlowsBuilderCompilerPass.php
FlowsBuilderCompilerPass.process
public function process(ContainerBuilder $container) { $this->container = $container; $this->processorDefinitionsRegistry = $this->container->getDefinition('smartesb.registry.processor_definitions'); $processorDefinitionsServices = $container->findTaggedServiceIds(self::TAG_DEFINITIONS); foreach ($processorDefinitionsServices as $id => $tags) { foreach ($tags as $attributes) { $this->processorDefinitionsRegistry->addMethodCall('register', [$attributes['nodeName'], new Reference($id)]); } } /** @var SmartboxIntegrationCamelConfigExtension $extension */ $extension = $container->getExtension('smartbox_integration_camel_config'); /** @var SmartboxIntegrationFrameworkExtension $frameworkExtension */ $frameworkExtension = $container->getExtension('smartbox_integration_framework'); $flowsDirs = $extension->getFlowsDirectories(); $currentVersion = $frameworkExtension->getFlowsVersion(); $frozenFlowsDir = $extension->getFrozenFlowsDirectory(); // Load current version if not frozen if (!file_exists($frozenFlowsDir.'/'.$currentVersion)) { $this->loadFlowsFromPaths($currentVersion, $flowsDirs); } // Load frozen versions $finder = new Finder(); $frozenDirs = $finder->directories()->in($frozenFlowsDir)->depth(0); /** @var SplFileInfo $frozenDir */ foreach ($frozenDirs as $frozenDir) { $subFinder = new Finder(); $version = $frozenDir->getRelativePathname(); $subDirs = $subFinder->directories()->in($frozenDir->getRealPath())->depth(0); $paths = []; /** @var SplFileInfo $subDir */ foreach ($subDirs as $subDir) { $paths[] = $subDir->getRealPath(); } $this->loadFlowsFromPaths($version, $paths); } }
php
public function process(ContainerBuilder $container) { $this->container = $container; $this->processorDefinitionsRegistry = $this->container->getDefinition('smartesb.registry.processor_definitions'); $processorDefinitionsServices = $container->findTaggedServiceIds(self::TAG_DEFINITIONS); foreach ($processorDefinitionsServices as $id => $tags) { foreach ($tags as $attributes) { $this->processorDefinitionsRegistry->addMethodCall('register', [$attributes['nodeName'], new Reference($id)]); } } /** @var SmartboxIntegrationCamelConfigExtension $extension */ $extension = $container->getExtension('smartbox_integration_camel_config'); /** @var SmartboxIntegrationFrameworkExtension $frameworkExtension */ $frameworkExtension = $container->getExtension('smartbox_integration_framework'); $flowsDirs = $extension->getFlowsDirectories(); $currentVersion = $frameworkExtension->getFlowsVersion(); $frozenFlowsDir = $extension->getFrozenFlowsDirectory(); // Load current version if not frozen if (!file_exists($frozenFlowsDir.'/'.$currentVersion)) { $this->loadFlowsFromPaths($currentVersion, $flowsDirs); } // Load frozen versions $finder = new Finder(); $frozenDirs = $finder->directories()->in($frozenFlowsDir)->depth(0); /** @var SplFileInfo $frozenDir */ foreach ($frozenDirs as $frozenDir) { $subFinder = new Finder(); $version = $frozenDir->getRelativePathname(); $subDirs = $subFinder->directories()->in($frozenDir->getRealPath())->depth(0); $paths = []; /** @var SplFileInfo $subDir */ foreach ($subDirs as $subDir) { $paths[] = $subDir->getRealPath(); } $this->loadFlowsFromPaths($version, $paths); } }
@param ContainerBuilder $container @api
https://github.com/smartboxgroup/camel-config-bundle/blob/f38505c50a446707b8e8f79ecaa1addd0a6cca11/DependencyInjection/FlowsBuilderCompilerPass.php#L268-L313
smartboxgroup/camel-config-bundle
DependencyInjection/FlowsBuilderCompilerPass.php
FlowsBuilderCompilerPass.loadFlowsFromPaths
protected function loadFlowsFromPaths($version, $paths) { $this->currentLoadingVersion = $version; $finder = new Finder(); $finder->files()->name('*.xml')->in($paths)->sortByName(); /** @var SplFileInfo $file */ foreach ($finder as $file) { $this->currentLoadingFile = $file; $this->currentFileSlug = self::slugify(str_replace('.xml', '', $this->currentLoadingFile->getRelativePathname())); $this->registeredNamesInFileCount = 1; $this->loadXMLFlows($file->getRealpath()); } }
php
protected function loadFlowsFromPaths($version, $paths) { $this->currentLoadingVersion = $version; $finder = new Finder(); $finder->files()->name('*.xml')->in($paths)->sortByName(); /** @var SplFileInfo $file */ foreach ($finder as $file) { $this->currentLoadingFile = $file; $this->currentFileSlug = self::slugify(str_replace('.xml', '', $this->currentLoadingFile->getRelativePathname())); $this->registeredNamesInFileCount = 1; $this->loadXMLFlows($file->getRealpath()); } }
Loads the flows in the given $paths for the given $version. @param string $version @param array $paths
https://github.com/smartboxgroup/camel-config-bundle/blob/f38505c50a446707b8e8f79ecaa1addd0a6cca11/DependencyInjection/FlowsBuilderCompilerPass.php#L321-L334
smartboxgroup/camel-config-bundle
DependencyInjection/FlowsBuilderCompilerPass.php
FlowsBuilderCompilerPass.buildFlow
public function buildFlow($config, $flowName = null) { // Default naming if ($flowName == null) { $path = $this->currentLoadingFile->getRelativePathname(); $flowName = self::slugify(str_replace('.xml', '', $path)); if ($this->registeredNamesInFileCount > 1) { $flowName .= '_'.$this->registeredNamesInFileCount; } ++$this->registeredNamesInFileCount; } // Avoid name duplicities if (in_array($flowName, $this->registeredNames)) { throw new InvalidConfigurationException('Flow name used twice: '.$flowName); } $flowName = 'v'.$this->currentLoadingVersion.'_'.$flowName; $this->registeredNames[] = $flowName; // Build stuff.. $itineraryRef = $this->buildItinerary($flowName); $from = null; $itineraryNodes = 0; foreach ($config as $key => $value) { if ($key == self::FROM) { $from = (string) @$value['uri']; } else { $this->addNodeToItinerary($itineraryRef, $key, $value); ++$itineraryNodes; } } if (empty($from)) { throw new InvalidConfigurationException( sprintf( 'The flow "%s" defined in "%s" must contain at least an endpoint to consume from it', $flowName, realpath($this->currentLoadingFile->getPathname()) ) ); } if ($itineraryNodes == 0) { throw new InvalidConfigurationException( sprintf( 'The flow "%s" defined in "%s" must contain at least one node in its itinerary', $flowName, realpath($this->currentLoadingFile->getPathname()) ) ); } $from = ItineraryResolver::getItineraryURIWithVersion($from, $this->currentLoadingVersion); $itinerariesRepo = $this->container->getDefinition('smartesb.map.itineraries'); $itinerariesRepo->addMethodCall('addItinerary', [$from, (string) $itineraryRef]); }
php
public function buildFlow($config, $flowName = null) { // Default naming if ($flowName == null) { $path = $this->currentLoadingFile->getRelativePathname(); $flowName = self::slugify(str_replace('.xml', '', $path)); if ($this->registeredNamesInFileCount > 1) { $flowName .= '_'.$this->registeredNamesInFileCount; } ++$this->registeredNamesInFileCount; } // Avoid name duplicities if (in_array($flowName, $this->registeredNames)) { throw new InvalidConfigurationException('Flow name used twice: '.$flowName); } $flowName = 'v'.$this->currentLoadingVersion.'_'.$flowName; $this->registeredNames[] = $flowName; // Build stuff.. $itineraryRef = $this->buildItinerary($flowName); $from = null; $itineraryNodes = 0; foreach ($config as $key => $value) { if ($key == self::FROM) { $from = (string) @$value['uri']; } else { $this->addNodeToItinerary($itineraryRef, $key, $value); ++$itineraryNodes; } } if (empty($from)) { throw new InvalidConfigurationException( sprintf( 'The flow "%s" defined in "%s" must contain at least an endpoint to consume from it', $flowName, realpath($this->currentLoadingFile->getPathname()) ) ); } if ($itineraryNodes == 0) { throw new InvalidConfigurationException( sprintf( 'The flow "%s" defined in "%s" must contain at least one node in its itinerary', $flowName, realpath($this->currentLoadingFile->getPathname()) ) ); } $from = ItineraryResolver::getItineraryURIWithVersion($from, $this->currentLoadingVersion); $itinerariesRepo = $this->container->getDefinition('smartesb.map.itineraries'); $itinerariesRepo->addMethodCall('addItinerary', [$from, (string) $itineraryRef]); }
{@inheritdoc}
https://github.com/smartboxgroup/camel-config-bundle/blob/f38505c50a446707b8e8f79ecaa1addd0a6cca11/DependencyInjection/FlowsBuilderCompilerPass.php#L360-L418
smartboxgroup/camel-config-bundle
DependencyInjection/FlowsBuilderCompilerPass.php
FlowsBuilderCompilerPass.buildProcessor
public function buildProcessor($name, $config) { $definitionService = $this->getDefinitionService($name); $definitionService->setDebug($this->container->getParameter('kernel.debug')); $id = $this->determineProcessorId($config); $def = $definitionService->buildProcessor($config, $id); $ref = $this->registerProcessor($def, $id); return $ref; }
php
public function buildProcessor($name, $config) { $definitionService = $this->getDefinitionService($name); $definitionService->setDebug($this->container->getParameter('kernel.debug')); $id = $this->determineProcessorId($config); $def = $definitionService->buildProcessor($config, $id); $ref = $this->registerProcessor($def, $id); return $ref; }
@param $name @param $config @return Reference @throws \Exception
https://github.com/smartboxgroup/camel-config-bundle/blob/f38505c50a446707b8e8f79ecaa1addd0a6cca11/DependencyInjection/FlowsBuilderCompilerPass.php#L428-L438
smartboxgroup/camel-config-bundle
DependencyInjection/FlowsBuilderCompilerPass.php
FlowsBuilderCompilerPass.buildEndpoint
public function buildEndpoint($config) { $uri = @$config['uri'].''; $id = $this->determineProcessorId($config); $runtimeBreakpoint = isset($config[ProcessorDefinition::ATTRIBUTE_RUNTIME_BREAKPOINT]) && $config[ProcessorDefinition::ATTRIBUTE_RUNTIME_BREAKPOINT] == true && $this->container->getParameter('kernel.debug') ; $compiletimeBreakpoint = isset($config[ProcessorDefinition::ATTRIBUTE_COMPILETIME_BREAKPOINT]) && $config[ProcessorDefinition::ATTRIBUTE_COMPILETIME_BREAKPOINT] == true && $this->container->getParameter('kernel.debug') ; // Use existing endpoint ... // ==================================== // Find by id ... !! Id should be specific for scheme, host, path if ($compiletimeBreakpoint && function_exists('xdebug_break')) { xdebug_break(); } /* * * DEBUGGING HINTS * * In case you are adding a compile time breakpoint in a flow xml xdebug will stop here. * * The definition of the endpoint you are debugging is extending this method. * * By continuing executing from here you will have chance to debug the way the endpoint service is built * in the container. * * If you are reading this by chance and wondering how you can add a compile time breakpoint to endpoint you * need to add this to your xml flow file, as part of the processor you want to debug: * * <... compiletime-breakpoint="1"/> * * Then you need to execute the compilation in debug mode with xdebug enabled */ $endpointDef = $this->getBasicDefinition(EndpointProcessor::class); $endpointDef->addMethodCall('setURI', [$uri]); if (isset($config->description)) { $endpointDef->addMethodCall('setDescription', [(string) $config->description]); } if ($runtimeBreakpoint) { $endpointDef->addMethodCall('setRuntimeBreakpoint', [true]); } return $this->registerProcessor($endpointDef, $id); }
php
public function buildEndpoint($config) { $uri = @$config['uri'].''; $id = $this->determineProcessorId($config); $runtimeBreakpoint = isset($config[ProcessorDefinition::ATTRIBUTE_RUNTIME_BREAKPOINT]) && $config[ProcessorDefinition::ATTRIBUTE_RUNTIME_BREAKPOINT] == true && $this->container->getParameter('kernel.debug') ; $compiletimeBreakpoint = isset($config[ProcessorDefinition::ATTRIBUTE_COMPILETIME_BREAKPOINT]) && $config[ProcessorDefinition::ATTRIBUTE_COMPILETIME_BREAKPOINT] == true && $this->container->getParameter('kernel.debug') ; // Use existing endpoint ... // ==================================== // Find by id ... !! Id should be specific for scheme, host, path if ($compiletimeBreakpoint && function_exists('xdebug_break')) { xdebug_break(); } /* * * DEBUGGING HINTS * * In case you are adding a compile time breakpoint in a flow xml xdebug will stop here. * * The definition of the endpoint you are debugging is extending this method. * * By continuing executing from here you will have chance to debug the way the endpoint service is built * in the container. * * If you are reading this by chance and wondering how you can add a compile time breakpoint to endpoint you * need to add this to your xml flow file, as part of the processor you want to debug: * * <... compiletime-breakpoint="1"/> * * Then you need to execute the compilation in debug mode with xdebug enabled */ $endpointDef = $this->getBasicDefinition(EndpointProcessor::class); $endpointDef->addMethodCall('setURI', [$uri]); if (isset($config->description)) { $endpointDef->addMethodCall('setDescription', [(string) $config->description]); } if ($runtimeBreakpoint) { $endpointDef->addMethodCall('setRuntimeBreakpoint', [true]); } return $this->registerProcessor($endpointDef, $id); }
@param $config @return Reference @throws \Exception
https://github.com/smartboxgroup/camel-config-bundle/blob/f38505c50a446707b8e8f79ecaa1addd0a6cca11/DependencyInjection/FlowsBuilderCompilerPass.php#L452-L504
smartboxgroup/camel-config-bundle
DependencyInjection/FlowsBuilderCompilerPass.php
FlowsBuilderCompilerPass.buildItinerary
public function buildItinerary($name) { $itineraryClass = $this->container->getParameter('smartesb.itinerary.class'); $def = $this->getBasicDefinition($itineraryClass); return $this->registerItinerary($def, $name); }
php
public function buildItinerary($name) { $itineraryClass = $this->container->getParameter('smartesb.itinerary.class'); $def = $this->getBasicDefinition($itineraryClass); return $this->registerItinerary($def, $name); }
{@inheritdoc}
https://github.com/smartboxgroup/camel-config-bundle/blob/f38505c50a446707b8e8f79ecaa1addd0a6cca11/DependencyInjection/FlowsBuilderCompilerPass.php#L509-L515
smartboxgroup/camel-config-bundle
DependencyInjection/FlowsBuilderCompilerPass.php
FlowsBuilderCompilerPass.addProcessorDefinitionToItinerary
public function addProcessorDefinitionToItinerary(Reference $itinerary, Definition $processor, $id = null) { $id = $this->determineProcessorId(['id' => $id]); $ref = $this->registerProcessor($processor, $id); $this->addToItinerary($itinerary, $ref); }
php
public function addProcessorDefinitionToItinerary(Reference $itinerary, Definition $processor, $id = null) { $id = $this->determineProcessorId(['id' => $id]); $ref = $this->registerProcessor($processor, $id); $this->addToItinerary($itinerary, $ref); }
{@inheritdoc}
https://github.com/smartboxgroup/camel-config-bundle/blob/f38505c50a446707b8e8f79ecaa1addd0a6cca11/DependencyInjection/FlowsBuilderCompilerPass.php#L530-L535
smartboxgroup/camel-config-bundle
DependencyInjection/FlowsBuilderCompilerPass.php
FlowsBuilderCompilerPass.addNodeToItinerary
public function addNodeToItinerary(Reference $itinerary, $nodeName, $nodeConfig) { switch ($nodeName) { case self::TO: $ref = $this->buildEndpoint($nodeConfig); $this->addToItinerary($itinerary, $ref); break; default: $ref = $this->buildProcessor($nodeName, $nodeConfig); $this->addToItinerary($itinerary, $ref); break; } }
php
public function addNodeToItinerary(Reference $itinerary, $nodeName, $nodeConfig) { switch ($nodeName) { case self::TO: $ref = $this->buildEndpoint($nodeConfig); $this->addToItinerary($itinerary, $ref); break; default: $ref = $this->buildProcessor($nodeName, $nodeConfig); $this->addToItinerary($itinerary, $ref); break; } }
@param Definition|Reference $itinerary @param string $nodeName @param $nodeConfig @throws \Exception @internal param $configNode
https://github.com/smartboxgroup/camel-config-bundle/blob/f38505c50a446707b8e8f79ecaa1addd0a6cca11/DependencyInjection/FlowsBuilderCompilerPass.php#L546-L558
ddvphp/wechat
org/old_version/wechatpay.class.php
Wechatpay.checkAuth
public function checkAuth($appid='',$appsecret='',$token=''){ if (!$appid || !$appsecret) { $appid = $this->appid; $appsecret = $this->appsecret; } if ($token) { //手动指定token,优先使用 $this->access_token=$token; return $this->access_token; } //TODO: get the cache access_token $result = $this->http_get(self::API_URL_PREFIX.self::AUTH_URL.'appid='.$appid.'&secret='.$appsecret); if ($result) { $json = json_decode($result,true); if (!$json || isset($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return false; } $this->access_token = $json['access_token']; $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600; //TODO: cache access_token return $this->access_token; } return false; }
php
public function checkAuth($appid='',$appsecret='',$token=''){ if (!$appid || !$appsecret) { $appid = $this->appid; $appsecret = $this->appsecret; } if ($token) { //手动指定token,优先使用 $this->access_token=$token; return $this->access_token; } //TODO: get the cache access_token $result = $this->http_get(self::API_URL_PREFIX.self::AUTH_URL.'appid='.$appid.'&secret='.$appsecret); if ($result) { $json = json_decode($result,true); if (!$json || isset($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return false; } $this->access_token = $json['access_token']; $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600; //TODO: cache access_token return $this->access_token; } return false; }
获取access_token @param string $appid 如在类初始化时已提供,则可为空 @param string $appsecret 如在类初始化时已提供,则可为空 @param string $token 手动指定access_token,非必要情况不建议用
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/org/old_version/wechatpay.class.php#L125-L150
phPoirot/Stream
Filter/aFilterStreamCustom.php
aFilterStreamCustom.getLabel
function getLabel() { if ($this->filtername) return $this->filtername; $className = explode('\\', get_class($this)); $className = $className[count($className)-1]; return $className.'.*'; }
php
function getLabel() { if ($this->filtername) return $this->filtername; $className = explode('\\', get_class($this)); $className = $className[count($className)-1]; return $className.'.*'; }
Label Used To Register Our Filter @return string
https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/Filter/aFilterStreamCustom.php#L72-L81
phPoirot/Stream
Filter/aFilterStreamCustom.php
aFilterStreamCustom.appendTo
function appendTo(iResourceStream $streamResource, $rwFlag = STREAM_FILTER_ALL) { if (!RegistryOfFilterStream::has($this)) // register filter if not exists in registry RegistryOfFilterStream::register($this); $filterRes = stream_filter_append( $streamResource->getRHandler() , $this->getLabel() , $rwFlag , \Poirot\Std\cast($this->optsData())->toArray() ); return $filterRes; }
php
function appendTo(iResourceStream $streamResource, $rwFlag = STREAM_FILTER_ALL) { if (!RegistryOfFilterStream::has($this)) // register filter if not exists in registry RegistryOfFilterStream::register($this); $filterRes = stream_filter_append( $streamResource->getRHandler() , $this->getLabel() , $rwFlag , \Poirot\Std\cast($this->optsData())->toArray() ); return $filterRes; }
Append Filter To Resource Stream ! By default, stream_filter_append() will attach the filter to the read filter chain if the file was opened for reading (i.e. File Mode: r, and/or +). The filter will also be attached to the write filter chain if the file was opened for writing (i.e. File Mode: w, a, and/or +). STREAM_FILTER_READ, STREAM_FILTER_WRITE, and/or STREAM_FILTER_ALL can also be passed to the read_write parameter to override this behavior. Note: Stream data is read from resources (both local and remote) in chunks, with any unconsumed data kept in internal buffers. When a new filter is appended to a stream, data in the internal buffers is processed through the new filter at that time. This differs from the behavior of stream_filter_prepend() Note: When a filter is added for read and write, two instances of the filter are created. stream_filter_append() must be called twice with STREAM_FILTER_READ and STREAM_FILTER_WRITE to get both filter resources. @param iResourceStream $streamResource @param int $rwFlag @return resource
https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/Filter/aFilterStreamCustom.php#L109-L123
phPoirot/Stream
Filter/aFilterStreamCustom.php
aFilterStreamCustom._getDataFromBucket
protected function _getDataFromBucket($in, &$consumed) { $data = ''; while ($bucket = stream_bucket_make_writeable($in)) { $data .= $bucket->data; $consumed += $bucket->datalen; } return $data; }
php
protected function _getDataFromBucket($in, &$consumed) { $data = ''; while ($bucket = stream_bucket_make_writeable($in)) { $data .= $bucket->data; $consumed += $bucket->datalen; } return $data; }
Read Data From Bucket @param resource $in userfilter.bucket brigade @param int $consumed @return string
https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/Filter/aFilterStreamCustom.php#L156-L165
phPoirot/Stream
Filter/aFilterStreamCustom.php
aFilterStreamCustom._writeBackDataOut
protected function _writeBackDataOut($out, $data) { $buck = stream_bucket_new($this->bufferHandle, ''); if (false === $buck) // trigger filter error return PSFS_ERR_FATAL; $buck->data = $data; stream_bucket_append($out, $buck); // data was processed successfully return PSFS_PASS_ON; }
php
protected function _writeBackDataOut($out, $data) { $buck = stream_bucket_new($this->bufferHandle, ''); if (false === $buck) // trigger filter error return PSFS_ERR_FATAL; $buck->data = $data; stream_bucket_append($out, $buck); // data was processed successfully return PSFS_PASS_ON; }
Write Back Filtered Data On Out Bucket @param resource $out userfilter.bucket brigade @param string $data @return int PSFS_ERR_FATAL|PSFS_PASS_ON
https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/Filter/aFilterStreamCustom.php#L175-L187
liufee/cms-core
backend/actions/ViewAction.php
ViewAction.run
public function run($id) { /* @var $model \yii\db\ActiveRecord */ $model = call_user_func([$this->modelClass, 'findOne'], $id); return $this->controller->render('view', [ 'model' => $model, ]); }
php
public function run($id) { /* @var $model \yii\db\ActiveRecord */ $model = call_user_func([$this->modelClass, 'findOne'], $id); return $this->controller->render('view', [ 'model' => $model, ]); }
view详情页 @param $id @return string
https://github.com/liufee/cms-core/blob/440ee229e3b722d6088c57926d612b5f891b370d/backend/actions/ViewAction.php#L24-L31
ShaoZeMing/lumen-pgApi
app/Http/Controllers/LbsApi/WorkerApiController.php
WorkerApiController.insert
public function insert() { try { $this->validate( $this->request, $this->validator->getRules(Validator::RULE_CREATE), $this->validator->getMassage()); } catch (ValidationException $e) { Log::info('c=WorkerApiController f=insert msg=' . $this->response_msg($e->getResponse())); return $this->response_msg($e->getResponse()); } $data = $this->request->all(); Log::info('c=WorkerApiController f=insert msg=' . json_encode($data)); $result = $this->apiRepository->insertData($data); if ($result !== false) { return $this->response_json(0, "添加成功", $result); } else { return $this->response_json(1, "添加失败", [], 422); } }
php
public function insert() { try { $this->validate( $this->request, $this->validator->getRules(Validator::RULE_CREATE), $this->validator->getMassage()); } catch (ValidationException $e) { Log::info('c=WorkerApiController f=insert msg=' . $this->response_msg($e->getResponse())); return $this->response_msg($e->getResponse()); } $data = $this->request->all(); Log::info('c=WorkerApiController f=insert msg=' . json_encode($data)); $result = $this->apiRepository->insertData($data); if ($result !== false) { return $this->response_json(0, "添加成功", $result); } else { return $this->response_json(1, "添加失败", [], 422); } }
@api {post} /lbs/insert-worker 添加师傅 @apiDescription 添加师傅位置信息 @apiGroup Worker-LBS @apiPermission LBS_TOKEN @apiParam {String} lbs_token 认证秘钥 @apiParam {Int} uid 关联ID @apiParam {String} full_address 地址 @apiParam {String} name 姓名 @apiParam {String} mobile 电话 @apiParam {float} worker_lat 纬度 @apiParam {float} worker_lng 经度 @apiVersion 0.1.0 @apiSuccessExample {json} 成功-Response: { "error": 0, "msg": "添加成功", "data": [] } @apiErrorExample {json} 错误-Response: { "error": 1, "msg": "验证错误:该uid关联师傅已存在(uid),", "data": [] }
https://github.com/ShaoZeMing/lumen-pgApi/blob/f5ef140ef8d2f6ec9f1d1a6dc61292913e4e7271/app/Http/Controllers/LbsApi/WorkerApiController.php#L147-L169
brick/validation
src/Internal/Decimal.php
Decimal.parse
public static function parse(string $number) : Decimal { if (preg_match('/^(\-?)([0-9]+)(?:\.([0-9]+))?$/', $number, $matches) !== 1) { throw new \InvalidArgumentException('Invalid number: ' . $number); } $sign = $matches[1]; $integral = $matches[2]; if (isset($matches[3])) { $fractional = rtrim($matches[3], '0'); } else { $fractional = ''; } $scale = strlen($fractional); $value = $integral . $fractional; $value = ltrim($value, '0'); if ($value === '') { $value = '0'; } $value = $sign . $value; $intValue = (int) $value; if ($value !== (string) $intValue) { throw new \InvalidArgumentException('Decimal number out of range for this platform: ' . $value); } return new Decimal($intValue, $scale); }
php
public static function parse(string $number) : Decimal { if (preg_match('/^(\-?)([0-9]+)(?:\.([0-9]+))?$/', $number, $matches) !== 1) { throw new \InvalidArgumentException('Invalid number: ' . $number); } $sign = $matches[1]; $integral = $matches[2]; if (isset($matches[3])) { $fractional = rtrim($matches[3], '0'); } else { $fractional = ''; } $scale = strlen($fractional); $value = $integral . $fractional; $value = ltrim($value, '0'); if ($value === '') { $value = '0'; } $value = $sign . $value; $intValue = (int) $value; if ($value !== (string) $intValue) { throw new \InvalidArgumentException('Decimal number out of range for this platform: ' . $value); } return new Decimal($intValue, $scale); }
@param string $number @return Decimal @throws \InvalidArgumentException If the number is invalid, or exceeds the size of an int on this platform.
https://github.com/brick/validation/blob/b33593f75df80530417007bde97c4772807563ab/src/Internal/Decimal.php#L41-L74
brick/validation
src/Internal/Decimal.php
Decimal.isLessThan
public function isLessThan(Decimal $that) : bool { $this->scaleValues($this, $that, $a, $b); return $a < $b; }
php
public function isLessThan(Decimal $that) : bool { $this->scaleValues($this, $that, $a, $b); return $a < $b; }
@param Decimal $that @return bool @throws \RangeException If the result exceeds the size of an int on this platform.
https://github.com/brick/validation/blob/b33593f75df80530417007bde97c4772807563ab/src/Internal/Decimal.php#L83-L88
brick/validation
src/Internal/Decimal.php
Decimal.isGreaterThan
public function isGreaterThan(Decimal $that) : bool { $this->scaleValues($this, $that, $a, $b); return $a > $b; }
php
public function isGreaterThan(Decimal $that) : bool { $this->scaleValues($this, $that, $a, $b); return $a > $b; }
@param Decimal $that @return bool @throws \RangeException If the result exceeds the size of an int on this platform.
https://github.com/brick/validation/blob/b33593f75df80530417007bde97c4772807563ab/src/Internal/Decimal.php#L97-L102
brick/validation
src/Internal/Decimal.php
Decimal.minus
public function minus(Decimal $that) : Decimal { $this->scaleValues($this, $that, $a, $b); $value = $a - $b; if (is_float($value)) { throw new \RangeException('The subtraction result overflows.'); } $scale = max($this->scale, $that->scale); while ($scale !== 0) { if ($value % 10 !== 0) { break; } $value /= 10; $scale--; } return new Decimal($value, $scale); }
php
public function minus(Decimal $that) : Decimal { $this->scaleValues($this, $that, $a, $b); $value = $a - $b; if (is_float($value)) { throw new \RangeException('The subtraction result overflows.'); } $scale = max($this->scale, $that->scale); while ($scale !== 0) { if ($value % 10 !== 0) { break; } $value /= 10; $scale--; } return new Decimal($value, $scale); }
@param Decimal $that @return Decimal @throws \RangeException If the result exceeds the size of an int on this platform.
https://github.com/brick/validation/blob/b33593f75df80530417007bde97c4772807563ab/src/Internal/Decimal.php#L111-L133
brick/validation
src/Internal/Decimal.php
Decimal.isDivisibleBy
public function isDivisibleBy(Decimal $that) : bool { $this->scaleValues($this, $that, $a, $b); return $a % $b === 0; }
php
public function isDivisibleBy(Decimal $that) : bool { $this->scaleValues($this, $that, $a, $b); return $a % $b === 0; }
@param Decimal $that @return bool @throws \RangeException If the result exceeds the size of an int on this platform.
https://github.com/brick/validation/blob/b33593f75df80530417007bde97c4772807563ab/src/Internal/Decimal.php#L142-L147
brick/validation
src/Internal/Decimal.php
Decimal.scaleValues
private function scaleValues(Decimal $x, Decimal $y, & $a, & $b) : void { $a = $x->value; $b = $y->value; if ($x->scale > $y->scale) { $b *= 10 ** ($x->scale - $y->scale); if (is_float($b)) { throw new \RangeException('The scaled result overflows.'); } } elseif ($x->scale < $y->scale) { $a *= 10 ** ($y->scale - $x->scale); if (is_float($a)) { throw new \RangeException('The scaled result overflows.'); } } }
php
private function scaleValues(Decimal $x, Decimal $y, & $a, & $b) : void { $a = $x->value; $b = $y->value; if ($x->scale > $y->scale) { $b *= 10 ** ($x->scale - $y->scale); if (is_float($b)) { throw new \RangeException('The scaled result overflows.'); } } elseif ($x->scale < $y->scale) { $a *= 10 ** ($y->scale - $x->scale); if (is_float($a)) { throw new \RangeException('The scaled result overflows.'); } } }
Puts the internal values of the given decimal numbers on the same scale. @param Decimal $x The first decimal number. @param Decimal $y The second decimal number. @param int $a A variable to store the scaled integer value of $x. @param int $b A variable to store the scaled integer value of $y. @return void @throws \RangeException If the scaled value exceeds the size of an int range on this platform.
https://github.com/brick/validation/blob/b33593f75df80530417007bde97c4772807563ab/src/Internal/Decimal.php#L169-L187
payapi/payapi-sdk-php
src/payapi/core/core.config.php
config.mode
public function mode($mode) { if ($mode !== false) { $this->staging = true; } else { $this->staging = false; } }
php
public function mode($mode) { if ($mode !== false) { $this->staging = true; } else { $this->staging = false; } }
-> @NOTE true enables staging mode, false for production
https://github.com/payapi/payapi-sdk-php/blob/6a675749c88742b261178d7977f2436d540132b4/src/payapi/core/core.config.php#L43-L50
atelierspierrot/templatengine
src/Assets/CompressorAdapter/JS.php
JS.minify
public static function minify($input) { $output = ''; $input = self::merge($input); $inQuotes = array(); $noSpacesAround = '{}()[]<>|&!?:;,+-*/="\''; $input = preg_replace("`(\r\n|\r)`", "\n", $input); $inputs = str_split($input); $inputs_count = count($inputs); $prevChr = null; for ($i=0; $i<$inputs_count; $i++) { $chr = $inputs[$i]; $nextChr = $i+1 < $inputs_count ? $inputs[$i+1] : null; switch ($chr) { case '/': if (!count($inQuotes) && $nextChr == '*' && $inputs[$i+2] != '@') { $i = 1 + strpos($input, '*/', $i); continue 2; } elseif (!count($inQuotes) && $nextChr == '/') { if (strpos($input, "\n", $i)) { $i = strpos($input, "\n", $i); } else { $i = strlen($input); } continue 2; } elseif (!count($inQuotes)) { $eolPos = strpos($input, "\n", $i); if ($eolPos===false) { $eolPos = $inputs_count; } $eol = substr($input, $i, $eolPos-$i); if (!preg_match('`^(/.+(?<=\\\/)/(?!/)[gim]*)[^gim]`U', $eol, $m)) { preg_match('`^(/.+(?<!/)/(?!/)[gim]*)[^gim]`U', $eol, $m); } // it's a RegExp if (isset($m[1])) { $output .= $m[1]; $i += strlen($m[1])-1; continue 2; } } break; case "'": case '"': if ($prevChr != '\\' || ($prevChr == '\\' && $inputs[$i-2] == '\\')) { if (end($inQuotes) == $chr) { array_pop($inQuotes); } elseif (!count($inQuotes)) { $inQuotes[] = $chr; } } break; case ' ': case "\t": case "\n": if (!count($inQuotes)) { if (strstr("{$noSpacesAround} \t\n", $nextChr) || strstr("{$noSpacesAround} \t\n", $prevChr) ) { continue 2; } $chr = ' '; } break; default: break; } $output .= $chr; $prevChr = $chr; } $output = trim($output); $output = str_replace(';}', '}', $output); return $output; }
php
public static function minify($input) { $output = ''; $input = self::merge($input); $inQuotes = array(); $noSpacesAround = '{}()[]<>|&!?:;,+-*/="\''; $input = preg_replace("`(\r\n|\r)`", "\n", $input); $inputs = str_split($input); $inputs_count = count($inputs); $prevChr = null; for ($i=0; $i<$inputs_count; $i++) { $chr = $inputs[$i]; $nextChr = $i+1 < $inputs_count ? $inputs[$i+1] : null; switch ($chr) { case '/': if (!count($inQuotes) && $nextChr == '*' && $inputs[$i+2] != '@') { $i = 1 + strpos($input, '*/', $i); continue 2; } elseif (!count($inQuotes) && $nextChr == '/') { if (strpos($input, "\n", $i)) { $i = strpos($input, "\n", $i); } else { $i = strlen($input); } continue 2; } elseif (!count($inQuotes)) { $eolPos = strpos($input, "\n", $i); if ($eolPos===false) { $eolPos = $inputs_count; } $eol = substr($input, $i, $eolPos-$i); if (!preg_match('`^(/.+(?<=\\\/)/(?!/)[gim]*)[^gim]`U', $eol, $m)) { preg_match('`^(/.+(?<!/)/(?!/)[gim]*)[^gim]`U', $eol, $m); } // it's a RegExp if (isset($m[1])) { $output .= $m[1]; $i += strlen($m[1])-1; continue 2; } } break; case "'": case '"': if ($prevChr != '\\' || ($prevChr == '\\' && $inputs[$i-2] == '\\')) { if (end($inQuotes) == $chr) { array_pop($inQuotes); } elseif (!count($inQuotes)) { $inQuotes[] = $chr; } } break; case ' ': case "\t": case "\n": if (!count($inQuotes)) { if (strstr("{$noSpacesAround} \t\n", $nextChr) || strstr("{$noSpacesAround} \t\n", $prevChr) ) { continue 2; } $chr = ' '; } break; default: break; } $output .= $chr; $prevChr = $chr; } $output = trim($output); $output = str_replace(';}', '}', $output); return $output; }
Inspired by <http://code.seebz.net/p/minify-js/>
https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/Assets/CompressorAdapter/JS.php#L46-L127
Porter-connectors/HttpConnector
src/Net/Http/HttpConnector.php
HttpConnector.fetch
public function fetch(ConnectionContext $context, $source) { $url = QueryBuilder::mergeQuery($source, $this->options->getQueryParameters()); $streamContext = stream_context_create([ 'http' => // Instruct PHP to ignore HTTP error codes so Porter can handle them instead. ['ignore_errors' => true] + $this->options->extractHttpContextOptions() , 'ssl' => $this->options->getSslOptions()->extractSslContextOptions(), ]); return $context->retry(static function () use ($url, $streamContext) { if (false === $body = @file_get_contents($url, false, $streamContext)) { $error = error_get_last(); throw new HttpConnectionException($error['message'], $error['type']); } $response = new HttpResponse($http_response_header, $body); if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 400) { throw new HttpServerException( "HTTP server responded with error: \"{$response->getReasonPhrase()}\".\n\n$response", $response ); } return $response; }); }
php
public function fetch(ConnectionContext $context, $source) { $url = QueryBuilder::mergeQuery($source, $this->options->getQueryParameters()); $streamContext = stream_context_create([ 'http' => // Instruct PHP to ignore HTTP error codes so Porter can handle them instead. ['ignore_errors' => true] + $this->options->extractHttpContextOptions() , 'ssl' => $this->options->getSslOptions()->extractSslContextOptions(), ]); return $context->retry(static function () use ($url, $streamContext) { if (false === $body = @file_get_contents($url, false, $streamContext)) { $error = error_get_last(); throw new HttpConnectionException($error['message'], $error['type']); } $response = new HttpResponse($http_response_header, $body); if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 400) { throw new HttpServerException( "HTTP server responded with error: \"{$response->getReasonPhrase()}\".\n\n$response", $response ); } return $response; }); }
{@inheritdoc} @param ConnectionContext $context Runtime connection settings and methods. @param string $source Source. @return HttpResponse Response. @throws \InvalidArgumentException Options is not an instance of HttpOptions. @throws HttpConnectionException Failed to connect to source. @throws HttpServerException Server sent an error code.
https://github.com/Porter-connectors/HttpConnector/blob/d6395e4e3fe1e772a1b99d3462b25eee919a7179/src/Net/Http/HttpConnector.php#L41-L71
ARCANEDEV/Markup
src/Entities/Tag/Type.php
Type.checkName
private function checkName(&$name) { if (! is_string($name)) { throw new InvalidTypeException( 'The tag type must be a string, ' . gettype($name) . ' is given.' ); } $name = strtolower(trim($name)); }
php
private function checkName(&$name) { if (! is_string($name)) { throw new InvalidTypeException( 'The tag type must be a string, ' . gettype($name) . ' is given.' ); } $name = strtolower(trim($name)); }
Check name @param string $name @throws InvalidTypeException
https://github.com/ARCANEDEV/Markup/blob/881331df74b27614d025c365daacbae6aa865612/src/Entities/Tag/Type.php#L65-L74
zikula/FileSystem
Facade/SftpFacade.php
SftpFacade.authPubkey
public function authPubkey($session, $username, $pubkey, $privkey, $passphrase) { return ssh2_auth_pubkey_file($session, $username, $pubkey, $privkey, $passphrase); }
php
public function authPubkey($session, $username, $pubkey, $privkey, $passphrase) { return ssh2_auth_pubkey_file($session, $username, $pubkey, $privkey, $passphrase); }
Facade for ssh2_auth_pubkey_file. @param resource $session The resource to login to. @param string $username The username to login with. @param string $pubkey The path to the public key to use. @param string $privkey The path to the private key. @param string $passphrase The passphrase for the key. @return boolean True if logged in.
https://github.com/zikula/FileSystem/blob/8e12d6839aa50a7590f5ad22cc2d33c8f88ff726/Facade/SftpFacade.php#L68-L71
zikula/FileSystem
Facade/SftpFacade.php
SftpFacade.scpSend
public function scpSend($session, $local_file, $remote_file, $create_mode = 0644) { return ssh2_scp_send($session, $local_file, $remote_file, $create_mode); }
php
public function scpSend($session, $local_file, $remote_file, $create_mode = 0644) { return ssh2_scp_send($session, $local_file, $remote_file, $create_mode); }
Facade for ssh2_scp_send. @param resource $session The sftp resource to use. @param string $local_file The local file to send. @param string $remote_file The remote path to write to. @param int $create_mode The permission of the remote file. @return boolean True on success.
https://github.com/zikula/FileSystem/blob/8e12d6839aa50a7590f5ad22cc2d33c8f88ff726/Facade/SftpFacade.php#L110-L113
keeko/framework
src/foundation/ModuleManager.php
ModuleManager.getSubscribedEvents
public static function getSubscribedEvents() { return [ ModuleEvent::INSTALLED => 'moduleUpdated', ModuleEvent::UNINSTALLED => 'moduleUninstalled', ModuleEvent::UPDATED => 'moduleUpdated', ModuleEvent::ACTIVATED => 'moduleActivated', ModuleEvent::DEACTIVATED => 'moduleDeactivated' ]; }
php
public static function getSubscribedEvents() { return [ ModuleEvent::INSTALLED => 'moduleUpdated', ModuleEvent::UNINSTALLED => 'moduleUninstalled', ModuleEvent::UPDATED => 'moduleUpdated', ModuleEvent::ACTIVATED => 'moduleActivated', ModuleEvent::DEACTIVATED => 'moduleDeactivated' ]; }
{@inheritDoc}
https://github.com/keeko/framework/blob/a2c5d76a4ab7bd658e81d88fb3c98eee115c06ac/src/foundation/ModuleManager.php#L57-L65
keeko/framework
src/foundation/ModuleManager.php
ModuleManager.load
public function load($packageName) { if ($this->loadedModules->has($packageName)) { return $this->loadedModules->get($packageName); } // check existence if (!$this->installedModules->has($packageName)) { throw new ModuleException(sprintf('Module (%s) does not exist.', $packageName), 500); } // check activation if (!$this->activatedModules->has($packageName)) { throw new ModuleException(sprintf('Module (%s) not activated', $packageName), 501); } $model = $this->activatedModules->get($packageName); if ($model->getInstalledVersion() > $model->getActivatedVersion()) { throw new ModuleException(sprintf('Module Version Mismatch (%s). Module needs to be updated by the Administrator', $packageName), 500); } // load $className = $model->getClassName(); /* @var $module AbstractModule */ $module = new $className($model, $this->service); $this->loadedModules->set($packageName, $module); // load locale $localeService = $this->getServiceContainer()->getLocaleService(); $file = sprintf('/%s/locales/{locale}/translations.json', $packageName); $localeService->loadLocaleFile($file, $module->getCanonicalName()); return $module; }
php
public function load($packageName) { if ($this->loadedModules->has($packageName)) { return $this->loadedModules->get($packageName); } // check existence if (!$this->installedModules->has($packageName)) { throw new ModuleException(sprintf('Module (%s) does not exist.', $packageName), 500); } // check activation if (!$this->activatedModules->has($packageName)) { throw new ModuleException(sprintf('Module (%s) not activated', $packageName), 501); } $model = $this->activatedModules->get($packageName); if ($model->getInstalledVersion() > $model->getActivatedVersion()) { throw new ModuleException(sprintf('Module Version Mismatch (%s). Module needs to be updated by the Administrator', $packageName), 500); } // load $className = $model->getClassName(); /* @var $module AbstractModule */ $module = new $className($model, $this->service); $this->loadedModules->set($packageName, $module); // load locale $localeService = $this->getServiceContainer()->getLocaleService(); $file = sprintf('/%s/locales/{locale}/translations.json', $packageName); $localeService->loadLocaleFile($file, $module->getCanonicalName()); return $module; }
Loads a module and returns the associated class or returns if already loaded @param String $packageName @throws ModuleException @return AbstractModule
https://github.com/keeko/framework/blob/a2c5d76a4ab7bd658e81d88fb3c98eee115c06ac/src/foundation/ModuleManager.php#L126-L160
prooph/processing
library/Type/String.php
String.buildDescription
public static function buildDescription() { if (DescriptionRegistry::hasDescription(__CLASS__)) return DescriptionRegistry::getDescription(__CLASS__); $desc = new Description('String', NativeType::STRING, false); DescriptionRegistry::registerDescriptionFor(__CLASS__, $desc); return $desc; }
php
public static function buildDescription() { if (DescriptionRegistry::hasDescription(__CLASS__)) return DescriptionRegistry::getDescription(__CLASS__); $desc = new Description('String', NativeType::STRING, false); DescriptionRegistry::registerDescriptionFor(__CLASS__, $desc); return $desc; }
The description is cached in the internal description property Implement the method to build the description only once and only if it is requested @return Description
https://github.com/prooph/processing/blob/a2947bccbffeecc4ca93a15e38ab53814e3e53e5/library/Type/String.php#L34-L43
prooph/processing
library/Type/String.php
String.setValue
protected function setValue($value) { if (!is_string($value)) { throw InvalidTypeException::fromMessageAndPrototype("Value must be a string", static::prototype()); } if(!mb_check_encoding($value, 'UTF-8')) { throw InvalidTypeException::fromMessageAndPrototype("Value must be a UTF-8 encoded", static::prototype()); } $this->value = $value; }
php
protected function setValue($value) { if (!is_string($value)) { throw InvalidTypeException::fromMessageAndPrototype("Value must be a string", static::prototype()); } if(!mb_check_encoding($value, 'UTF-8')) { throw InvalidTypeException::fromMessageAndPrototype("Value must be a UTF-8 encoded", static::prototype()); } $this->value = $value; }
Performs assertions and sets the internal value property on success @param mixed $value @throws Exception\InvalidTypeException @return void
https://github.com/prooph/processing/blob/a2947bccbffeecc4ca93a15e38ab53814e3e53e5/library/Type/String.php#L52-L63
fxpio/fxp-gluon
Block/Type/PanelSectionType.php
PanelSectionType.buildBlock
public function buildBlock(BlockBuilderInterface $builder, array $options) { if (!BlockUtil::isEmpty($options['label'])) { $builder->add('_heading', HeadingType::class, [ 'size' => 6, 'label' => $options['label'], ]); } if ($options['collapsible']) { $builder->add('_panel_section_actions', PanelActionsType::class, []); $builder->get('_panel_section_actions')->add('_button_collapse', ButtonType::class, [ 'label' => '', 'attr' => ['class' => 'btn-panel-collapse'], 'style' => 'default', 'prepend' => '<span class="caret"></span>', ]); } }
php
public function buildBlock(BlockBuilderInterface $builder, array $options) { if (!BlockUtil::isEmpty($options['label'])) { $builder->add('_heading', HeadingType::class, [ 'size' => 6, 'label' => $options['label'], ]); } if ($options['collapsible']) { $builder->add('_panel_section_actions', PanelActionsType::class, []); $builder->get('_panel_section_actions')->add('_button_collapse', ButtonType::class, [ 'label' => '', 'attr' => ['class' => 'btn-panel-collapse'], 'style' => 'default', 'prepend' => '<span class="caret"></span>', ]); } }
{@inheritdoc}
https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Type/PanelSectionType.php#L35-L53
fxpio/fxp-gluon
Block/Type/PanelSectionType.php
PanelSectionType.addChild
public function addChild(BlockInterface $child, BlockInterface $block, array $options) { if (BlockUtil::isBlockType($child, HeadingType::class)) { if ($block->has('_heading')) { $msg = 'The panel section block "%s" has already panel section title. Removes the label option of the panel section block.'; throw new InvalidConfigurationException(sprintf($msg, $block->getName())); } } elseif (BlockUtil::isBlockType($child, PanelActionsType::class)) { if ($block->getAttribute('already_actions')) { $actions = $block->get($block->getAttribute('already_actions')); foreach ($actions->all() as $action) { $child->add($action); } $block->remove($block->getAttribute('already_actions')); } else { $block->setAttribute('already_actions', $child->getName()); } } elseif (BlockUtil::isBlockType($child, PanelRowType::class)) { $cOptions = []; if (null !== $block->getOption('column')) { $cOptions['column'] = $block->getOption('column'); } if (null !== $block->getOption('layout_max')) { $cOptions['layout_max'] = $block->getOption('layout_max'); } if (null !== $block->getOption('layout_size')) { $cOptions['layout_size'] = $block->getOption('layout_size'); } if (null !== $block->getOption('layout_style') && null === $child->getOption('layout_style')) { $cOptions['layout_style'] = $block->getOption('layout_style'); } if (null !== $block->getOption('cell_label_style') && null === $child->getOption('cell_label_style')) { $cOptions['cell_label_style'] = $block->getOption('cell_label_style'); } $child->setOptions($cOptions); $this->setLastRow($block, $child); } elseif (BlockUtil::isBlockType($child, PanelCellType::class)) { $row = $this->getLastRow($block); $row->add($child); $block->remove($child->getName()); } }
php
public function addChild(BlockInterface $child, BlockInterface $block, array $options) { if (BlockUtil::isBlockType($child, HeadingType::class)) { if ($block->has('_heading')) { $msg = 'The panel section block "%s" has already panel section title. Removes the label option of the panel section block.'; throw new InvalidConfigurationException(sprintf($msg, $block->getName())); } } elseif (BlockUtil::isBlockType($child, PanelActionsType::class)) { if ($block->getAttribute('already_actions')) { $actions = $block->get($block->getAttribute('already_actions')); foreach ($actions->all() as $action) { $child->add($action); } $block->remove($block->getAttribute('already_actions')); } else { $block->setAttribute('already_actions', $child->getName()); } } elseif (BlockUtil::isBlockType($child, PanelRowType::class)) { $cOptions = []; if (null !== $block->getOption('column')) { $cOptions['column'] = $block->getOption('column'); } if (null !== $block->getOption('layout_max')) { $cOptions['layout_max'] = $block->getOption('layout_max'); } if (null !== $block->getOption('layout_size')) { $cOptions['layout_size'] = $block->getOption('layout_size'); } if (null !== $block->getOption('layout_style') && null === $child->getOption('layout_style')) { $cOptions['layout_style'] = $block->getOption('layout_style'); } if (null !== $block->getOption('cell_label_style') && null === $child->getOption('cell_label_style')) { $cOptions['cell_label_style'] = $block->getOption('cell_label_style'); } $child->setOptions($cOptions); $this->setLastRow($block, $child); } elseif (BlockUtil::isBlockType($child, PanelCellType::class)) { $row = $this->getLastRow($block); $row->add($child); $block->remove($child->getName()); } }
{@inheritdoc}
https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Type/PanelSectionType.php#L69-L118
fxpio/fxp-gluon
Block/Type/PanelSectionType.php
PanelSectionType.finishView
public function finishView(BlockView $view, BlockInterface $block, array $options) { $hasRow = 0; $hasRenderedRow = false; foreach ($view->children as $name => $child) { if (\in_array('heading', $child->vars['block_prefixes'])) { BlockUtil::addAttributeClass($child, 'panel-section-title'); $view->vars['panel_section_heading'] = $child; unset($view->children[$name]); } elseif (\in_array('panel_actions', $child->vars['block_prefixes'])) { if (\count($child->children) > 0 || isset($child->vars['panel_button_collapse'])) { $view->vars['panel_section_actions'] = $child; } unset($view->children[$name]); } elseif (\in_array('panel_row', $child->vars['block_prefixes'])) { ++$hasRow; if (!$hasRenderedRow && $child->vars['rendered']) { $hasRenderedRow = true; } } } if (!is_scalar($view->vars['value'])) { $view->vars['value'] = ''; } if ($view->vars['hidden_if_empty'] && BlockUtil::isEmpty($view->vars['value']) && $hasRow === \count($view->children) && !$hasRenderedRow) { $view->vars['rendered'] = false; } }
php
public function finishView(BlockView $view, BlockInterface $block, array $options) { $hasRow = 0; $hasRenderedRow = false; foreach ($view->children as $name => $child) { if (\in_array('heading', $child->vars['block_prefixes'])) { BlockUtil::addAttributeClass($child, 'panel-section-title'); $view->vars['panel_section_heading'] = $child; unset($view->children[$name]); } elseif (\in_array('panel_actions', $child->vars['block_prefixes'])) { if (\count($child->children) > 0 || isset($child->vars['panel_button_collapse'])) { $view->vars['panel_section_actions'] = $child; } unset($view->children[$name]); } elseif (\in_array('panel_row', $child->vars['block_prefixes'])) { ++$hasRow; if (!$hasRenderedRow && $child->vars['rendered']) { $hasRenderedRow = true; } } } if (!is_scalar($view->vars['value'])) { $view->vars['value'] = ''; } if ($view->vars['hidden_if_empty'] && BlockUtil::isEmpty($view->vars['value']) && $hasRow === \count($view->children) && !$hasRenderedRow) { $view->vars['rendered'] = false; } }
{@inheritdoc}
https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Type/PanelSectionType.php#L140-L175
fxpio/fxp-gluon
Block/Type/PanelSectionType.php
PanelSectionType.setLastRow
protected function setLastRow(BlockInterface $block, BlockInterface $row) { if (!BlockUtil::isBlockType($row, PanelRowSpacerType::class)) { $block->setAttribute('last_row', $row->getName()); } }
php
protected function setLastRow(BlockInterface $block, BlockInterface $row) { if (!BlockUtil::isBlockType($row, PanelRowSpacerType::class)) { $block->setAttribute('last_row', $row->getName()); } }
Set the last row. @param BlockInterface $block @param BlockInterface $row
https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Type/PanelSectionType.php#L218-L223
fxpio/fxp-gluon
Block/Type/PanelSectionType.php
PanelSectionType.getLastRow
protected function getLastRow(BlockInterface $block) { if ($block->hasAttribute('last_row')) { $row = $block->get($block->getAttribute('last_row')); // return current row if (\count($row) < $row->getOption('column')) { return $row; } } // new row $rowName = BlockUtil::createUniqueName(); $block->add($rowName, PanelRowType::class); return $block->get($rowName); }
php
protected function getLastRow(BlockInterface $block) { if ($block->hasAttribute('last_row')) { $row = $block->get($block->getAttribute('last_row')); // return current row if (\count($row) < $row->getOption('column')) { return $row; } } // new row $rowName = BlockUtil::createUniqueName(); $block->add($rowName, PanelRowType::class); return $block->get($rowName); }
Get the last row. @param BlockInterface $block @return BlockInterface
https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Type/PanelSectionType.php#L232-L248
ajaxtown/eaglehorn_framework
src/Eaglehorn/Router.php
Router.execute
static function execute(Base $base) { self::$_base = $base; //first we separate the parameters $request = isset($_REQUEST['route']) ? $_REQUEST['route'] : '/'; if(strpos($request,'?') > 0) { $split = explode('?',$request); $request = $split[0]; } self::$_attr = array_slice(explode('/', trim($request, '/')), 2); self::_run($request); return self::$callback; }
php
static function execute(Base $base) { self::$_base = $base; //first we separate the parameters $request = isset($_REQUEST['route']) ? $_REQUEST['route'] : '/'; if(strpos($request,'?') > 0) { $split = explode('?',$request); $request = $split[0]; } self::$_attr = array_slice(explode('/', trim($request, '/')), 2); self::_run($request); return self::$callback; }
Executes the router @return mixed
https://github.com/ajaxtown/eaglehorn_framework/blob/5e2a1456ff6c65b3925f1219f115d8a919930f52/src/Eaglehorn/Router.php#L59-L76
ajaxtown/eaglehorn_framework
src/Eaglehorn/Router.php
Router._run
private static function _run($request) { // Whether or not we have matched the URL to a route $matched_route = false; $request = '/' . $request; //make sure the request has a trailing slash $request = rtrim($request, '/') . '/'; $request = str_replace("//","/",$request); // Sort the array by priority ksort(self::$_routes); // Loop through each priority level foreach (self::$_routes as $priority => $routes) { // Loop through each route for this priority level foreach ($routes as $source => $destination) { // Does the routing rule match the current URL? if (preg_match($source, $request, $matches)) { // A routing rule was matched $matched_route = TRUE; $attr = implode('/',array_intersect_key($matches, array_flip(array_filter(array_keys($matches), 'is_string')))); self::$_attr = explode('/', trim($attr, '/')); self::_set_callback($destination); } } } if(!$matched_route) { if($request != '/') { self::_set_callback($request); } } }
php
private static function _run($request) { // Whether or not we have matched the URL to a route $matched_route = false; $request = '/' . $request; //make sure the request has a trailing slash $request = rtrim($request, '/') . '/'; $request = str_replace("//","/",$request); // Sort the array by priority ksort(self::$_routes); // Loop through each priority level foreach (self::$_routes as $priority => $routes) { // Loop through each route for this priority level foreach ($routes as $source => $destination) { // Does the routing rule match the current URL? if (preg_match($source, $request, $matches)) { // A routing rule was matched $matched_route = TRUE; $attr = implode('/',array_intersect_key($matches, array_flip(array_filter(array_keys($matches), 'is_string')))); self::$_attr = explode('/', trim($attr, '/')); self::_set_callback($destination); } } } if(!$matched_route) { if($request != '/') { self::_set_callback($request); } } }
Tries to match one of the URL routes to the current URL, otherwise execute the default function. Sets the callback that needs to be returned @param string $request
https://github.com/ajaxtown/eaglehorn_framework/blob/5e2a1456ff6c65b3925f1219f115d8a919930f52/src/Eaglehorn/Router.php#L86-L129
ajaxtown/eaglehorn_framework
src/Eaglehorn/Router.php
Router._set_callback
private static function _set_callback($destination) { if(is_callable($destination)) { self::$callback = array($destination,self::$_attr); } else { $result = explode('/', trim($destination, '/')); //fix the controller now $controller = ($result[0] == "") ? configItem('site')['default_controller'] : str_replace('-', '/', $result[0]); //if no method, set it to index $method = isset($result[1]) ? $result[1] : 'index'; //if controller is valid file if (self::fileExists($file = ucfirst(configItem('site')['cust_controller_dir']) . $controller . '.php',false)) { self::$callback = array(ucFirst($controller), $method, self::$_attr); } else { header("HTTP/1.0 404 Not Found"); self::$_base->hook('404',array( 'file' => $file, 'controller' => $controller, 'method' => $method, 'message' => '404' )); die(); } } }
php
private static function _set_callback($destination) { if(is_callable($destination)) { self::$callback = array($destination,self::$_attr); } else { $result = explode('/', trim($destination, '/')); //fix the controller now $controller = ($result[0] == "") ? configItem('site')['default_controller'] : str_replace('-', '/', $result[0]); //if no method, set it to index $method = isset($result[1]) ? $result[1] : 'index'; //if controller is valid file if (self::fileExists($file = ucfirst(configItem('site')['cust_controller_dir']) . $controller . '.php',false)) { self::$callback = array(ucFirst($controller), $method, self::$_attr); } else { header("HTTP/1.0 404 Not Found"); self::$_base->hook('404',array( 'file' => $file, 'controller' => $controller, 'method' => $method, 'message' => '404' )); die(); } } }
Sets the callback as an array containing Controller, Method & Parameters @param string $destination
https://github.com/ajaxtown/eaglehorn_framework/blob/5e2a1456ff6c65b3925f1219f115d8a919930f52/src/Eaglehorn/Router.php#L136-L166
phPoirot/Client-OAuth2
src/Grant/aGrantRequest.php
aGrantRequest.__toArray
function __toArray() { $params = __( new HydrateGetters($this) ) ->setExcludeNullValues(); $params = StdTravers::of($params)->toArray(null, true); return $params; }
php
function __toArray() { $params = __( new HydrateGetters($this) ) ->setExcludeNullValues(); $params = StdTravers::of($params)->toArray(null, true); return $params; }
Get Grant Request Params As Array @return array
https://github.com/phPoirot/Client-OAuth2/blob/8745fd54afbbb185669b9e38b1241ecc8ffc7268/src/Grant/aGrantRequest.php#L33-L40
inhere/php-library-plus
libs/Task/Handlers/Task.php
Task.run
public function run($workload, TaskWrapper $task) { $result = false; $this->id = $task->getId(); $this->name = $task->getName(); try { if (false !== $this->beforeRun($workload, $task)) { $result = $this->doRun($workload, $task); $this->afterRun($result); } } catch (\Exception $e) { $this->onException($e); } return $result; }
php
public function run($workload, TaskWrapper $task) { $result = false; $this->id = $task->getId(); $this->name = $task->getName(); try { if (false !== $this->beforeRun($workload, $task)) { $result = $this->doRun($workload, $task); $this->afterRun($result); } } catch (\Exception $e) { $this->onException($e); } return $result; }
do the job @param string $workload @param TaskWrapper $task @return mixed
https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Task/Handlers/Task.php#L48-L65
schpill/thin
src/Filter/Normalize.php
Normalize.filter
public function filter($value) { // transliteration $value = strtr($value, $this->transliteration); // change to lowercase if($this->transformCase) { $value = mb_convert_case($value, MB_CASE_LOWER, 'utf8'); } // replace punctuation if($this->transformPunctuation) { $value = strtr($value, $this->punctuation); } return $value; }
php
public function filter($value) { // transliteration $value = strtr($value, $this->transliteration); // change to lowercase if($this->transformCase) { $value = mb_convert_case($value, MB_CASE_LOWER, 'utf8'); } // replace punctuation if($this->transformPunctuation) { $value = strtr($value, $this->punctuation); } return $value; }
Normalise the input string @param string $value String to be normalised @return string Normalised string
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Filter/Normalize.php#L115-L131
schpill/thin
src/Filter/Normalize.php
Normalize.setTransliterationReplacements
public function setTransliterationReplacements($replacements) { if(!is_array($replacements)) { throw new \Thin\Exception(__METHOD__ . ': method expects a keyed array as argument.', 500); } foreach($replacements as $key => $value) { $this->transliteration[$key] = $value; } return $this; }
php
public function setTransliterationReplacements($replacements) { if(!is_array($replacements)) { throw new \Thin\Exception(__METHOD__ . ': method expects a keyed array as argument.', 500); } foreach($replacements as $key => $value) { $this->transliteration[$key] = $value; } return $this; }
Set transliteration replacement values. @param array $replacements A keyed array of characters to replace, e.g. ['Ł' => 'L']; @return \Thin\Filter\Normalise Provides a fluent interface @throws \Thin\Exception in case the argument is not an array.
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Filter/Normalize.php#L174-L183
schpill/thin
src/Filter/Normalize.php
Normalize.setPunctuationReplacements
public function setPunctuationReplacements($replacements) { if(!is_array($replacements)) { throw new \Thin\Exception(__METHOD__ . ': method expects a keyed array as argument.', 500); } foreach($replacements as $key => $value) { $this->punctuation[$key] = $value; } return $this; }
php
public function setPunctuationReplacements($replacements) { if(!is_array($replacements)) { throw new \Thin\Exception(__METHOD__ . ': method expects a keyed array as argument.', 500); } foreach($replacements as $key => $value) { $this->punctuation[$key] = $value; } return $this; }
Set punctuation replacement values. @param array $replacements A keyed array of characters to replace, e.g. [' ' => '_']; @return \Thin\Filter\Normalise Provides a fluent interface @throws \Thin\Exception in case the argument is not an array.
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Filter/Normalize.php#L196-L205
rkeet/zf-doctrine-mvc
src/Entity/AbstractEntity.php
AbstractEntity.setEventManager
public function setEventManager(EventManagerInterface $events) : AbstractEntity { $className = get_class($this); $nsPos = strpos($className, '\\') ?: 0; $events->setIdentifiers( array_merge( [ __CLASS__, $className, substr($className, 0, $nsPos), ], array_values(class_implements($className)), (array) $this->eventIdentifier ) ); $this->events = $events; return $this; }
php
public function setEventManager(EventManagerInterface $events) : AbstractEntity { $className = get_class($this); $nsPos = strpos($className, '\\') ?: 0; $events->setIdentifiers( array_merge( [ __CLASS__, $className, substr($className, 0, $nsPos), ], array_values(class_implements($className)), (array) $this->eventIdentifier ) ); $this->events = $events; return $this; }
Set the event manager instance used by this context @param EventManagerInterface $events @return AbstractEntity
https://github.com/rkeet/zf-doctrine-mvc/blob/ec5fb19e453824383b39570d15bd77b85cec3ca1/src/Entity/AbstractEntity.php#L67-L87
rkeet/zf-doctrine-mvc
src/Entity/AbstractEntity.php
AbstractEntity.setEvent
public function setEvent(Event $e) : void { if ( ! $e instanceof DoctrineEvent) { $eventParams = $e->getParams(); $e = new DoctrineEvent(); $e->setParams($eventParams); unset($eventParams); } $this->event = $e; }
php
public function setEvent(Event $e) : void { if ( ! $e instanceof DoctrineEvent) { $eventParams = $e->getParams(); $e = new DoctrineEvent(); $e->setParams($eventParams); unset($eventParams); } $this->event = $e; }
Set an event to use during dispatch By default, will re-cast to MvcEvent if another event type is provided. @param Event $e @return void
https://github.com/rkeet/zf-doctrine-mvc/blob/ec5fb19e453824383b39570d15bd77b85cec3ca1/src/Entity/AbstractEntity.php#L114-L123
rkeet/zf-doctrine-mvc
src/Entity/AbstractEntity.php
AbstractEntity.getArrayCopy
public function getArrayCopy() : array { $values = get_object_vars($this); foreach ($values as $property => $value) { // Skip relations if (is_object($value)) { unset($values[$property]); } } return $values; }
php
public function getArrayCopy() : array { $values = get_object_vars($this); foreach ($values as $property => $value) { // Skip relations if (is_object($value)) { unset($values[$property]); } } return $values; }
Gets an array copy
https://github.com/rkeet/zf-doctrine-mvc/blob/ec5fb19e453824383b39570d15bd77b85cec3ca1/src/Entity/AbstractEntity.php#L144-L155
rkeet/zf-doctrine-mvc
src/Entity/AbstractEntity.php
AbstractEntity.exchangeArray
public function exchangeArray($data) { foreach ($data as $property => $value) { if (isset($this->$property)) { $method = 'set' . ucfirst($property); $this->$method($value); } } }
php
public function exchangeArray($data) { foreach ($data as $property => $value) { if (isset($this->$property)) { $method = 'set' . ucfirst($property); $this->$method($value); } } }
Maps the specified data to the properties of this object @param array $data
https://github.com/rkeet/zf-doctrine-mvc/blob/ec5fb19e453824383b39570d15bd77b85cec3ca1/src/Entity/AbstractEntity.php#L162-L170
rkeet/zf-doctrine-mvc
src/Entity/AbstractEntity.php
AbstractEntity.getAssociations
public function getAssociations() : array { $values = get_object_vars($this); foreach ($values as $property => $value) { // Skip scalar values if ( ! is_object($value)) { unset($values[$property]); } } return $values; }
php
public function getAssociations() : array { $values = get_object_vars($this); foreach ($values as $property => $value) { // Skip scalar values if ( ! is_object($value)) { unset($values[$property]); } } return $values; }
Gets associations
https://github.com/rkeet/zf-doctrine-mvc/blob/ec5fb19e453824383b39570d15bd77b85cec3ca1/src/Entity/AbstractEntity.php#L175-L186
andyburton/Sonic-Framework
src/Controller/Session.php
Session.callAction
public function callAction () { // Only call the method if the user is authenticated if ($this->checkAuthenticated ()) { $this->view->assign ('user', $this->user); parent::callAction (); } }
php
public function callAction () { // Only call the method if the user is authenticated if ($this->checkAuthenticated ()) { $this->view->assign ('user', $this->user); parent::callAction (); } }
Call controller action method @return void
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Controller/Session.php#L36-L47
andyburton/Sonic-Framework
src/Controller/Session.php
Session.checkAuthenticated
protected function checkAuthenticated () { // Create user if (!$this->user) { $this->user = new \Sonic\Model\User; } // Check authenticated $auth = $this->user->initSession (); if ($auth !== TRUE) { switch ($auth) { case 'invalid_session': new Message ('error', 'Please login to continue'); break; case 'user_read_error': new Message ('error', 'There seems to be a problem, please login to continue'); break; case 'inactive': new Message ('error', 'Account not activated'); break; case 'timeout': new Message ('error', 'Your session has expired, please login to continue'); break; } $this->template = $this->authModule? strtolower ($this->authModule) . '/' : NULL; $this->template .= 'login.tpl'; return FALSE; } // Return return TRUE; }
php
protected function checkAuthenticated () { // Create user if (!$this->user) { $this->user = new \Sonic\Model\User; } // Check authenticated $auth = $this->user->initSession (); if ($auth !== TRUE) { switch ($auth) { case 'invalid_session': new Message ('error', 'Please login to continue'); break; case 'user_read_error': new Message ('error', 'There seems to be a problem, please login to continue'); break; case 'inactive': new Message ('error', 'Account not activated'); break; case 'timeout': new Message ('error', 'Your session has expired, please login to continue'); break; } $this->template = $this->authModule? strtolower ($this->authModule) . '/' : NULL; $this->template .= 'login.tpl'; return FALSE; } // Return return TRUE; }
Check the user is authenticated @return boolean
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Controller/Session.php#L55-L101
ezsystems/ezprestapiprovider
classes/models/rest_content_model.php
ezpRestContentModel.getMetadataByContent
public static function getMetadataByContent( ezpContent $content ) { $aMetadata = array( 'objectName' => $content->name, 'classIdentifier' => $content->classIdentifier, 'datePublished' => (int)$content->datePublished, 'dateModified' => (int)$content->dateModified, 'objectRemoteId' => $content->remote_id, 'objectId' => (int)$content->id ); return $aMetadata; }
php
public static function getMetadataByContent( ezpContent $content ) { $aMetadata = array( 'objectName' => $content->name, 'classIdentifier' => $content->classIdentifier, 'datePublished' => (int)$content->datePublished, 'dateModified' => (int)$content->dateModified, 'objectRemoteId' => $content->remote_id, 'objectId' => (int)$content->id ); return $aMetadata; }
Returns metadata for given content as array @param ezpContent $content @return array
https://github.com/ezsystems/ezprestapiprovider/blob/98012d22225fca242fa6b87cd7c71bf912ca8cbd/classes/models/rest_content_model.php#L19-L31
ezsystems/ezprestapiprovider
classes/models/rest_content_model.php
ezpRestContentModel.getMetadataByLocation
public static function getMetadataByLocation( ezpContentLocation $location ) { $url = $location->url_alias; eZURI::transformURI( $url, false, 'full' ); // $url is passed as a reference $aMetadata = array( 'nodeId' => (int)$location->node_id, 'nodeRemoteId' => $location->remote_id, 'fullUrl' => $url ); return $aMetadata; }
php
public static function getMetadataByLocation( ezpContentLocation $location ) { $url = $location->url_alias; eZURI::transformURI( $url, false, 'full' ); // $url is passed as a reference $aMetadata = array( 'nodeId' => (int)$location->node_id, 'nodeRemoteId' => $location->remote_id, 'fullUrl' => $url ); return $aMetadata; }
Returns metadata for given content location as array @param ezpContentLocation $location @return array
https://github.com/ezsystems/ezprestapiprovider/blob/98012d22225fca242fa6b87cd7c71bf912ca8cbd/classes/models/rest_content_model.php#L38-L50
ezsystems/ezprestapiprovider
classes/models/rest_content_model.php
ezpRestContentModel.getLocationsByContent
public static function getLocationsByContent( ezpContent $content ) { $aReturnLocations = array(); $assignedNodes = $content->assigned_nodes; foreach ( $assignedNodes as $node ) { $location = ezpContentLocation::fromNode( $node ); $locationData = self::getMetadataByLocation( $location ); $locationData['isMain'] = $location->is_main; $aReturnLocations[] = $locationData; } return $aReturnLocations; }
php
public static function getLocationsByContent( ezpContent $content ) { $aReturnLocations = array(); $assignedNodes = $content->assigned_nodes; foreach ( $assignedNodes as $node ) { $location = ezpContentLocation::fromNode( $node ); $locationData = self::getMetadataByLocation( $location ); $locationData['isMain'] = $location->is_main; $aReturnLocations[] = $locationData; } return $aReturnLocations; }
Returns all locations for provided content as array. @param ezpContent $content @return array Associative array with following keys : - fullUrl => URL for content, including server - nodeId => NodeID for location - remoteId => RemoteID for location - isMain => whether location is main for provided content
https://github.com/ezsystems/ezprestapiprovider/blob/98012d22225fca242fa6b87cd7c71bf912ca8cbd/classes/models/rest_content_model.php#L61-L74
ezsystems/ezprestapiprovider
classes/models/rest_content_model.php
ezpRestContentModel.getFieldsByContent
public static function getFieldsByContent( ezpContent $content ) { $aReturnFields = array(); foreach ( $content->fields as $name => $field ) { $aReturnFields[$name] = self::attributeOutputData( $field ); } return $aReturnFields; }
php
public static function getFieldsByContent( ezpContent $content ) { $aReturnFields = array(); foreach ( $content->fields as $name => $field ) { $aReturnFields[$name] = self::attributeOutputData( $field ); } return $aReturnFields; }
Returns all fields for provided content @param ezpContent $content @return array Associative array with following keys : - type => Field type (datatype string) - identifier => Attribute identifier - value => String representation of field content - id => Attribute numerical ID - classattribute_id => Numerical class attribute ID
https://github.com/ezsystems/ezprestapiprovider/blob/98012d22225fca242fa6b87cd7c71bf912ca8cbd/classes/models/rest_content_model.php#L86-L95
ezsystems/ezprestapiprovider
classes/models/rest_content_model.php
ezpRestContentModel.attributeOutputData
public static function attributeOutputData( ezpContentField $field ) { // @TODO move to datatype representation layer switch ( $field->data_type_string ) { case 'ezxmltext': $html = $field->content->attribute( 'output' )->attribute( 'output_text' ); $attributeValue = array( strip_tags( $html ) ); break; case 'ezimage': $strRepImage = $field->toString(); $delimPos = strpos( $strRepImage, '|' ); if ( $delimPos !== false ) { $strRepImage = substr( $strRepImage, 0, $delimPos ); } $attributeValue = array( $strRepImage ); break; default: $datatypeBlacklist = array_fill_keys( eZINI::instance()->variable( 'ContentSettings', 'DatatypeBlackListForExternal' ), true ); if ( isset ( $datatypeBlacklist[$field->data_type_string] ) ) $attributeValue = array( null ); else $attributeValue = array( $field->toString() ); break; } // cleanup values so that the result is consistent: // - no array if one item // - false if no values if ( count( $attributeValue ) == 0 ) { $attributeValue = false; } else if ( count( $attributeValue ) == 1 ) { $attributeValue = current( $attributeValue ); } return array( 'type' => $field->data_type_string, 'identifier' => $field->contentclass_attribute_identifier, 'value' => $attributeValue, 'id' => (int)$field->id, 'classattribute_id' => (int)$field->contentclassattribute_id ); }
php
public static function attributeOutputData( ezpContentField $field ) { // @TODO move to datatype representation layer switch ( $field->data_type_string ) { case 'ezxmltext': $html = $field->content->attribute( 'output' )->attribute( 'output_text' ); $attributeValue = array( strip_tags( $html ) ); break; case 'ezimage': $strRepImage = $field->toString(); $delimPos = strpos( $strRepImage, '|' ); if ( $delimPos !== false ) { $strRepImage = substr( $strRepImage, 0, $delimPos ); } $attributeValue = array( $strRepImage ); break; default: $datatypeBlacklist = array_fill_keys( eZINI::instance()->variable( 'ContentSettings', 'DatatypeBlackListForExternal' ), true ); if ( isset ( $datatypeBlacklist[$field->data_type_string] ) ) $attributeValue = array( null ); else $attributeValue = array( $field->toString() ); break; } // cleanup values so that the result is consistent: // - no array if one item // - false if no values if ( count( $attributeValue ) == 0 ) { $attributeValue = false; } else if ( count( $attributeValue ) == 1 ) { $attributeValue = current( $attributeValue ); } return array( 'type' => $field->data_type_string, 'identifier' => $field->contentclass_attribute_identifier, 'value' => $attributeValue, 'id' => (int)$field->id, 'classattribute_id' => (int)$field->contentclassattribute_id ); }
Transforms an ezpContentField in an array representation @todo Refactor, this doesn't really belong here. Either in ezpContentField, or in an extend class @param ezpContentField $field @return array Associative array with following keys : - type => Field type (datatype string) - identifier => Attribute identifier - value => String representation of field content - id => Attribute numerical ID - classattribute_id => Numerical class attribute ID
https://github.com/ezsystems/ezprestapiprovider/blob/98012d22225fca242fa6b87cd7c71bf912ca8cbd/classes/models/rest_content_model.php#L108-L157
ezsystems/ezprestapiprovider
classes/models/rest_content_model.php
ezpRestContentModel.getFieldsLinksByContent
public static function getFieldsLinksByContent( ezpContent $content, ezpRestRequest $currentRequest ) { $links = array(); $baseUri = $currentRequest->getBaseURI(); $contentQueryString = $currentRequest->getContentQueryString( true ); foreach ( $content->fields as $fieldName => $fieldValue ) { $links[$fieldName] = $baseUri.'/field/'.$fieldName.$contentQueryString; } $links['*'] = $baseUri.'/fields'.$contentQueryString; return $links; }
php
public static function getFieldsLinksByContent( ezpContent $content, ezpRestRequest $currentRequest ) { $links = array(); $baseUri = $currentRequest->getBaseURI(); $contentQueryString = $currentRequest->getContentQueryString( true ); foreach ( $content->fields as $fieldName => $fieldValue ) { $links[$fieldName] = $baseUri.'/field/'.$fieldName.$contentQueryString; } $links['*'] = $baseUri.'/fields'.$contentQueryString; return $links; }
Returns fields links for a given content, for a potential future request on a specific field. Note that every link provided is based on the current URI. So for a content REST request "/content/node/2?Translation=eng-GB", a field link will look like "content/node/2/field/field_identifier?Translation=eng-GB" @param ezpContent $content @param ezpRestRequest $currentRequest Current REST request object. Needed to build proper links @return array Associative array, indexed by field identifier. An additional "*" index is added to request every fields
https://github.com/ezsystems/ezprestapiprovider/blob/98012d22225fca242fa6b87cd7c71bf912ca8cbd/classes/models/rest_content_model.php#L167-L180
ezsystems/ezprestapiprovider
classes/models/rest_content_model.php
ezpRestContentModel.getChildrenList
public static function getChildrenList( ezpContentCriteria $c, ezpRestRequest $currentRequest, array $responseGroups = array() ) { $aRetData = array(); $aChildren = ezpContentRepository::query( $c ); foreach ( $aChildren as $childNode ) { $childEntry = self::getMetadataByContent( $childNode ); $childEntry = array_merge( $childEntry, self::getMetadataByLocation( $childNode->locations ) ); // Add fields with their values if requested if ( in_array( ezpRestContentController::VIEWLIST_RESPONSEGROUP_FIELDS, $responseGroups ) ) { $childEntry['fields'] = array(); foreach ( $childNode->fields as $fieldName => $field ) { $childEntry['fields'][$fieldName] = self::attributeOutputData( $field ); } } $aRetData[] = $childEntry; } return $aRetData; }
php
public static function getChildrenList( ezpContentCriteria $c, ezpRestRequest $currentRequest, array $responseGroups = array() ) { $aRetData = array(); $aChildren = ezpContentRepository::query( $c ); foreach ( $aChildren as $childNode ) { $childEntry = self::getMetadataByContent( $childNode ); $childEntry = array_merge( $childEntry, self::getMetadataByLocation( $childNode->locations ) ); // Add fields with their values if requested if ( in_array( ezpRestContentController::VIEWLIST_RESPONSEGROUP_FIELDS, $responseGroups ) ) { $childEntry['fields'] = array(); foreach ( $childNode->fields as $fieldName => $field ) { $childEntry['fields'][$fieldName] = self::attributeOutputData( $field ); } } $aRetData[] = $childEntry; } return $aRetData; }
Returns all children node data, based on the provided criteria object @param ezpContentCriteria $c @param ezpRestRequest $currentRequest @param array $responseGroups Requested ResponseGroups @return array
https://github.com/ezsystems/ezprestapiprovider/blob/98012d22225fca242fa6b87cd7c71bf912ca8cbd/classes/models/rest_content_model.php#L189-L213
luoxiaojun1992/lb_framework
components/Auth.php
Auth.authBasic
public static function authBasic($user, $password, $request = null) { return ($request ? $request->getBasicAuthUser() : Lb::app()->getBasicAuthUser()) == $user && HashHelper::hash($request ? $request->getBasicAuthPassword() : Lb::app()->getBasicAuthPassword()) == $password; }
php
public static function authBasic($user, $password, $request = null) { return ($request ? $request->getBasicAuthUser() : Lb::app()->getBasicAuthUser()) == $user && HashHelper::hash($request ? $request->getBasicAuthPassword() : Lb::app()->getBasicAuthPassword()) == $password; }
Basic Authentication @param $user @param $password @param $request RequestContract @return bool
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/Auth.php#L25-L29
luoxiaojun1992/lb_framework
components/Auth.php
Auth.authQueryString
public static function authQueryString($authKey, $accessToken, $request = null) { return HashHelper::hash($request ? $request->getParam($authKey) : Lb::app()->getParam($authKey)) == $accessToken; }
php
public static function authQueryString($authKey, $accessToken, $request = null) { return HashHelper::hash($request ? $request->getParam($authKey) : Lb::app()->getParam($authKey)) == $accessToken; }
Query String Authentication @param $authKey @param $accessToken @param $request RequestContract @return bool
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/Auth.php#L39-L42
alphacomm/alpharpc
src/AlphaRPC/Manager/Protocol/ClientHandlerJobRequest.php
ClientHandlerJobRequest.fromMessage
public static function fromMessage(Message $msg) { $requestId = $msg->shift(); $actionName = $msg->shift(); $parameters = $msg->toArray(); return new self($requestId, $actionName, $parameters); }
php
public static function fromMessage(Message $msg) { $requestId = $msg->shift(); $actionName = $msg->shift(); $parameters = $msg->toArray(); return new self($requestId, $actionName, $parameters); }
Creates an instance from the Message. @param Message $msg @return ClientHandlerJobRequest
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Manager/Protocol/ClientHandlerJobRequest.php#L93-L100
alphacomm/alpharpc
src/AlphaRPC/Manager/Protocol/ClientHandlerJobRequest.php
ClientHandlerJobRequest.toMessage
public function toMessage() { $m = new Message(array( $this->getRequestId(), $this->getActionName(), )); $m->append($this->getParameters()); return $m; }
php
public function toMessage() { $m = new Message(array( $this->getRequestId(), $this->getActionName(), )); $m->append($this->getParameters()); return $m; }
Create a new Message from this StorageStatus. @return Message
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Manager/Protocol/ClientHandlerJobRequest.php#L107-L116
rnijveld/pgt
lib/Pgettext/Pgettext.php
Pgettext.msgfmt
public static function msgfmt($po, $mo = null) { $stringset = Po::fromFile($po); if ($mo === null) { $mo = substr($po, 0, -3) . '.mo'; } Mo::toFile($stringset, $mo); }
php
public static function msgfmt($po, $mo = null) { $stringset = Po::fromFile($po); if ($mo === null) { $mo = substr($po, 0, -3) . '.mo'; } Mo::toFile($stringset, $mo); }
Read a po file and store a mo file. If no MO filename is given, one will be generated from the PO filename. @param string $po Filename of the input PO file. @param string $mo Filename of the output MO file. @return void
https://github.com/rnijveld/pgt/blob/9d64b4858438a9833065265c2e6d2db94b7e6fcd/lib/Pgettext/Pgettext.php#L22-L29
rnijveld/pgt
lib/Pgettext/Pgettext.php
Pgettext.msgunfmt
public static function msgunfmt($mo, $po = null) { $stringset = Mo::fromFile($mo); if ($po === null) { print Po::toString($stringset); } else { Po::toFile($stringset, $po); } }
php
public static function msgunfmt($mo, $po = null) { $stringset = Mo::fromFile($mo); if ($po === null) { print Po::toString($stringset); } else { Po::toFile($stringset, $po); } }
Reads a mo file and stores the po file. If no PO file was given, only displays what would be the result. @param string $mo Filename of the input MO file. @param string $po Filename of the output PO file. @return void
https://github.com/rnijveld/pgt/blob/9d64b4858438a9833065265c2e6d2db94b7e6fcd/lib/Pgettext/Pgettext.php#L38-L46
cmmarslender/post-iterator
includes/Cmmarslender/PostIterator/PostIterator.php
PostIterator.have_pages
public function have_pages() { $this->setup(); $offset = $this->get_query_offset(); return (bool) ( $offset < $this->total_posts ); }
php
public function have_pages() { $this->setup(); $offset = $this->get_query_offset(); return (bool) ( $offset < $this->total_posts ); }
Indicates if we have posts to process
https://github.com/cmmarslender/post-iterator/blob/5c9007614a4979183c77ea5fb009bb577d44d3a1/includes/Cmmarslender/PostIterator/PostIterator.php#L94-L100
cmmarslender/post-iterator
includes/Cmmarslender/PostIterator/PostIterator.php
PostIterator.count_posts
protected function count_posts() { global $wpdb; $query = $this->get_count_query(); $this->total_posts = $wpdb->get_var( $query ); }
php
protected function count_posts() { global $wpdb; $query = $this->get_count_query(); $this->total_posts = $wpdb->get_var( $query ); }
Counts the total number of posts that match the restrictions, not including pagination.
https://github.com/cmmarslender/post-iterator/blob/5c9007614a4979183c77ea5fb009bb577d44d3a1/includes/Cmmarslender/PostIterator/PostIterator.php#L131-L137
Elephant418/Staq
src/Staq/Core/Router/Stack/Controller.php
Controller.createView
protected function createView($action='view') { $controller = \Staq\Util::getStackSubQuery($this); $view = (new \Stack\View)->byName($action, $controller); $view['controller'] = $controller; $view['controllerAction'] = $action; return $view; }
php
protected function createView($action='view') { $controller = \Staq\Util::getStackSubQuery($this); $view = (new \Stack\View)->byName($action, $controller); $view['controller'] = $controller; $view['controllerAction'] = $action; return $view; }
/* PRIVATE METHODS ***********************************************************************
https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Core/Router/Stack/Controller.php#L44-L51
jasny/entity
src/Traits/ToAssocTrait.php
ToAssocTrait.toAssoc
public function toAssoc(): array { $assoc = object_get_properties($this, $this instanceof DynamicEntity); /** @var Event\ToAssoc $event */ $event = $this->dispatchEvent(new Event\ToAssoc($this, $assoc)); $updatedAssoc = $event->getPayload(); return $updatedAssoc; }
php
public function toAssoc(): array { $assoc = object_get_properties($this, $this instanceof DynamicEntity); /** @var Event\ToAssoc $event */ $event = $this->dispatchEvent(new Event\ToAssoc($this, $assoc)); $updatedAssoc = $event->getPayload(); return $updatedAssoc; }
Cast the entity to an associative array. @return array
https://github.com/jasny/entity/blob/5af7c94645671a3257d6565ff1891ff61fdcf69b/src/Traits/ToAssocTrait.php#L29-L38
bruno-barros/w.eloquent-framework
src/weloquent/Support/Breadcrumb.php
Breadcrumb.get
public function get() { // dump($this->getPostType()); // dump($this->getTax()); // dump($this->getTerm()); $b = []; if (!is_front_page()) { // home $b[] = [ 'title' => ($this->homeTitle) ? $this->homeTitle : get_bloginfo('name'), 'url' => get_option('home') ]; if (is_category()) { if ($c = get_category(get_query_var('cat'))) { $b[] = ['title' => $c->name, 'url' => false]; } } else if (is_post_type_archive() && !is_tax() && $this->post) { $postType = $this->post->postType; if (!in_array($postType->name, $this->excludedPostTypes)) { $b[] = ['title' => $postType->label, 'url' => null]; } } else if (is_tax()) { // if is custom post type if ($pt = get_post_type_object($this->getPostType())) { if (!in_array($pt->name, $this->excludedPostTypes)) { $b[] = ['title' => $pt->label, 'url' => get_post_type_archive_link($this->getPostType())]; } } $tax = get_term_by('slug', $this->getTerm(), get_query_var('taxonomy')); $b[] = ['title' => $tax->name, 'url' => null]; } else if (is_single()) { // if is custom post type $postType = $this->post->postType; if (!in_array($postType->name, $this->excludedPostTypes)) { $b[] = ['title' => $postType->label, 'url' => $postType->permalink]; } else if (in_array($postType->name, $this->excludedPostTypes) && $custom = $this->getOverloaded($postType->name) ) { $b[] = ['title' => $custom->labels->name, 'url' => $custom->permalink]; } if ($this->post->categories) { foreach ($this->post->categories as $c) { $b[] = ['title' => $c->name, 'url' => $c->permalink]; } } if ($tax = $this->getCurrentTaxonomy()) { $b[] = ['title' => $tax->name, 'url' => get_term_link($tax)]; } $b[] = ['title' => $this->post->title, 'url' => false]; } elseif (is_date()) { $b[] = ['title' => get_the_time($this->dateFormat), 'url' => false]; } elseif (is_page() && $this->post->post_parent) { for ($i = count($this->post->ancestors) - 1; $i >= 0; $i--) { $b[] = [ 'title' => get_the_title($this->post->ancestors[$i]), 'url' => get_permalink($this->post->ancestors[$i]) ]; } $b[] = ['title' => $this->post->title, 'url' => false]; } elseif (is_page()) { $b[] = ['title' => $this->post->title, 'url' => false]; } else if (is_tag()) { $b[] = ['title' => single_tag_title('', false), 'url' => false]; } else if (is_author()) { $b[] = ['title' => sprintf(__('Posts by %s'), get_the_author()), 'url' => false]; } else if (is_search()) { $b[] = [ 'title' => sprintf(__('Search Results %1$s %2$s'), ':', '"' . esc_html(get_search_query()) . '"'), 'url' => false ]; } elseif (is_404()) { $b[] = ['title' => __('Page not found'), 'url' => false]; } } else { $b[] = [ 'title' => ($this->homeTitle) ? $this->homeTitle : get_bloginfo('name'), 'url' => false ]; } return Collection::make($b); }
php
public function get() { // dump($this->getPostType()); // dump($this->getTax()); // dump($this->getTerm()); $b = []; if (!is_front_page()) { // home $b[] = [ 'title' => ($this->homeTitle) ? $this->homeTitle : get_bloginfo('name'), 'url' => get_option('home') ]; if (is_category()) { if ($c = get_category(get_query_var('cat'))) { $b[] = ['title' => $c->name, 'url' => false]; } } else if (is_post_type_archive() && !is_tax() && $this->post) { $postType = $this->post->postType; if (!in_array($postType->name, $this->excludedPostTypes)) { $b[] = ['title' => $postType->label, 'url' => null]; } } else if (is_tax()) { // if is custom post type if ($pt = get_post_type_object($this->getPostType())) { if (!in_array($pt->name, $this->excludedPostTypes)) { $b[] = ['title' => $pt->label, 'url' => get_post_type_archive_link($this->getPostType())]; } } $tax = get_term_by('slug', $this->getTerm(), get_query_var('taxonomy')); $b[] = ['title' => $tax->name, 'url' => null]; } else if (is_single()) { // if is custom post type $postType = $this->post->postType; if (!in_array($postType->name, $this->excludedPostTypes)) { $b[] = ['title' => $postType->label, 'url' => $postType->permalink]; } else if (in_array($postType->name, $this->excludedPostTypes) && $custom = $this->getOverloaded($postType->name) ) { $b[] = ['title' => $custom->labels->name, 'url' => $custom->permalink]; } if ($this->post->categories) { foreach ($this->post->categories as $c) { $b[] = ['title' => $c->name, 'url' => $c->permalink]; } } if ($tax = $this->getCurrentTaxonomy()) { $b[] = ['title' => $tax->name, 'url' => get_term_link($tax)]; } $b[] = ['title' => $this->post->title, 'url' => false]; } elseif (is_date()) { $b[] = ['title' => get_the_time($this->dateFormat), 'url' => false]; } elseif (is_page() && $this->post->post_parent) { for ($i = count($this->post->ancestors) - 1; $i >= 0; $i--) { $b[] = [ 'title' => get_the_title($this->post->ancestors[$i]), 'url' => get_permalink($this->post->ancestors[$i]) ]; } $b[] = ['title' => $this->post->title, 'url' => false]; } elseif (is_page()) { $b[] = ['title' => $this->post->title, 'url' => false]; } else if (is_tag()) { $b[] = ['title' => single_tag_title('', false), 'url' => false]; } else if (is_author()) { $b[] = ['title' => sprintf(__('Posts by %s'), get_the_author()), 'url' => false]; } else if (is_search()) { $b[] = [ 'title' => sprintf(__('Search Results %1$s %2$s'), ':', '"' . esc_html(get_search_query()) . '"'), 'url' => false ]; } elseif (is_404()) { $b[] = ['title' => __('Page not found'), 'url' => false]; } } else { $b[] = [ 'title' => ($this->homeTitle) ? $this->homeTitle : get_bloginfo('name'), 'url' => false ]; } return Collection::make($b); }
Return the breadcrumb as array @return Collection
https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Support/Breadcrumb.php#L79-L210