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
carlosV2/DumbsmartRepositories
src/RepositoryManager.php
RepositoryManager.getRepositoryForClassName
public function getRepositoryForClassName($className) { if (array_key_exists($className, $this->repositories)) { return $this->repositories[$className]; } throw new RepositoryNotFoundException($className); }
php
public function getRepositoryForClassName($className) { if (array_key_exists($className, $this->repositories)) { return $this->repositories[$className]; } throw new RepositoryNotFoundException($className); }
@param string $className @return Repository @throws RepositoryNotFoundException
https://github.com/carlosV2/DumbsmartRepositories/blob/4170d5e196003aa83b295c686bdce42987e22a14/src/RepositoryManager.php#L48-L55
smartboxgroup/camel-config-bundle
ProcessorDefinitions/ProcessorDefinition.php
ProcessorDefinition.buildProcessor
public function buildProcessor($configNode, $id) { $definition = $this->getBasicDefinition(); if ($configNode instanceof \SimpleXMLElement) { $attributes = $configNode->attributes(); // runtime debug breakpoint if ( isset($attributes[self::ATTRIBUTE_RUNTIME_BREAKPOINT]) && $attributes[self::ATTRIBUTE_RUNTIME_BREAKPOINT] == true && $this->debug ) { $definition->addMethodCall('setRuntimeBreakpoint', [true]); } // compile time debug breakpoint if ( isset($attributes[self::ATTRIBUTE_COMPILETIME_BREAKPOINT]) && $attributes[self::ATTRIBUTE_COMPILETIME_BREAKPOINT] == true && $this->debug ) { if (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. * * When you step out from this function you will get into the function you want to debug. * * The definition of the processor you are debugging is extending this method. * * To debug in that way you can add this to your xml flow file, as part of the processor you want to debug: * * <... compiletime-breakpoint="1"/> * */ return $definition; }
php
public function buildProcessor($configNode, $id) { $definition = $this->getBasicDefinition(); if ($configNode instanceof \SimpleXMLElement) { $attributes = $configNode->attributes(); // runtime debug breakpoint if ( isset($attributes[self::ATTRIBUTE_RUNTIME_BREAKPOINT]) && $attributes[self::ATTRIBUTE_RUNTIME_BREAKPOINT] == true && $this->debug ) { $definition->addMethodCall('setRuntimeBreakpoint', [true]); } // compile time debug breakpoint if ( isset($attributes[self::ATTRIBUTE_COMPILETIME_BREAKPOINT]) && $attributes[self::ATTRIBUTE_COMPILETIME_BREAKPOINT] == true && $this->debug ) { if (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. * * When you step out from this function you will get into the function you want to debug. * * The definition of the processor you are debugging is extending this method. * * To debug in that way you can add this to your xml flow file, as part of the processor you want to debug: * * <... compiletime-breakpoint="1"/> * */ return $definition; }
{@inheritdoc}
https://github.com/smartboxgroup/camel-config-bundle/blob/f38505c50a446707b8e8f79ecaa1addd0a6cca11/ProcessorDefinitions/ProcessorDefinition.php#L66-L111
Elephant418/Staq
src/Staq/Server.php
Server.addApplication
public function addApplication($namespace, $listeningList = NULL) { if (is_null($listeningList)) { $listeningList = $this->getDefaultBaseUri(); } $this->doFormatListeningList($listeningList); $this->applications[$namespace] = $listeningList; return $this; }
php
public function addApplication($namespace, $listeningList = NULL) { if (is_null($listeningList)) { $listeningList = $this->getDefaultBaseUri(); } $this->doFormatListeningList($listeningList); $this->applications[$namespace] = $listeningList; return $this; }
/* SETTER METHODS ***********************************************************************
https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Server.php#L33-L41
Elephant418/Staq
src/Staq/Server.php
Server.createApplication
public function createApplication($namespace = 'Staq\Core\Ground', $baseUri = NULL, $platform = NULL) { if (empty($baseUri)) { $baseUri = $this->getDefaultBaseUri(); } if (empty($platform)) { $platform = 'prod'; if (\Staq\Util::isCli()) { if (!isset($argv[1])) { echo 'You must specify a platform.' . PHP_EOL; echo 'Ex: ' . $argv[0] . ' local' . PHP_EOL; die; } $platform = $argv[1]; } } $extensions = $this->findExtensions($namespace); if (!is_null(static::$autoloader)) { spl_autoload_unregister(array(static::$autoloader, 'autoload')); } static::$autoloader = new \Staq\Autoloader($extensions); spl_autoload_register(array(static::$autoloader, 'autoload')); static::$application = new \Stack\Application($extensions, $baseUri, $platform); static::$application->initialize(); return static::$application; }
php
public function createApplication($namespace = 'Staq\Core\Ground', $baseUri = NULL, $platform = NULL) { if (empty($baseUri)) { $baseUri = $this->getDefaultBaseUri(); } if (empty($platform)) { $platform = 'prod'; if (\Staq\Util::isCli()) { if (!isset($argv[1])) { echo 'You must specify a platform.' . PHP_EOL; echo 'Ex: ' . $argv[0] . ' local' . PHP_EOL; die; } $platform = $argv[1]; } } $extensions = $this->findExtensions($namespace); if (!is_null(static::$autoloader)) { spl_autoload_unregister(array(static::$autoloader, 'autoload')); } static::$autoloader = new \Staq\Autoloader($extensions); spl_autoload_register(array(static::$autoloader, 'autoload')); static::$application = new \Stack\Application($extensions, $baseUri, $platform); static::$application->initialize(); return static::$application; }
/* PUBLIC METHODS ***********************************************************************
https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Server.php#L59-L84
Elephant418/Staq
src/Staq/Server.php
Server.getCurrentPlatform
protected function getCurrentPlatform($request, &$baseUri) { foreach ($this->platforms as $platform => $listeningList) { foreach ($listeningList as $listening) { if ($listening->match($request)) { $baseUri .= $listening->uri; \UString::doNotEndWith($baseUri, '/'); return $platform; } } } }
php
protected function getCurrentPlatform($request, &$baseUri) { foreach ($this->platforms as $platform => $listeningList) { foreach ($listeningList as $listening) { if ($listening->match($request)) { $baseUri .= $listening->uri; \UString::doNotEndWith($baseUri, '/'); return $platform; } } } }
/* APPLICATION SWITCH SETTINGS ***********************************************************************
https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Server.php#L110-L121
Elephant418/Staq
src/Staq/Server.php
Server.findExtensions
protected function findExtensions($namespace) { $this->initializeNamespaces(); $files = []; $old = []; $namespaces = [$namespace, 'Staq\Core\Ground']; while (array_diff($namespaces, $old)) { $extensions = $this->formatExtensionsFromNamespaces($namespaces); foreach ($extensions as $extension) { $files[] = $extension . '/setting/Application.ini'; } $ini = (new \Pixel418\Iniliq\IniParser)->parse(array_reverse($files)); $old = $namespaces; $namespaces = array_reverse($ini->getAsArray('extension.list')); $namespaces = \UArray::reverseMergeUnique($old, $namespaces); } return $this->formatExtensionsFromNamespaces($namespaces); }
php
protected function findExtensions($namespace) { $this->initializeNamespaces(); $files = []; $old = []; $namespaces = [$namespace, 'Staq\Core\Ground']; while (array_diff($namespaces, $old)) { $extensions = $this->formatExtensionsFromNamespaces($namespaces); foreach ($extensions as $extension) { $files[] = $extension . '/setting/Application.ini'; } $ini = (new \Pixel418\Iniliq\IniParser)->parse(array_reverse($files)); $old = $namespaces; $namespaces = array_reverse($ini->getAsArray('extension.list')); $namespaces = \UArray::reverseMergeUnique($old, $namespaces); } return $this->formatExtensionsFromNamespaces($namespaces); }
/* EXTENSIONS PARSING SETTINGS ***********************************************************************
https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Server.php#L162-L179
acacha/forge-publish
src/Console/Commands/Traits/ChecksSite.php
ChecksSite.checkSite
protected function checkSite() { $sites = $this->fetchSites(fp_env('ACACHA_FORGE_SERVER')); return in_array(fp_env('ACACHA_FORGE_SITE'), collect($sites)->pluck('id')->toArray()); }
php
protected function checkSite() { $sites = $this->fetchSites(fp_env('ACACHA_FORGE_SERVER')); return in_array(fp_env('ACACHA_FORGE_SITE'), collect($sites)->pluck('id')->toArray()); }
Check site. @return bool
https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/Traits/ChecksSite.php#L19-L23
acacha/forge-publish
src/Console/Commands/Traits/ChecksSite.php
ChecksSite.checkSiteAndAbort
protected function checkSiteAndAbort($site = null) { $site = $site ? $site : fp_env('ACACHA_FORGE_SITE'); if (! $this->checkSite($site)) { $this->error('Site ' . $site . ' not valid'); die(); } }
php
protected function checkSiteAndAbort($site = null) { $site = $site ? $site : fp_env('ACACHA_FORGE_SITE'); if (! $this->checkSite($site)) { $this->error('Site ' . $site . ' not valid'); die(); } }
Check site and abort. @param null $site
https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/Traits/ChecksSite.php#L30-L37
BenGorFile/FileBundle
src/BenGorFile/FileBundle/DependencyInjection/Compiler/RoutesPass.php
RoutesPass.process
public function process(ContainerBuilder $container) { $config = $container->getParameter('bengor_file.config'); $downloadConfiguration = []; $getFilesConfiguration = []; $getFileConfiguration = []; $uploadConfiguration = []; foreach ($config['file_class'] as $key => $file) { $downloadConfiguration[$key] = [ 'storage' => $file['storage'], 'upload_destination' => $file['upload_destination'], 'download_base_url' => $file['download_base_url'], ]; $getFilesConfiguration[$key] = array_merge( $file['use_cases']['get_files'], $file['routes']['get_files'] ); $getFileConfiguration[$key] = array_merge( $file['use_cases']['get_file'], $file['routes']['get_file'] ); $uploadConfiguration[$key] = array_merge( $file['use_cases']['upload'], $file['routes']['upload'] ); $uploadConfiguration[$key]['upload_strategy'] = $file['upload_strategy']; } (new DownloadRoutesLoaderBuilder($container, $downloadConfiguration))->build(); (new GetFilesRoutesLoaderBuilder($container, $getFilesConfiguration))->build(); (new GetFileRoutesLoaderBuilder($container, $getFileConfiguration))->build(); (new UploadRoutesLoaderBuilder($container, $uploadConfiguration))->build(); }
php
public function process(ContainerBuilder $container) { $config = $container->getParameter('bengor_file.config'); $downloadConfiguration = []; $getFilesConfiguration = []; $getFileConfiguration = []; $uploadConfiguration = []; foreach ($config['file_class'] as $key => $file) { $downloadConfiguration[$key] = [ 'storage' => $file['storage'], 'upload_destination' => $file['upload_destination'], 'download_base_url' => $file['download_base_url'], ]; $getFilesConfiguration[$key] = array_merge( $file['use_cases']['get_files'], $file['routes']['get_files'] ); $getFileConfiguration[$key] = array_merge( $file['use_cases']['get_file'], $file['routes']['get_file'] ); $uploadConfiguration[$key] = array_merge( $file['use_cases']['upload'], $file['routes']['upload'] ); $uploadConfiguration[$key]['upload_strategy'] = $file['upload_strategy']; } (new DownloadRoutesLoaderBuilder($container, $downloadConfiguration))->build(); (new GetFilesRoutesLoaderBuilder($container, $getFilesConfiguration))->build(); (new GetFileRoutesLoaderBuilder($container, $getFileConfiguration))->build(); (new UploadRoutesLoaderBuilder($container, $uploadConfiguration))->build(); }
{@inheritdoc}
https://github.com/BenGorFile/FileBundle/blob/82c1fa952e7e7b7a188141a34053ab612b699a21/src/BenGorFile/FileBundle/DependencyInjection/Compiler/RoutesPass.php#L34-L68
gluephp/glue
src/Router/Router.php
Router.resolveErrorHandler
public function resolveErrorHandler($errorCode) { return array_key_exists($errorCode, $this->errorHandlers) ? call_user_func_array($this->errorHandlers[$errorCode], []) : ''; }
php
public function resolveErrorHandler($errorCode) { return array_key_exists($errorCode, $this->errorHandlers) ? call_user_func_array($this->errorHandlers[$errorCode], []) : ''; }
Resolve an error handler @return [type] [description]
https://github.com/gluephp/glue/blob/d54e0905dfe74d1c114c04f33fa89a60e2651562/src/Router/Router.php#L42-L47
gluephp/glue
src/Router/Router.php
Router.route
public function route($name, array $args = null, $noInitialSlash = false) { $route = ltrim(parent::route($name, $args), '/'); return $noInitialSlash ? $route : '/' . $route; }
php
public function route($name, array $args = null, $noInitialSlash = false) { $route = ltrim(parent::route($name, $args), '/'); return $noInitialSlash ? $route : '/' . $route; }
Resolve a named route @param $name @param array $args @param boolean $noInitialSlash @return string
https://github.com/gluephp/glue/blob/d54e0905dfe74d1c114c04f33fa89a60e2651562/src/Router/Router.php#L58-L65
x2ts/x2ts
src/db/orm/Model.php
Model.getInstance
public static function getInstance(array $args, array $conf, string $confHash) { @list($modelName) = $args; $namespace = $conf['namespace'] ?? static::$_conf['namespace']; $className = "\\{$namespace}\\" . Toolkit::toCamelCase($modelName, true); /** @var Model $model */ $model = class_exists($className) ? new $className($modelName) : new Model($modelName); $model->saveConf($conf, $confHash); $model->init(); return $model; }
php
public static function getInstance(array $args, array $conf, string $confHash) { @list($modelName) = $args; $namespace = $conf['namespace'] ?? static::$_conf['namespace']; $className = "\\{$namespace}\\" . Toolkit::toCamelCase($modelName, true); /** @var Model $model */ $model = class_exists($className) ? new $className($modelName) : new Model($modelName); $model->saveConf($conf, $confHash); $model->init(); return $model; }
@param array $args @param array $conf @param string $confHash @return Model
https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/db/orm/Model.php#L124-L134
x2ts/x2ts
src/db/orm/Model.php
Model.save
public function save(int $scenario = Model::INSERT_NORMAL) { $this->modelManager->save($scenario); return $this; }
php
public function save(int $scenario = Model::INSERT_NORMAL) { $this->modelManager->save($scenario); return $this; }
@param int $scenario [optional] @return $this
https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/db/orm/Model.php#L163-L166
x2ts/x2ts
src/db/orm/Model.php
Model.many
public function many(string $condition = '', array $params = array(), $offset = null, $limit = null) { return $this->loadWiths($this->modelManager->many($condition, $params, $offset, $limit)); }
php
public function many(string $condition = '', array $params = array(), $offset = null, $limit = null) { return $this->loadWiths($this->modelManager->many($condition, $params, $offset, $limit)); }
@noinspection MoreThanThreeArgumentsInspection @param string $condition @param array $params @param int $offset @param int $limit @return array
https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/db/orm/Model.php#L273-L275
x2ts/x2ts
src/db/orm/Model.php
Model.loadWiths
protected function loadWiths(array $models) { if ($models && $this->_with) { foreach ($this->_with as $w) { /** @var BatchLoader $loader */ $loader = $w['loader']; $subWith = $w['with']; $loader->batchLoadFor($models, $subWith); } $this->_with = []; } return $models; }
php
protected function loadWiths(array $models) { if ($models && $this->_with) { foreach ($this->_with as $w) { /** @var BatchLoader $loader */ $loader = $w['loader']; $subWith = $w['with']; $loader->batchLoadFor($models, $subWith); } $this->_with = []; } return $models; }
@param array $models @return array
https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/db/orm/Model.php#L282-L293
x2ts/x2ts
src/db/orm/Model.php
Model.sql
public function sql(string $sql, array $params = []) { return $this->loadWiths($this->modelManager->sql($sql, $params)); }
php
public function sql(string $sql, array $params = []) { return $this->loadWiths($this->modelManager->sql($sql, $params)); }
@param string $sql @param array $params @return array @throws \x2ts\db\DataBaseException
https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/db/orm/Model.php#L312-L314
x2ts/x2ts
src/db/orm/Model.php
Model.setupOne
protected function setupOne(array $properties) { $pkName = $this->pkName; /** @var Column $column */ foreach ($this->tableSchema->columns as $column) { if (!array_key_exists($column->name, $properties)) { continue; } if (null !== $properties[$column->name]) { if ($column->isInt()) { $this->_properties[$column->name] = (int) $properties[$column->name]; } else if ($column->isFloat()) { $this->_properties[$column->name] = (float) $properties[$column->name]; } else { $this->_properties[$column->name] = $properties[$column->name]; } } else { $this->_properties[$column->name] = null; } } $this->_modified = array(); $this->_oldPK = $this->_properties[$pkName] ?? null; return $this; }
php
protected function setupOne(array $properties) { $pkName = $this->pkName; /** @var Column $column */ foreach ($this->tableSchema->columns as $column) { if (!array_key_exists($column->name, $properties)) { continue; } if (null !== $properties[$column->name]) { if ($column->isInt()) { $this->_properties[$column->name] = (int) $properties[$column->name]; } else if ($column->isFloat()) { $this->_properties[$column->name] = (float) $properties[$column->name]; } else { $this->_properties[$column->name] = $properties[$column->name]; } } else { $this->_properties[$column->name] = null; } } $this->_modified = array(); $this->_oldPK = $this->_properties[$pkName] ?? null; return $this; }
@param array $properties @return $this
https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/db/orm/Model.php#L321-L347
x2ts/x2ts
src/db/orm/Model.php
Model.setup
public function setup(array $properties) { if (is_array(reset($properties))) { $modelList = array(); foreach ($properties as $p) { $o = clone $this; $o->setupOne($p); $modelList[] = $o; } return $modelList; } return $this->setupOne($properties); }
php
public function setup(array $properties) { if (is_array(reset($properties))) { $modelList = array(); foreach ($properties as $p) { $o = clone $this; $o->setupOne($p); $modelList[] = $o; } return $modelList; } return $this->setupOne($properties); }
@param array $properties @return Model[]|Model
https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/db/orm/Model.php#L361-L373
x2ts/x2ts
src/db/orm/Model.php
Model.loadRelationObj
protected function loadRelationObj( string $name, string $condition = '', array $params = [], int $offset = 0, int $limit = 200 ) { X::logger()->trace("Loading relation $name"); if (array_key_exists($name, $this->relations)) { $relation = $this->relations[$name]; return $relation->fetchRelated($this, $condition, $params, $offset, $limit); } return null; }
php
protected function loadRelationObj( string $name, string $condition = '', array $params = [], int $offset = 0, int $limit = 200 ) { X::logger()->trace("Loading relation $name"); if (array_key_exists($name, $this->relations)) { $relation = $this->relations[$name]; return $relation->fetchRelated($this, $condition, $params, $offset, $limit); } return null; }
@noinspection MoreThanThreeArgumentsInspection @param $name @param string $condition @param array $params @param int $offset @param int $limit @return Model|array|null
https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/db/orm/Model.php#L561-L574
x2ts/x2ts
src/db/orm/Model.php
Model.assign
public function assign($props) { if (!is_array($props) && !$props instanceof \Traversable) { throw new TypeError('Argument 1 passed to ' . __METHOD__ . ' must be an instance of iterable, ' . gettype($props) . ' given'); } if ($this->isNewRecord && !empty($props[$this->pkName])) { $this->load($props[$this->pkName]); } foreach ($props as $key => $value) { $this->$key = $value; } return $this; }
php
public function assign($props) { if (!is_array($props) && !$props instanceof \Traversable) { throw new TypeError('Argument 1 passed to ' . __METHOD__ . ' must be an instance of iterable, ' . gettype($props) . ' given'); } if ($this->isNewRecord && !empty($props[$this->pkName])) { $this->load($props[$this->pkName]); } foreach ($props as $key => $value) { $this->$key = $value; } return $this; }
@param array|\Traversable $props @return $this @throws TypeError
https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/db/orm/Model.php#L656-L670
x2ts/x2ts
src/db/orm/Model.php
Model._propertySet
protected function _propertySet($name, $value) { if (array_key_exists($name, $this->_properties)) { if ($this->_properties[$name] !== $value) { $this->_properties[$name] = $value; $this->_modified[$name] = $value; return 1; } return 0; } return false; }
php
protected function _propertySet($name, $value) { if (array_key_exists($name, $this->_properties)) { if ($this->_properties[$name] !== $value) { $this->_properties[$name] = $value; $this->_modified[$name] = $value; return 1; } return 0; } return false; }
@param string $name The name of the property to be set @param mixed $value The value of the property @return int|bool Returns the number of changed properties, or false if $name is invalid
https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/db/orm/Model.php#L679-L689
x2ts/x2ts
src/db/orm/Model.php
Model.jsonSerialize
public function jsonSerialize() { $jsonArray = array(); foreach ($this as $key => $value) { $jsonArray[$key] = $value; } return $jsonArray; }
php
public function jsonSerialize() { $jsonArray = array(); foreach ($this as $key => $value) { $jsonArray[$key] = $value; } return $jsonArray; }
(PHP 5 &gt;= 5.4.0)<br/> Specify data which should be serialized to JSON @link http://php.net/manual/en/jsonserializable.jsonserialize.php @return mixed data which can be serialized by <b>json_encode</b>, which is a value of any type other than a resource.
https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/db/orm/Model.php#L733-L739
Synapse-Cmf/synapse-cmf
src/Synapse/Cmf/Framework/Theme/Zone/Repository/Doctrine/DoctrineRepository.php
DoctrineRepository.onCreateZone
public function onCreateZone(ZoneEvent $event) { $zone = $event->getZone(); if ($zone->getComponents()->isEmpty()) { return; } $this->save($zone); }
php
public function onCreateZone(ZoneEvent $event) { $zone = $event->getZone(); if ($zone->getComponents()->isEmpty()) { return; } $this->save($zone); }
Zone creation event handler. Triggers persistence call only if component was defined into it. @param ZoneEvent $event
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Framework/Theme/Zone/Repository/Doctrine/DoctrineRepository.php#L38-L46
amarcinkowski/hospitalplugin
src/WP/ScriptsAndStyles.php
ScriptsAndStyles.init
public function init($path, $pages, $scripts, $styles, $type = 'admin') { if ($type == 'admin') { $action = 'admin_enqueue_scripts'; } else { $action = 'wp_enqueue_scripts'; } $this->path = $path; $this->pages = $pages; $this->scripts = $scripts; $this->styles = $styles; add_action($action, array( $this, 'hospitalPluginStyles' )); add_action($action, array( $this, 'hospitalPluginScripts' )); add_action($action, array( $this, 'removeCustomScripts' )); }
php
public function init($path, $pages, $scripts, $styles, $type = 'admin') { if ($type == 'admin') { $action = 'admin_enqueue_scripts'; } else { $action = 'wp_enqueue_scripts'; } $this->path = $path; $this->pages = $pages; $this->scripts = $scripts; $this->styles = $styles; add_action($action, array( $this, 'hospitalPluginStyles' )); add_action($action, array( $this, 'hospitalPluginScripts' )); add_action($action, array( $this, 'removeCustomScripts' )); }
init
https://github.com/amarcinkowski/hospitalplugin/blob/acdc2be5157abfbdcafb4dcf6c6ba505e291263f/src/WP/ScriptsAndStyles.php#L53-L76
amarcinkowski/hospitalplugin
src/WP/ScriptsAndStyles.php
ScriptsAndStyles.hospitalRegisterScript
public function hospitalRegisterScript($file, $required = null, $hook = null) { wp_enqueue_script('hospital_admin_script' . $file, $this->path . '/js/' . $file, $required); }
php
public function hospitalRegisterScript($file, $required = null, $hook = null) { wp_enqueue_script('hospital_admin_script' . $file, $this->path . '/js/' . $file, $required); }
hospitalRegisterScript @param unknown $file @param unknown $required
https://github.com/amarcinkowski/hospitalplugin/blob/acdc2be5157abfbdcafb4dcf6c6ba505e291263f/src/WP/ScriptsAndStyles.php#L93-L96
amarcinkowski/hospitalplugin
src/WP/ScriptsAndStyles.php
ScriptsAndStyles.hospitalLocalizeScript
public function hospitalLocalizeScript($file, $data) { $json_dates = json_encode($data); $params = array( 'my_arr' => $json_dates ); wp_localize_script('hospital_admin_script' . $file, 'php_params', $params); }
php
public function hospitalLocalizeScript($file, $data) { $json_dates = json_encode($data); $params = array( 'my_arr' => $json_dates ); wp_localize_script('hospital_admin_script' . $file, 'php_params', $params); }
hospitalLocalizeScript @param unknown $file @param unknown $data
https://github.com/amarcinkowski/hospitalplugin/blob/acdc2be5157abfbdcafb4dcf6c6ba505e291263f/src/WP/ScriptsAndStyles.php#L103-L110
amarcinkowski/hospitalplugin
src/WP/ScriptsAndStyles.php
ScriptsAndStyles.hospitalPluginStyles
public function hospitalPluginStyles($hook) { if (in_array($hook, $this->pages)) { foreach ($this->styles as $style) { self::hospitalRegisterStyle($style); } } }
php
public function hospitalPluginStyles($hook) { if (in_array($hook, $this->pages)) { foreach ($this->styles as $style) { self::hospitalRegisterStyle($style); } } }
hospitalPluginStyles
https://github.com/amarcinkowski/hospitalplugin/blob/acdc2be5157abfbdcafb4dcf6c6ba505e291263f/src/WP/ScriptsAndStyles.php#L115-L122
amarcinkowski/hospitalplugin
src/WP/ScriptsAndStyles.php
ScriptsAndStyles.hospitalPluginScripts
public function hospitalPluginScripts($hook) { $jQ = array( 'jquery' ); if (in_array($hook, $this->pages)) { foreach ($this->scripts as $script) { self::hospitalRegisterScript($script, $jQ, $hook); } } }
php
public function hospitalPluginScripts($hook) { $jQ = array( 'jquery' ); if (in_array($hook, $this->pages)) { foreach ($this->scripts as $script) { self::hospitalRegisterScript($script, $jQ, $hook); } } }
hospitalPluginScripts @param string $hook hook to the page
https://github.com/amarcinkowski/hospitalplugin/blob/acdc2be5157abfbdcafb4dcf6c6ba505e291263f/src/WP/ScriptsAndStyles.php#L128-L138
phpui/hom-php
src/HOM/Container.php
Container.setItem
public function setItem($item, $index = null): ContainerInterface { if (is_null($index)) { $this->items[] = $item; } else { $this->items[$index] = $item; } return $this; }
php
public function setItem($item, $index = null): ContainerInterface { if (is_null($index)) { $this->items[] = $item; } else { $this->items[$index] = $item; } return $this; }
Set an item into children list. @param mixed $item @param mixed $index Optional. @return \HOM\ContainerInterface
https://github.com/phpui/hom-php/blob/c4eccd3e64cf8c7b5ff663f9fea3f31579e17006/src/HOM/Container.php#L54-L62
phpui/hom-php
src/HOM/Container.php
Container.removeItemByIndex
public function removeItemByIndex($index): ContainerInterface { if ($this->hasItem($index)) { $this->items[$index] = null; //prevente unset item. unset($this->items[$index]); //unset only index, not the item. } return $this; }
php
public function removeItemByIndex($index): ContainerInterface { if ($this->hasItem($index)) { $this->items[$index] = null; //prevente unset item. unset($this->items[$index]); //unset only index, not the item. } return $this; }
Removes the child from the children list for the given index. @param mixed $index @return \HOM\ContainerInterface
https://github.com/phpui/hom-php/blob/c4eccd3e64cf8c7b5ff663f9fea3f31579e17006/src/HOM/Container.php#L127-L135
phpui/hom-php
src/HOM/Container.php
Container.getItemsCode
protected function getItemsCode(): string { $code = ''; if ($this->countItems() > 0) { foreach ($this->getAllItems() as $item) { if (is_string($item)) { $code .= $item; } else { $code .= (string) $item; } } } return $code; }
php
protected function getItemsCode(): string { $code = ''; if ($this->countItems() > 0) { foreach ($this->getAllItems() as $item) { if (is_string($item)) { $code .= $item; } else { $code .= (string) $item; } } } return $code; }
Get html code for children. @return string
https://github.com/phpui/hom-php/blob/c4eccd3e64cf8c7b5ff663f9fea3f31579e17006/src/HOM/Container.php#L142-L155
Etenil/assegai
src/assegai/Controller.php
Controller.helper
function helper($helper_name) { if(array_key_exists($helper_name, $this->helpers)) { return $this->helpers[$helper_name]; } else { $classname = 'Helper_' . ucwords($helper_name); return new $classname($this->modules, $this->server, $this->request, $this->security); } }
php
function helper($helper_name) { if(array_key_exists($helper_name, $this->helpers)) { return $this->helpers[$helper_name]; } else { $classname = 'Helper_' . ucwords($helper_name); return new $classname($this->modules, $this->server, $this->request, $this->security); } }
Instanciates a helper.
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/Controller.php#L147-L155
Etenil/assegai
src/assegai/Controller.php
Controller.view
function view($view_name, array $var_list = NULL, array $block_list = NULL) { if($var_list === NULL) { $var_list = array(); // Avoids notices. } $vars = (object)$var_list; $blocks = (object)$block_list; if($hook_data = $this->modules->preView($this->request, $view_name, $vars)) { return $hook_data; } $serv = $this->server; $me = $this; $parent_tpl = false; $current_block = false; $helpers = new \stdClass(); // Little hack to access urls easier. $url = function($url) use($serv) { return $serv->siteUrl($url); }; $load_helper = function($helper_name) use(&$helpers, &$me) { $helpers->{$helper_name} = $me->helper($helper_name); }; $startblock = function($name) use(&$current_block) { $current_block = $name; ob_start(); }; $endblock = function() use(&$block_list, &$current_block) { $block_list[$current_block] = ob_get_clean(); $current_block = false; }; $inherit = function($template) use(&$parent_tpl) { $parent_tpl = $template; }; $clean = function($val, $placeholder='-') { return \assegai\Utils::cleanFilename($val, $placeholder); }; $template_path = false; // Shorthands $h = &$helpers; ob_start(); $template_path = $this->server->getRelAppPath('views/' . $view_name . '.phtml'); if(!file_exists($template_path)) { $template_path = $this->server->main->get('templates_path') . '/' . $view_name . '.phtml'; } // Traditional PHP template. require($template_path); $data = ob_get_clean(); if($hook_data = $this->modules->postView($this->request, $view_name, $vars, $data)) { return $hook_data; } if($parent_tpl) { return $this->view($parent_tpl, $var_list, $block_list); } return $data; }
php
function view($view_name, array $var_list = NULL, array $block_list = NULL) { if($var_list === NULL) { $var_list = array(); // Avoids notices. } $vars = (object)$var_list; $blocks = (object)$block_list; if($hook_data = $this->modules->preView($this->request, $view_name, $vars)) { return $hook_data; } $serv = $this->server; $me = $this; $parent_tpl = false; $current_block = false; $helpers = new \stdClass(); // Little hack to access urls easier. $url = function($url) use($serv) { return $serv->siteUrl($url); }; $load_helper = function($helper_name) use(&$helpers, &$me) { $helpers->{$helper_name} = $me->helper($helper_name); }; $startblock = function($name) use(&$current_block) { $current_block = $name; ob_start(); }; $endblock = function() use(&$block_list, &$current_block) { $block_list[$current_block] = ob_get_clean(); $current_block = false; }; $inherit = function($template) use(&$parent_tpl) { $parent_tpl = $template; }; $clean = function($val, $placeholder='-') { return \assegai\Utils::cleanFilename($val, $placeholder); }; $template_path = false; // Shorthands $h = &$helpers; ob_start(); $template_path = $this->server->getRelAppPath('views/' . $view_name . '.phtml'); if(!file_exists($template_path)) { $template_path = $this->server->main->get('templates_path') . '/' . $view_name . '.phtml'; } // Traditional PHP template. require($template_path); $data = ob_get_clean(); if($hook_data = $this->modules->postView($this->request, $view_name, $vars, $data)) { return $hook_data; } if($parent_tpl) { return $this->view($parent_tpl, $var_list, $block_list); } return $data; }
Loads a view.
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/Controller.php#L160-L231
Etenil/assegai
src/assegai/Controller.php
Controller.model
protected function model($model_name) { if(stripos($model_name, 'model') === false) { $model_name = sprintf('%s\models\%s', $this->server->getAppName(), $model_name); } if($hook_data = $this->modules->preModel($model_name)) { return $hook_data; } if(!class_exists($model_name)) { throw new exceptions\HttpInternalServerError("Class $model_name not found"); } $model = new $model_name($this->modules); if($hook_data = $this->modules->postModel($model_name) === true) { return $hook_data; } return $model; }
php
protected function model($model_name) { if(stripos($model_name, 'model') === false) { $model_name = sprintf('%s\models\%s', $this->server->getAppName(), $model_name); } if($hook_data = $this->modules->preModel($model_name)) { return $hook_data; } if(!class_exists($model_name)) { throw new exceptions\HttpInternalServerError("Class $model_name not found"); } $model = new $model_name($this->modules); if($hook_data = $this->modules->postModel($model_name) === true) { return $hook_data; } return $model; }
Loads a model.
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/Controller.php#L236-L257
Etenil/assegai
src/assegai/Controller.php
Controller.dump
protected function dump($var, $no_html = false) { $dump = var_export($var, true); if($no_html) { return $dump; } else { return '<pre>' . htmlentities($dump) . '</pre>' . PHP_EOL;; } }
php
protected function dump($var, $no_html = false) { $dump = var_export($var, true); if($no_html) { return $dump; } else { return '<pre>' . htmlentities($dump) . '</pre>' . PHP_EOL;; } }
Tiny wrapper arround var_dump to ease debugging. @param mixed $var is the variable to be dumped @param boolean $no_html defines whether the variable contains messy HTML characters or not. The given $var will be escaped if set to false. Default is false. @return The HTML code of a human representation of the $var.
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/Controller.php#L277-L285
Etenil/assegai
src/assegai/Controller.php
Controller.checkCsrf
protected final function checkCsrf() { $valid = false; $r = $this->request; if($r->getSession('assegai_csrf_token') && $r->post('csrf') && $r->getSession('assegai_csrf_token') == $r->post('csrf')) { $valid = true; } $this->request->killSession('assegai_csrf_token'); return $valid; }
php
protected final function checkCsrf() { $valid = false; $r = $this->request; if($r->getSession('assegai_csrf_token') && $r->post('csrf') && $r->getSession('assegai_csrf_token') == $r->post('csrf')) { $valid = true; } $this->request->killSession('assegai_csrf_token'); return $valid; }
Checks the validity of the CSRF token.
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/Controller.php#L319-L333
dave-redfern/laravel-doctrine-entity-validation
src/Commands/GenerateHydrators.php
GenerateHydrators.handle
public function handle() { $path = storage_path($this->config->get('doctrine_hydrators.cache_path', 'cache/hydrators')); if (!file_exists($path)) { mkdir($path, 0755, true); } array_map('unlink', glob("$path/*") ?: []); foreach ($this->config->get('doctrine_hydrators.entities', []) as $class) { $this->output->writeln("Processing hydrator for <info>{$class}</info>"); $config = new Configuration($class); $config->setGeneratedClassesTargetDir($path); $config->setAutoGenerateProxies(true); $config->createFactory()->getHydratorClass(); } $this->output->writeln("Hydrator classes generated to <info>$path</info>"); }
php
public function handle() { $path = storage_path($this->config->get('doctrine_hydrators.cache_path', 'cache/hydrators')); if (!file_exists($path)) { mkdir($path, 0755, true); } array_map('unlink', glob("$path/*") ?: []); foreach ($this->config->get('doctrine_hydrators.entities', []) as $class) { $this->output->writeln("Processing hydrator for <info>{$class}</info>"); $config = new Configuration($class); $config->setGeneratedClassesTargetDir($path); $config->setAutoGenerateProxies(true); $config->createFactory()->getHydratorClass(); } $this->output->writeln("Hydrator classes generated to <info>$path</info>"); }
Execute the console command. @return mixed
https://github.com/dave-redfern/laravel-doctrine-entity-validation/blob/e8cb491545514f65536697e870f079d6b731c4b3/src/Commands/GenerateHydrators.php#L73-L92
headzoo/web-tools
src/Headzoo/Web/Tools/Builders/Headers.php
Headers.build
public function build(array $headers) { if (count($headers) > self::MAX_HEADERS) { throw new Exceptions\BuildException( sprintf( "Number of header fields exceeds the %d max number.", self::MAX_HEADERS ) ); } $headers = self::normalize($headers); return join(self::NEWLINE, $headers) . self::NEWLINE; }
php
public function build(array $headers) { if (count($headers) > self::MAX_HEADERS) { throw new Exceptions\BuildException( sprintf( "Number of header fields exceeds the %d max number.", self::MAX_HEADERS ) ); } $headers = self::normalize($headers); return join(self::NEWLINE, $headers) . self::NEWLINE; }
{@inheritDoc}
https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/Builders/Headers.php#L54-L67
headzoo/web-tools
src/Headzoo/Web/Tools/Builders/Headers.php
Headers.normalize
public function normalize(array $headers) { $raw = []; foreach($headers as $name => $value) { if (is_int($name)) { list($name, $value) = explode(":", $value, 2); } $name = Utils::normalizeHeaderName($name, $this->stripX); $value = trim($value); $raw[] = "{$name}: {$value}"; } return $raw; }
php
public function normalize(array $headers) { $raw = []; foreach($headers as $name => $value) { if (is_int($name)) { list($name, $value) = explode(":", $value, 2); } $name = Utils::normalizeHeaderName($name, $this->stripX); $value = trim($value); $raw[] = "{$name}: {$value}"; } return $raw; }
{@inheritDoc}
https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/Builders/Headers.php#L72-L86
objective-php/events-handler
src/EventsHandlerAwareTrait.php
EventsHandlerAwareTrait.trigger
public function trigger($eventName, $origin = null, $context = [], EventInterface $event = null) { if ($eventsHandler = $this->getEventsHandler()) { $eventsHandler->trigger($eventName, $origin, $context, $event); } }
php
public function trigger($eventName, $origin = null, $context = [], EventInterface $event = null) { if ($eventsHandler = $this->getEventsHandler()) { $eventsHandler->trigger($eventName, $origin, $context, $event); } }
Proxy trigger method @param string $eventName @param mixed $origin @param array $context @param EventInterface|null $event
https://github.com/objective-php/events-handler/blob/2e8fb6c5649bb1cc22ae4541ea0467031b4505ed/src/EventsHandlerAwareTrait.php#L49-L54
objective-php/events-handler
src/EventsHandlerAwareTrait.php
EventsHandlerAwareTrait.bind
public function bind($eventName, $callback, $mode = EventsHandlerInterface::BINDING_MODE_LAST) { if ($eventsHandler = $this->getEventsHandler()) { $eventsHandler->bind($eventName, $callback, $mode); } }
php
public function bind($eventName, $callback, $mode = EventsHandlerInterface::BINDING_MODE_LAST) { if ($eventsHandler = $this->getEventsHandler()) { $eventsHandler->bind($eventName, $callback, $mode); } }
Proxy bind method @param string $eventName @param string $callback @param string $mode
https://github.com/objective-php/events-handler/blob/2e8fb6c5649bb1cc22ae4541ea0467031b4505ed/src/EventsHandlerAwareTrait.php#L63-L68
pmdevelopment/tool-bundle
Services/Google/ReCaptchaService.php
ReCaptchaService.isValid
public function isValid($secret, Request $request) { $captcha = $request->get('g-recaptcha-response'); if(null === $captcha || true === empty($captcha)){ return false; } $guzzle = $this->getClient(); $result = $guzzle->request(Request::METHOD_POST, self::URI_VERIFY_V2, [ 'form_params' => [ 'secret' => $secret, 'response' => $captcha, 'remoteip' => $request->getClientIp(), ] ]); $bodyContents = $result->getBody()->getContents(); if (true === empty($bodyContents)) { return false; } $jsonContents = json_decode($bodyContents, true); if (false === isset($jsonContents['success']) || true !== $jsonContents['success']) { return false; } return true; }
php
public function isValid($secret, Request $request) { $captcha = $request->get('g-recaptcha-response'); if(null === $captcha || true === empty($captcha)){ return false; } $guzzle = $this->getClient(); $result = $guzzle->request(Request::METHOD_POST, self::URI_VERIFY_V2, [ 'form_params' => [ 'secret' => $secret, 'response' => $captcha, 'remoteip' => $request->getClientIp(), ] ]); $bodyContents = $result->getBody()->getContents(); if (true === empty($bodyContents)) { return false; } $jsonContents = json_decode($bodyContents, true); if (false === isset($jsonContents['success']) || true !== $jsonContents['success']) { return false; } return true; }
Is Valid @param string $secret @param Request $request @return bool
https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Services/Google/ReCaptchaService.php#L33-L61
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Observer.php
Radial_Core_Model_Observer.processExchangePlatformOrder
public function processExchangePlatformOrder(Varien_Event_Observer $observer) { $order = $observer->getEvent()->getOrder(); $quote = $order->getQuote(); Mage::dispatchEvent('ebayenterprise_giftcard_redeem', array('quote' => $quote, 'order' => $order)); return $this; }
php
public function processExchangePlatformOrder(Varien_Event_Observer $observer) { $order = $observer->getEvent()->getOrder(); $quote = $order->getQuote(); Mage::dispatchEvent('ebayenterprise_giftcard_redeem', array('quote' => $quote, 'order' => $order)); return $this; }
Perform all processing necessary for the order to be placed with the Exchange Platform - allocate inventory, redeem SVC. If any of the observers need to indicate that an order should not be created, the observer method should throw an exception. Observers the 'sales_order_place_before' event. @see Mage_Sales_Model_Order::place @param Varien_Event_Observer $observer contains the order being placed which will have a reference to the quote the order was created for @throws EbayEnterprise_Eb2cInventory_Model_Allocation_Exception @throws Exception @return self
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Observer.php#L91-L97
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Observer.php
Radial_Core_Model_Observer.rollbackExchangePlatformOrder
public function rollbackExchangePlatformOrder(Varien_Event_Observer $observer) { Mage::helper('ebayenterprise_magelog')->debug(__METHOD__); Mage::dispatchEvent('eb2c_order_creation_failure', array( 'quote' => $observer->getEvent()->getQuote(), 'order' => $observer->getEvent()->getOrder() )); return $this; }
php
public function rollbackExchangePlatformOrder(Varien_Event_Observer $observer) { Mage::helper('ebayenterprise_magelog')->debug(__METHOD__); Mage::dispatchEvent('eb2c_order_creation_failure', array( 'quote' => $observer->getEvent()->getQuote(), 'order' => $observer->getEvent()->getOrder() )); return $this; }
Roll back any Exchange Platform actions made for the order - rollback allocation, void SVC redemptions, void payment auths. Observes the 'sales_model_service_quote_submit_failure' event. @see Mage_Sales_Model_Service_Quote::submitOrder @param Varien_Event_Observer $observer Contains the failed order as well as the quote the order was created for @return self
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Observer.php#L106-L114
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Observer.php
Radial_Core_Model_Observer.handleShipGroupChargeType
public function handleShipGroupChargeType(Varien_Event_Observer $observer) { $event = $observer->getEvent(); $shipGroup = $event->getShipGroupPayload(); Mage::helper('radial_core/shipping_chargetype')->setShippingChargeType($shipGroup); return $this; }
php
public function handleShipGroupChargeType(Varien_Event_Observer $observer) { $event = $observer->getEvent(); $shipGroup = $event->getShipGroupPayload(); Mage::helper('radial_core/shipping_chargetype')->setShippingChargeType($shipGroup); return $this; }
respond to the order create's request for a valid ship group charge type @param Varien_Event_Observer $observer @return self
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Observer.php#L135-L141
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Observer.php
Radial_Core_Model_Observer.handleSalesQuoteCollectTotalsAfter
public function handleSalesQuoteCollectTotalsAfter(Varien_Event_Observer $observer) { $event = $observer->getEvent(); /** @var Mage_Sales_Model_Quote $quote */ $quote = $event->getQuote(); /** @var Mage_Sales_Model_Resource_Quote_Address_Collection */ $addresses = $quote->getAddressesCollection(); foreach ($addresses as $address) { $appliedRuleIds = $address->getAppliedRuleIds(); if (is_array($appliedRuleIds)) { $appliedRuleIds = implode(',', $appliedRuleIds); } $data = (array) $address->getEbayEnterpriseOrderDiscountData(); $data[$appliedRuleIds] = [ 'id' => $appliedRuleIds, 'amount' => $address->getBaseShippingDiscountAmount(), 'description' => $this->helper->__('Shipping Discount'), ]; $address->setEbayEnterpriseOrderDiscountData($data); } }
php
public function handleSalesQuoteCollectTotalsAfter(Varien_Event_Observer $observer) { $event = $observer->getEvent(); /** @var Mage_Sales_Model_Quote $quote */ $quote = $event->getQuote(); /** @var Mage_Sales_Model_Resource_Quote_Address_Collection */ $addresses = $quote->getAddressesCollection(); foreach ($addresses as $address) { $appliedRuleIds = $address->getAppliedRuleIds(); if (is_array($appliedRuleIds)) { $appliedRuleIds = implode(',', $appliedRuleIds); } $data = (array) $address->getEbayEnterpriseOrderDiscountData(); $data[$appliedRuleIds] = [ 'id' => $appliedRuleIds, 'amount' => $address->getBaseShippingDiscountAmount(), 'description' => $this->helper->__('Shipping Discount'), ]; $address->setEbayEnterpriseOrderDiscountData($data); } }
Account for shipping discounts not attached to an item. Combine all shipping discounts into one. @see self::handleSalesConvertQuoteAddressToOrderAddress @see Mage_SalesRule_Model_Validator::processShippingAmount @param Varien_Event_Observer @return void
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Observer.php#L152-L172
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Observer.php
Radial_Core_Model_Observer.handleSalesRuleValidatorProcess
public function handleSalesRuleValidatorProcess(Varien_Event_Observer $observer) { /** @var Varien_Event $event */ $event = $observer->getEvent(); /** @var Mage_SalesRule_Model_Rule $rule */ $rule = $event->getRule(); /** @var Mage_Sales_Model_Quote $quote */ $quote = $event->getQuote(); /** @var Mage_Core_Model_Store $store */ $store = $quote->getStore(); /** @var Mage_Sales_Model_Quote_Item $item */ $item = $event->getItem(); /** @var Varien_Object */ $result = $event->getResult(); $data = (array) $item->getEbayEnterpriseOrderDiscountData(); $ruleId = $rule->getId(); // Use the rule id to prevent duplicates. $data[$ruleId] = [ 'amount' => $this->calculateDiscountAmount($item, $result, $data), 'applied_count' => $event->getQty(), 'code' => $this->helper->getQuoteCouponCode($quote, $rule), 'description' => $rule->getStoreLabel($store) ?: $rule->getName(), 'effect_type' => $rule->getSimpleAction(), 'id' => $ruleId, ]; if( $item instanceof Mage_Sales_Model_Quote_Address_Item ) { $item->setEbayEnterpriseOrderDiscountData($data); foreach( $quote->getAllItems() as $quoteItem ) { if( $quoteItem->getId() === $item->getQuoteItemId()) { $quoteItem->setData('ebayenterprise_order_discount_data', serialize($data)); $quoteItem->save(); break; } } } else { $item->setEbayEnterpriseOrderDiscountData($data); $item->setData('ebayenterprise_order_discount_data', serialize($data)); $item->save(); } }
php
public function handleSalesRuleValidatorProcess(Varien_Event_Observer $observer) { /** @var Varien_Event $event */ $event = $observer->getEvent(); /** @var Mage_SalesRule_Model_Rule $rule */ $rule = $event->getRule(); /** @var Mage_Sales_Model_Quote $quote */ $quote = $event->getQuote(); /** @var Mage_Core_Model_Store $store */ $store = $quote->getStore(); /** @var Mage_Sales_Model_Quote_Item $item */ $item = $event->getItem(); /** @var Varien_Object */ $result = $event->getResult(); $data = (array) $item->getEbayEnterpriseOrderDiscountData(); $ruleId = $rule->getId(); // Use the rule id to prevent duplicates. $data[$ruleId] = [ 'amount' => $this->calculateDiscountAmount($item, $result, $data), 'applied_count' => $event->getQty(), 'code' => $this->helper->getQuoteCouponCode($quote, $rule), 'description' => $rule->getStoreLabel($store) ?: $rule->getName(), 'effect_type' => $rule->getSimpleAction(), 'id' => $ruleId, ]; if( $item instanceof Mage_Sales_Model_Quote_Address_Item ) { $item->setEbayEnterpriseOrderDiscountData($data); foreach( $quote->getAllItems() as $quoteItem ) { if( $quoteItem->getId() === $item->getQuoteItemId()) { $quoteItem->setData('ebayenterprise_order_discount_data', serialize($data)); $quoteItem->save(); break; } } } else { $item->setEbayEnterpriseOrderDiscountData($data); $item->setData('ebayenterprise_order_discount_data', serialize($data)); $item->save(); } }
Account for discounts in order create request. @see self::handleSalesConvertQuoteItemToOrderItem @see Mage_SalesRule_Model_Validator::process @see Order-Datatypes-Common-1.0.xsd:PromoDiscountSet @param Varien_Event_Observer @return void
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Observer.php#L183-L226
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Observer.php
Radial_Core_Model_Observer.calculateDiscountAmount
protected function calculateDiscountAmount(Mage_Sales_Model_Quote_Item_Abstract $item, Varien_Object $result, array $data) { /** @var float */ $itemRowTotal = $item->getBaseRowTotal(); /** @var float */ $currentDiscountAmount = $result->getBaseDiscountAmount(); /** @var float */ $previousAppliedDiscountAmount = 0.00; foreach ($data as $discount) { $previousAppliedDiscountAmount += $discount['amount']; } /** @var float */ $itemRowTotalWithAppliedPreviousDiscount = $itemRowTotal - $previousAppliedDiscountAmount; if ($itemRowTotalWithAppliedPreviousDiscount < 0) { $itemRowTotalWithAppliedPreviousDiscount = 0; } return $itemRowTotalWithAppliedPreviousDiscount < $currentDiscountAmount ? $itemRowTotalWithAppliedPreviousDiscount : $currentDiscountAmount; }
php
protected function calculateDiscountAmount(Mage_Sales_Model_Quote_Item_Abstract $item, Varien_Object $result, array $data) { /** @var float */ $itemRowTotal = $item->getBaseRowTotal(); /** @var float */ $currentDiscountAmount = $result->getBaseDiscountAmount(); /** @var float */ $previousAppliedDiscountAmount = 0.00; foreach ($data as $discount) { $previousAppliedDiscountAmount += $discount['amount']; } /** @var float */ $itemRowTotalWithAppliedPreviousDiscount = $itemRowTotal - $previousAppliedDiscountAmount; if ($itemRowTotalWithAppliedPreviousDiscount < 0) { $itemRowTotalWithAppliedPreviousDiscount = 0; } return $itemRowTotalWithAppliedPreviousDiscount < $currentDiscountAmount ? $itemRowTotalWithAppliedPreviousDiscount : $currentDiscountAmount; }
When the previously applied discount amount on the item row total is less than the current applied discount recalculate the current discount to account for previously applied discount. Otherwise, don't recalculate the current discount. @param Mage_Sales_Model_Quote_Item @param Varien_Object @param array @return float
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Observer.php#L239-L258
wearenolte/wp-elements
src/Utils.php
Utils.get_video_embed_url
public static function get_video_embed_url( $url ) { if ( strpos( $url, 'youtube' ) !== false && strpos( $url, 'watch' ) !== false ) { $parts = wp_parse_url( $url ); if ( is_array( $parts ) && isset( $parts['query'] ) ) { parse_str( $parts['query'] ); if ( isset( $v ) ) { return 'https://www.youtube.com/embed/' . $v; } } } if ( strpos( $url, 'vimeo' ) !== false && strpos( $url, 'player' ) === false ) { $parts = wp_parse_url( $url ); if ( is_array( $parts ) && isset( $parts['path'] ) ) { return 'https://player.vimeo.com/video' . $parts['path']; } } return $url; }
php
public static function get_video_embed_url( $url ) { if ( strpos( $url, 'youtube' ) !== false && strpos( $url, 'watch' ) !== false ) { $parts = wp_parse_url( $url ); if ( is_array( $parts ) && isset( $parts['query'] ) ) { parse_str( $parts['query'] ); if ( isset( $v ) ) { return 'https://www.youtube.com/embed/' . $v; } } } if ( strpos( $url, 'vimeo' ) !== false && strpos( $url, 'player' ) === false ) { $parts = wp_parse_url( $url ); if ( is_array( $parts ) && isset( $parts['path'] ) ) { return 'https://player.vimeo.com/video' . $parts['path']; } } return $url; }
Convert a "watch" url into an "embed" Eg https://www.youtube.com/watch?v=OQZKh8Bjdv0 to https://www.youtube.com/embed/OQZKh8Bjdv0 Or https://vimeo.com/155086124 to https://player.vimeo.com/video/155086124 @param string $url The video url. @return string
https://github.com/wearenolte/wp-elements/blob/e35a2878cfbd6746554ff7f6c0cee6f5239b0152/src/Utils.php#L18-L39
romeOz/rock-cache
src/Redis.php
Redis.setTags
protected function setTags($key, array $tags = []) { if (empty($tags)) { return; } foreach ($this->prepareTags($tags) as $tag) { $this->storage->sAdd($tag, $key); } }
php
protected function setTags($key, array $tags = []) { if (empty($tags)) { return; } foreach ($this->prepareTags($tags) as $tag) { $this->storage->sAdd($tag, $key); } }
Set tags. @param string $key @param array $tags
https://github.com/romeOz/rock-cache/blob/bbd146ee323e8cc1fb11dc1803215c3656e02c57/src/Redis.php#L259-L268
upiksaleh/codeup-yihai
src/theming/RowCol.php
RowCol.init
public function init() { if($this->type === 'row') { Theme::initWidget('row', $this); } elseif($this->type === 'col') { Theme::initWidget('col', $this); if($this->colClass){ Html::addCssClass($this->options, Theme::getClassCols($this->colClass)); } } echo Html::beginTag('div',$this->options)."\n"; }
php
public function init() { if($this->type === 'row') { Theme::initWidget('row', $this); } elseif($this->type === 'col') { Theme::initWidget('col', $this); if($this->colClass){ Html::addCssClass($this->options, Theme::getClassCols($this->colClass)); } } echo Html::beginTag('div',$this->options)."\n"; }
--------------------------------------------------------------------
https://github.com/upiksaleh/codeup-yihai/blob/98f3db37963157f8fa18c1637acc8d3877f6c982/src/theming/RowCol.php#L33-L45
ellipsephp/handlers-adr
src/ContainerResponder.php
ContainerResponder.response
public function response(ServerRequestInterface $request, PayloadInterface $payload): ResponseInterface { $responder = $this->container->get($this->id); if ($responder instanceof ResponderInterface) { return $responder->response($request, $payload); } throw new ContainedResponderTypeException($this->id, $responder); }
php
public function response(ServerRequestInterface $request, PayloadInterface $payload): ResponseInterface { $responder = $this->container->get($this->id); if ($responder instanceof ResponderInterface) { return $responder->response($request, $payload); } throw new ContainedResponderTypeException($this->id, $responder); }
Get the responder from the container then proxy its response method. @param \Psr\Http\Message\ServerRequestInterface $request @param \Ellipse\ADR\PayloadInterface $payload @return \Psr\Http\Message\ResponseInterface @throws \Ellipse\Handlers\Exceptions\ContainedResponderTypeException
https://github.com/ellipsephp/handlers-adr/blob/1c0879494a8b7718f7e157d0cd41b4c5ec19b5c5/src/ContainerResponder.php#L50-L61
bennybi/yii2-cza-base
components/actions/common/AttachmentDeleteAction.php
AttachmentDeleteAction.run
public function run($id) { $attachementClass = $this->attachementClass; $attachement = $attachementClass::findOne(['id' => $id]); if ($attachement->delete()) { if ($this->onComplete) { return call_user_func($this->onComplete, $id); } $responseData = ResponseDatum::getSuccessDatum(['message' => Yii::t('cza', 'Operation completed successfully!')], $id); } else { $responseData = ResponseDatum::getErrorDatum(['message' => Yii::t('cza', 'Error: operation can not finish!!')], $id); } return $this->controller->asJson($responseData); }
php
public function run($id) { $attachementClass = $this->attachementClass; $attachement = $attachementClass::findOne(['id' => $id]); if ($attachement->delete()) { if ($this->onComplete) { return call_user_func($this->onComplete, $id); } $responseData = ResponseDatum::getSuccessDatum(['message' => Yii::t('cza', 'Operation completed successfully!')], $id); } else { $responseData = ResponseDatum::getErrorDatum(['message' => Yii::t('cza', 'Error: operation can not finish!!')], $id); } return $this->controller->asJson($responseData); }
Runs the action. This method displays the view requested by the user. @throws HttpException if the view is invalid
https://github.com/bennybi/yii2-cza-base/blob/8257db8034bd948712fa469062921f210f0ba8da/components/actions/common/AttachmentDeleteAction.php#L37-L49
as3io/modlr
src/Metadata/Cache/CacheWarmer.php
CacheWarmer.clear
public function clear($type = null) { if (false === $this->mf->hasCache()) { return []; } return $this->doClear($this->getTypes($type)); }
php
public function clear($type = null) { if (false === $this->mf->hasCache()) { return []; } return $this->doClear($this->getTypes($type)); }
Clears metadata objects from the cache. @param string|array|null $type @return array
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/Cache/CacheWarmer.php#L38-L44
as3io/modlr
src/Metadata/Cache/CacheWarmer.php
CacheWarmer.warm
public function warm($type = null) { if (false === $this->mf->hasCache()) { return []; } return $this->doWarm($this->getTypes($type)); }
php
public function warm($type = null) { if (false === $this->mf->hasCache()) { return []; } return $this->doWarm($this->getTypes($type)); }
Warms up metadata objects into the cache. @param string|array|null $type @return array
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/Cache/CacheWarmer.php#L52-L58
as3io/modlr
src/Metadata/Cache/CacheWarmer.php
CacheWarmer.doClear
private function doClear(array $types) { $cleared = []; $this->mf->enableCache(false); foreach ($types as $type) { $metadata = $this->mf->getMetadataForType($type); $this->mf->getCache()->evictMetadataFromCache($metadata); $cleared[] = $type; } $this->mf->enableCache(true); $this->mf->clearMemory(); return $cleared; }
php
private function doClear(array $types) { $cleared = []; $this->mf->enableCache(false); foreach ($types as $type) { $metadata = $this->mf->getMetadataForType($type); $this->mf->getCache()->evictMetadataFromCache($metadata); $cleared[] = $type; } $this->mf->enableCache(true); $this->mf->clearMemory(); return $cleared; }
Clears metadata objects for the provided model types. @param array $types @return array
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/Cache/CacheWarmer.php#L66-L80
as3io/modlr
src/Metadata/Cache/CacheWarmer.php
CacheWarmer.doWarm
private function doWarm(array $types) { $warmed = []; $this->doClear($types); foreach ($types as $type) { $this->mf->getMetadataForType($type); $warmed[] = $type; } return $warmed; }
php
private function doWarm(array $types) { $warmed = []; $this->doClear($types); foreach ($types as $type) { $this->mf->getMetadataForType($type); $warmed[] = $type; } return $warmed; }
Warms up the metadata objects for the provided model types. @param array $types @return array
https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/Cache/CacheWarmer.php#L88-L97
IftekherSunny/Planet-Framework
src/Sun/Mail/Mailer.php
Mailer.send
public function send($email, $name = null, $subject, $body, $attachment = null, $bcc = null) { $this->phpMailer->isSMTP(); $this->phpMailer->Host = $this->app->config->getMail('host'); $this->phpMailer->SMTPAuth = true; $this->phpMailer->Username = $this->app->config->getMail('username'); $this->phpMailer->Password = $this->app->config->getMail('password'); $this->phpMailer->SMTPSecure = $this->app->config->getMail('encryption'); $this->phpMailer->Port = $this->app->config->getMail('port'); $this->phpMailer->From = $this->app->config->getMail('from.email'); $this->phpMailer->FromName = $this->app->config->getMail('from.name'); $this->phpMailer->addAddress($email, $name); $this->phpMailer->addReplyTo( $this->app->config->getMail('reply.email'), $this->app->config->getMail('mail.reply.name') ); $this->phpMailer->addBCC($bcc); $this->phpMailer->addAttachment($attachment); $this->phpMailer->isHTML(true); $this->phpMailer->Subject = $subject; $this->phpMailer->Body = $body; /** * If log set to true * then log email */ if ($this->app->config->getMail('log') == true) return $this->logEmail($body); /** * If log set to false * then send email */ if ( $this->app->config->getMail('log') !== true) { try { set_time_limit(0); if( ! $this->phpMailer->send()) throw new MailerException($this->phpMailer->ErrorInfo); else return true; } catch(phpmailerException $e) { throw new MailerException($e->errorMessage()); } } }
php
public function send($email, $name = null, $subject, $body, $attachment = null, $bcc = null) { $this->phpMailer->isSMTP(); $this->phpMailer->Host = $this->app->config->getMail('host'); $this->phpMailer->SMTPAuth = true; $this->phpMailer->Username = $this->app->config->getMail('username'); $this->phpMailer->Password = $this->app->config->getMail('password'); $this->phpMailer->SMTPSecure = $this->app->config->getMail('encryption'); $this->phpMailer->Port = $this->app->config->getMail('port'); $this->phpMailer->From = $this->app->config->getMail('from.email'); $this->phpMailer->FromName = $this->app->config->getMail('from.name'); $this->phpMailer->addAddress($email, $name); $this->phpMailer->addReplyTo( $this->app->config->getMail('reply.email'), $this->app->config->getMail('mail.reply.name') ); $this->phpMailer->addBCC($bcc); $this->phpMailer->addAttachment($attachment); $this->phpMailer->isHTML(true); $this->phpMailer->Subject = $subject; $this->phpMailer->Body = $body; /** * If log set to true * then log email */ if ($this->app->config->getMail('log') == true) return $this->logEmail($body); /** * If log set to false * then send email */ if ( $this->app->config->getMail('log') !== true) { try { set_time_limit(0); if( ! $this->phpMailer->send()) throw new MailerException($this->phpMailer->ErrorInfo); else return true; } catch(phpmailerException $e) { throw new MailerException($e->errorMessage()); } } }
To send an email @param string $email @param string $name @param string $subject @param string $body @param string $attachment @param array $bcc @return bool @throws MailerException
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Mail/Mailer.php#L63-L117
IftekherSunny/Planet-Framework
src/Sun/Mail/Mailer.php
Mailer.logEmail
protected function logEmail($body) { if(!$this->filesystem->exists($this->getLogDirectory())) { $this->filesystem->createDirectory($this->getLogDirectory()); } return $this->filesystem->create($this->logFileName, $body); }
php
protected function logEmail($body) { if(!$this->filesystem->exists($this->getLogDirectory())) { $this->filesystem->createDirectory($this->getLogDirectory()); } return $this->filesystem->create($this->logFileName, $body); }
Generate Email Log File @param $body @return bool
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Mail/Mailer.php#L126-L133
luoxiaojun1992/lb_framework
components/response/SwooleResponse.php
SwooleResponse.response
public function response($data, $format, $is_success=true, $status_code = 200) { $this->httpCode($status_code); if ($is_success) { $data['status'] = 1; } else { $data['status'] = 0; } switch ($format) { case self::RESPONSE_TYPE_JSON: $response_content = JsonHelper::encode($data); break; case self::RESPONSE_TYPE_XML: header('Content-type:application/xml'); $response_content = XMLHelper::encode($data); break; default: $response_content = ''; } if (!$is_success) { $this->swooleResponse->end($response_content); } else { echo $response_content; } }
php
public function response($data, $format, $is_success=true, $status_code = 200) { $this->httpCode($status_code); if ($is_success) { $data['status'] = 1; } else { $data['status'] = 0; } switch ($format) { case self::RESPONSE_TYPE_JSON: $response_content = JsonHelper::encode($data); break; case self::RESPONSE_TYPE_XML: header('Content-type:application/xml'); $response_content = XMLHelper::encode($data); break; default: $response_content = ''; } if (!$is_success) { $this->swooleResponse->end($response_content); } else { echo $response_content; } }
Response Request @param $data @param $format @param bool $is_success @param int $status_code
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/response/SwooleResponse.php#L34-L58
luoxiaojun1992/lb_framework
components/response/SwooleResponse.php
SwooleResponse.startSession
public function startSession() { $swooleSession = SwooleSession::component(); $swooleSession->gc(time()); $swooleSession->write($this->getSessionId(), Lb::app()->serialize([])); return true; }
php
public function startSession() { $swooleSession = SwooleSession::component(); $swooleSession->gc(time()); $swooleSession->write($this->getSessionId(), Lb::app()->serialize([])); return true; }
Start Session @return bool
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/response/SwooleResponse.php#L103-L109
luoxiaojun1992/lb_framework
components/response/SwooleResponse.php
SwooleResponse.delSession
public function delSession($sessionKey) { $sessions = []; $swooleSession = SwooleSession::component(); $swooleSession->gc(time()); $sessionData = $swooleSession->read($this->getSessionId()); if ($sessionData) { $sessions = Lb::app()->unserialize($sessionData); } if (isset($sessions[$sessionKey])) { unset($sessions[$sessionKey]); $swooleSession->write($this->getSessionId(), Lb::app()->serialize($sessions)); } }
php
public function delSession($sessionKey) { $sessions = []; $swooleSession = SwooleSession::component(); $swooleSession->gc(time()); $sessionData = $swooleSession->read($this->getSessionId()); if ($sessionData) { $sessions = Lb::app()->unserialize($sessionData); } if (isset($sessions[$sessionKey])) { unset($sessions[$sessionKey]); $swooleSession->write($this->getSessionId(), Lb::app()->serialize($sessions)); } }
Delete session @param $sessionKey
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/response/SwooleResponse.php#L137-L150
luoxiaojun1992/lb_framework
components/response/SwooleResponse.php
SwooleResponse.setHeader
public function setHeader($key, $value, $replace = true, $http_response_code = null) { $this->swooleResponse->header($key. $value); }
php
public function setHeader($key, $value, $replace = true, $http_response_code = null) { $this->swooleResponse->header($key. $value); }
Set header @param $key @param $value @param bool $replace @param $http_response_code
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/response/SwooleResponse.php#L160-L163
luoxiaojun1992/lb_framework
components/response/SwooleResponse.php
SwooleResponse.setCookie
public function setCookie( $cookie_key, $cookie_value, $expire = null, $path = null, $domain = null, $secure = null, $httpOnly = null ) { $this->swooleResponse->cookie( $cookie_key, Lb::app()->encryptByConfig($cookie_value), $expire, $path, $domain, $secure, $httpOnly ); }
php
public function setCookie( $cookie_key, $cookie_value, $expire = null, $path = null, $domain = null, $secure = null, $httpOnly = null ) { $this->swooleResponse->cookie( $cookie_key, Lb::app()->encryptByConfig($cookie_value), $expire, $path, $domain, $secure, $httpOnly ); }
Set cookie @param $cookie_key @param $cookie_value @param null $expire @param null $path @param null $domain @param null $secure @param null $httpOnly
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/response/SwooleResponse.php#L176-L195
PhoxPHP/Glider
src/Console/TemplateBuilder.php
TemplateBuilder.createClassTemplate
public function createClassTemplate(String $templateName, String $filename, $savePath=null, Array $templateTags) { $template = file_get_contents(__DIR__ . '/templates/' . $templateName); foreach($templateTags as $key => $tag) { if (!preg_match_all('/' . $key . '/', $template)) { throw new RuntimeException(sprintf('[%s] tag does not exist in template.', $key)); } } if (!is_dir($savePath) || !is_readable($savePath)) { throw new RuntimeException(sprintf('[%s] directory is not readable', $savePath)); } $template = str_replace( array_keys($templateTags), array_values($templateTags), $template ); $file = $savePath . '/' . $filename . '.php'; $handle = fopen($file, 'w+'); fwrite($handle, $template); fclose($handle); $this->env->sendOutput( sprintf( '[%s] class has been generated and placed in [%s]', $templateTags['phx:class'], $file ), 'green', 'black' ); }
php
public function createClassTemplate(String $templateName, String $filename, $savePath=null, Array $templateTags) { $template = file_get_contents(__DIR__ . '/templates/' . $templateName); foreach($templateTags as $key => $tag) { if (!preg_match_all('/' . $key . '/', $template)) { throw new RuntimeException(sprintf('[%s] tag does not exist in template.', $key)); } } if (!is_dir($savePath) || !is_readable($savePath)) { throw new RuntimeException(sprintf('[%s] directory is not readable', $savePath)); } $template = str_replace( array_keys($templateTags), array_values($templateTags), $template ); $file = $savePath . '/' . $filename . '.php'; $handle = fopen($file, 'w+'); fwrite($handle, $template); fclose($handle); $this->env->sendOutput( sprintf( '[%s] class has been generated and placed in [%s]', $templateTags['phx:class'], $file ), 'green', 'black' ); }
Builds a class template. @param $templateName <String> @param $filename <String> @param $savePath <String> @param $templateTags <Array> @access public @return <void>
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Console/TemplateBuilder.php#L68-L101
antaresproject/translations
src/Http/Handlers/TranslationsBreadcrumbMenu.php
TranslationsBreadcrumbMenu.handle
public function handle() { if (!$this->passesAuthorization()) { return; } $code = from_route('code'); $id = from_route('id'); $locale = is_null($code) ? app()->getLocale() : $code; $locale = $locale == null ? 'en' : $locale; $current = Languages::where('code', $locale)->first(); $this->createMenu(); $acl = app('antares.acl')->make('antares/translations'); if ($acl->can('add-language')) { $this->handler ->add('translations-add-language', '^:translations-breadcrumb') ->title(trans('antares/translations::messages.manage_languages')) ->icon('zmdi-format-list-bulleted') ->link(handles('antares::translations/languages/index')); } if ($acl->can('import-translations')) { $this->handler ->add('translations-import', '^:translations-breadcrumb') ->title(trans('antares/translations::messages.import')) ->icon('zmdi-arrow-left-bottom') ->link(handles('antares::translations/languages/import/' . $current->code . '/' . $id)); } if ($acl->can('export-translations')) { $this->handler ->add('translations-export', '^:translations-breadcrumb') ->title(trans('antares/translations::messages.export')) ->icon('zmdi-arrow-right-top') ->link(handles('antares::translations/languages/export/' . $current->code . '/' . $id)) ->attributes([ 'class' => 'export-translations', 'data-title' => trans('antares/translations::messages.export_translations_ask'), 'data-description' => trans('antares/translations::messages.export_translations_description') ]); } if ($acl->can('publish-translations')) { $this->handler ->add('translations-publish', '^:translations-breadcrumb') ->title(trans('antares/translations::messages.publish')) ->icon('zmdi-check-all') ->link(handles('antares::translations/languages/publish/' . $id)) ->attributes([ 'class' => 'publish-translations', 'data-title' => trans('antares/translations::messages.publish_translations_ask'), 'data-description' => trans('antares/translations::messages.publish_translations_description') ]); } }
php
public function handle() { if (!$this->passesAuthorization()) { return; } $code = from_route('code'); $id = from_route('id'); $locale = is_null($code) ? app()->getLocale() : $code; $locale = $locale == null ? 'en' : $locale; $current = Languages::where('code', $locale)->first(); $this->createMenu(); $acl = app('antares.acl')->make('antares/translations'); if ($acl->can('add-language')) { $this->handler ->add('translations-add-language', '^:translations-breadcrumb') ->title(trans('antares/translations::messages.manage_languages')) ->icon('zmdi-format-list-bulleted') ->link(handles('antares::translations/languages/index')); } if ($acl->can('import-translations')) { $this->handler ->add('translations-import', '^:translations-breadcrumb') ->title(trans('antares/translations::messages.import')) ->icon('zmdi-arrow-left-bottom') ->link(handles('antares::translations/languages/import/' . $current->code . '/' . $id)); } if ($acl->can('export-translations')) { $this->handler ->add('translations-export', '^:translations-breadcrumb') ->title(trans('antares/translations::messages.export')) ->icon('zmdi-arrow-right-top') ->link(handles('antares::translations/languages/export/' . $current->code . '/' . $id)) ->attributes([ 'class' => 'export-translations', 'data-title' => trans('antares/translations::messages.export_translations_ask'), 'data-description' => trans('antares/translations::messages.export_translations_description') ]); } if ($acl->can('publish-translations')) { $this->handler ->add('translations-publish', '^:translations-breadcrumb') ->title(trans('antares/translations::messages.publish')) ->icon('zmdi-check-all') ->link(handles('antares::translations/languages/publish/' . $id)) ->attributes([ 'class' => 'publish-translations', 'data-title' => trans('antares/translations::messages.publish_translations_ask'), 'data-description' => trans('antares/translations::messages.publish_translations_description') ]); } }
Metoda wyzwalna podczas renderowania widoku i dodająca budująca menu jako submenu breadcrumbs @return void
https://github.com/antaresproject/translations/blob/63097aeb97f18c5aeeef7dcf15f0c67959951685/src/Http/Handlers/TranslationsBreadcrumbMenu.php#L61-L113
stonedz/pff2
src/modules/logger/Utils/LoggerFile.php
LoggerFile.getLogFile
public function getLogFile() { if ($this->_fp === null) { $this->LOG_DIR = ROOT .DS. 'app' . DS . 'logs'; $filename = $this->LOG_DIR . DS . date("Y-m-d"); $this->_fp = fopen($filename, 'a'); if ($this->_fp === false) { throw new LoggerException('Cannot open log file: ' . $filename); } chmod($filename, 0774); } return $this->_fp; }
php
public function getLogFile() { if ($this->_fp === null) { $this->LOG_DIR = ROOT .DS. 'app' . DS . 'logs'; $filename = $this->LOG_DIR . DS . date("Y-m-d"); $this->_fp = fopen($filename, 'a'); if ($this->_fp === false) { throw new LoggerException('Cannot open log file: ' . $filename); } chmod($filename, 0774); } return $this->_fp; }
Opens log file only if it's not already open @throws LoggerException @return null|resource
https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/modules/logger/Utils/LoggerFile.php#L55-L69
stonedz/pff2
src/modules/logger/Utils/LoggerFile.php
LoggerFile.logMessage
public function logMessage($message, $level = 0) { $this->getLogFile(); if (!flock($this->_fp, LOCK_EX)) { throw new LoggerFileException('Can\'t obtain file lock for: '); } $text = '[' . date("H:i:s") . ']' . $this->_levelNames[$level] . " " . $message . "\n"; // Log message if (fwrite($this->_fp, $text)) { flock($this->_fp, LOCK_UN); return true; } else { flock($this->_fp, LOCK_UN); throw new LoggerFileException('Can\'t write to logfile!'); } }
php
public function logMessage($message, $level = 0) { $this->getLogFile(); if (!flock($this->_fp, LOCK_EX)) { throw new LoggerFileException('Can\'t obtain file lock for: '); } $text = '[' . date("H:i:s") . ']' . $this->_levelNames[$level] . " " . $message . "\n"; // Log message if (fwrite($this->_fp, $text)) { flock($this->_fp, LOCK_UN); return true; } else { flock($this->_fp, LOCK_UN); throw new LoggerFileException('Can\'t write to logfile!'); } }
Logs a message @param string $message Message to log @param int $level Log level @return bool @throws LoggerFileException
https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/modules/logger/Utils/LoggerFile.php#L79-L92
crisu83/yii-consoletools
commands/FlushCommand.php
FlushCommand.init
public function init() { if (!isset($this->basePath)) { $this->basePath = Yii::getPathOfAlias('webroot'); } $this->basePath = rtrim($this->basePath, '/'); }
php
public function init() { if (!isset($this->basePath)) { $this->basePath = Yii::getPathOfAlias('webroot'); } $this->basePath = rtrim($this->basePath, '/'); }
Initializes the command.
https://github.com/crisu83/yii-consoletools/blob/53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc/commands/FlushCommand.php#L36-L42
crisu83/yii-consoletools
commands/FlushCommand.php
FlushCommand.flush
protected function flush() { echo "\nFlushing directories... "; foreach ($this->flushPaths as $dir) { $path = $this->basePath . '/' . $dir; if (file_exists($path)) { $this->flushDirectory($path); } $this->ensureDirectory($path); } echo "done\n"; }
php
protected function flush() { echo "\nFlushing directories... "; foreach ($this->flushPaths as $dir) { $path = $this->basePath . '/' . $dir; if (file_exists($path)) { $this->flushDirectory($path); } $this->ensureDirectory($path); } echo "done\n"; }
Flushes directories.
https://github.com/crisu83/yii-consoletools/blob/53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc/commands/FlushCommand.php#L47-L58
crisu83/yii-consoletools
commands/FlushCommand.php
FlushCommand.flushDirectory
protected function flushDirectory($path, $delete = false) { if (is_dir($path)) { $entries = scandir($path); foreach ($entries as $entry) { $exclude = array_merge(array('.', '..'), $this->exclude); if (in_array($entry, $exclude)) { continue; } $entryPath = $path . '/' . $entry; if (!is_link($entryPath) && is_dir($entryPath)) { $this->flushDirectory($entryPath, true); } else { unlink($entryPath); } } if ($delete) { rmdir($path); } } }
php
protected function flushDirectory($path, $delete = false) { if (is_dir($path)) { $entries = scandir($path); foreach ($entries as $entry) { $exclude = array_merge(array('.', '..'), $this->exclude); if (in_array($entry, $exclude)) { continue; } $entryPath = $path . '/' . $entry; if (!is_link($entryPath) && is_dir($entryPath)) { $this->flushDirectory($entryPath, true); } else { unlink($entryPath); } } if ($delete) { rmdir($path); } } }
Flushes a directory recursively. @param string $path the directory path. @param boolean $delete whether to delete the directory.
https://github.com/crisu83/yii-consoletools/blob/53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc/commands/FlushCommand.php#L65-L85
smartboxgroup/camel-config-bundle
ProcessorDefinitions/ThrottlerDefinition.php
ThrottlerDefinition.buildProcessor
public function buildProcessor($configNode, $id) { $def = parent::buildProcessor($configNode, $id); // timePeriodMillis $timeMs = (int) $configNode->attributes()->{'timePeriodMillis'}; if (!$timeMs && is_int($timeMs) && !$timeMs >= 0) { throw new \RuntimeException('The attribute timePeriodMillis of the throttler processor must be defined and be an integer >= 0'); } // asyncDelayed $asyncDelayed = false; if (isset($configNode->attributes()->{'asyncDelayed'})) { $asyncDelayed = strtolower($configNode->attributes()->{'asyncDelayed'}); if (!in_array($asyncDelayed, ['true', 'false'])) { throw new \RuntimeException(sprintf( 'The attribute asyncDelayed must be boolean ("true" or "false"): "%s" given', $asyncDelayed )); } $asyncDelayed = $asyncDelayed === 'true' ? true : false; } $def->addMethodCall('setPeriodMs', [$timeMs]); $def->addMethodCall('setAsyncDelayed', [$asyncDelayed]); $expression = null; $itineraryName = $this->getBuilder()->generateNextUniqueReproducibleIdForContext($id); $itineraryRef = $this->builder->buildItinerary($itineraryName); $evaluator = $this->getEvaluator(); foreach ($configNode as $nodeName => $nodeValue) { switch ($nodeName) { case self::SIMPLE: $expression = (string) $nodeValue; try { $evaluator->compile($expression, $this->evaluator->getExchangeExposedVars()); } catch (\Exception $e) { throw new InvalidConfigurationException( "Given value ({$expression}) should be a valid expression: ".$e->getMessage(), $e->getCode(), $e ); } break; case self::DESCRIPTION: $def->addMethodCall('setDescription', (string) $nodeValue); break; default: $this->builder->addNodeToItinerary($itineraryRef, $nodeName, $nodeValue); break; } } if ($expression === null) { throw new \RuntimeException('An expression must be defined for the throttler processor'); } $def->addMethodCall('setItinerary', [$itineraryRef]); $def->addMethodCall('setLimitExpression', [$expression]); return $def; }
php
public function buildProcessor($configNode, $id) { $def = parent::buildProcessor($configNode, $id); // timePeriodMillis $timeMs = (int) $configNode->attributes()->{'timePeriodMillis'}; if (!$timeMs && is_int($timeMs) && !$timeMs >= 0) { throw new \RuntimeException('The attribute timePeriodMillis of the throttler processor must be defined and be an integer >= 0'); } // asyncDelayed $asyncDelayed = false; if (isset($configNode->attributes()->{'asyncDelayed'})) { $asyncDelayed = strtolower($configNode->attributes()->{'asyncDelayed'}); if (!in_array($asyncDelayed, ['true', 'false'])) { throw new \RuntimeException(sprintf( 'The attribute asyncDelayed must be boolean ("true" or "false"): "%s" given', $asyncDelayed )); } $asyncDelayed = $asyncDelayed === 'true' ? true : false; } $def->addMethodCall('setPeriodMs', [$timeMs]); $def->addMethodCall('setAsyncDelayed', [$asyncDelayed]); $expression = null; $itineraryName = $this->getBuilder()->generateNextUniqueReproducibleIdForContext($id); $itineraryRef = $this->builder->buildItinerary($itineraryName); $evaluator = $this->getEvaluator(); foreach ($configNode as $nodeName => $nodeValue) { switch ($nodeName) { case self::SIMPLE: $expression = (string) $nodeValue; try { $evaluator->compile($expression, $this->evaluator->getExchangeExposedVars()); } catch (\Exception $e) { throw new InvalidConfigurationException( "Given value ({$expression}) should be a valid expression: ".$e->getMessage(), $e->getCode(), $e ); } break; case self::DESCRIPTION: $def->addMethodCall('setDescription', (string) $nodeValue); break; default: $this->builder->addNodeToItinerary($itineraryRef, $nodeName, $nodeValue); break; } } if ($expression === null) { throw new \RuntimeException('An expression must be defined for the throttler processor'); } $def->addMethodCall('setItinerary', [$itineraryRef]); $def->addMethodCall('setLimitExpression', [$expression]); return $def; }
{@inheritdoc}
https://github.com/smartboxgroup/camel-config-bundle/blob/f38505c50a446707b8e8f79ecaa1addd0a6cca11/ProcessorDefinitions/ThrottlerDefinition.php#L21-L86
cyberspectrum/i18n-contao
src/Extractor/Condition/ExpressionLanguageCondition.php
ExpressionLanguageCondition.evaluate
public function evaluate(array $row): bool { return (bool) $this->expressionLanguage->evaluate($this->expression, ['row' => (object) $row]); }
php
public function evaluate(array $row): bool { return (bool) $this->expressionLanguage->evaluate($this->expression, ['row' => (object) $row]); }
{@inheritDoc}
https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/Extractor/Condition/ExpressionLanguageCondition.php#L60-L63
frogbob/laravel-vue-ts-component-generator
src/LaravelVueTsComponentGenerator/Commands/GenerateVueComponent.php
GenerateVueComponent.buildClass
protected function buildClass($name) { $replace = [ '$componentName' => $name ]; return str_replace( array_keys($replace), array_values($replace), $this->generateClass($name) ); }
php
protected function buildClass($name) { $replace = [ '$componentName' => $name ]; return str_replace( array_keys($replace), array_values($replace), $this->generateClass($name) ); }
Build the class with the given name. Remove the base controller import if we are already in base namespace. @param string $name @return string
https://github.com/frogbob/laravel-vue-ts-component-generator/blob/5d9b97b0de753ac31fe5f9abcf15fe9405953ba9/src/LaravelVueTsComponentGenerator/Commands/GenerateVueComponent.php#L65-L73
jasny/meta
src/Source/CombinedSource.php
CombinedSource.forClass
public function forClass(string $class): array { $meta = []; foreach ($this->sources as $source) { $sourceMeta = $source->forClass($class); $meta = $this->mergeMeta($meta, $sourceMeta); } return $meta; }
php
public function forClass(string $class): array { $meta = []; foreach ($this->sources as $source) { $sourceMeta = $source->forClass($class); $meta = $this->mergeMeta($meta, $sourceMeta); } return $meta; }
Obtain meta data for class as array @throws InvalidArgumentException If class does not exist @param string $class @return array
https://github.com/jasny/meta/blob/26cf119542433776fecc6c31341787091fc2dbb6/src/Source/CombinedSource.php#L41-L51
jasny/meta
src/Source/CombinedSource.php
CombinedSource.mergeMeta
protected function mergeMeta(array $meta, array $sourceMeta): array { $properties = $meta['properties'] ?? []; $sourceProperties = $sourceMeta['properties'] ?? []; foreach ($sourceProperties as $name => $data) { $properties[$name] = array_merge($properties[$name] ?? [], $data); } $meta = array_merge($meta, $sourceMeta); $meta['properties'] = $properties; return $meta; }
php
protected function mergeMeta(array $meta, array $sourceMeta): array { $properties = $meta['properties'] ?? []; $sourceProperties = $sourceMeta['properties'] ?? []; foreach ($sourceProperties as $name => $data) { $properties[$name] = array_merge($properties[$name] ?? [], $data); } $meta = array_merge($meta, $sourceMeta); $meta['properties'] = $properties; return $meta; }
Merge meta data @param array $meta @param array $sourceMeta @return array
https://github.com/jasny/meta/blob/26cf119542433776fecc6c31341787091fc2dbb6/src/Source/CombinedSource.php#L60-L73
Phpillip/phpillip
src/Controller/ContentController.php
ContentController.page
public function page(Request $request, Application $app, Paginator $paginator) { return array_merge( ['pages' => count($paginator)], $this->extractViewParameters($request, ['app', 'paginator']) ); }
php
public function page(Request $request, Application $app, Paginator $paginator) { return array_merge( ['pages' => count($paginator)], $this->extractViewParameters($request, ['app', 'paginator']) ); }
Paginated list of contents @param Request $request @param Application $app @param Paginator $paginator @return array
https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/Controller/ContentController.php#L36-L42
Phpillip/phpillip
src/Controller/ContentController.php
ContentController.extractViewParameters
protected function extractViewParameters(Request $request, array $exclude = []) { $parameters = []; foreach ($request->attributes as $key => $value) { if (strpos($key, '_') !== 0 && !in_array($key, $exclude)) { $parameters[$key] = $value; } } return $parameters; }
php
protected function extractViewParameters(Request $request, array $exclude = []) { $parameters = []; foreach ($request->attributes as $key => $value) { if (strpos($key, '_') !== 0 && !in_array($key, $exclude)) { $parameters[$key] = $value; } } return $parameters; }
Extract view parameters from Request attributes @param Request $request @param array $exclude Keys to exclude from view @return array
https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/Controller/ContentController.php#L65-L76
PlatoCreative/silverstripe-sections
code/sections/BreadcrumbSection.php
BreadcrumbSection.getCMSFields
public function getCMSFields() { $fields = parent::getCMSFields(); $fields->addFieldsToTab( "Root.Main", array( DropdownField::create( 'ShowHome', 'Show home', array( "1" => "Yes", "0" => "No" ), 1 ) ) ); $this->extend('updateCMSFields', $fields); return $fields; }
php
public function getCMSFields() { $fields = parent::getCMSFields(); $fields->addFieldsToTab( "Root.Main", array( DropdownField::create( 'ShowHome', 'Show home', array( "1" => "Yes", "0" => "No" ), 1 ) ) ); $this->extend('updateCMSFields', $fields); return $fields; }
CMS Fields @return FieldList
https://github.com/PlatoCreative/silverstripe-sections/blob/54c96146ea8cc625b00ee009753539658f10d01a/code/sections/BreadcrumbSection.php#L26-L47
matryoshka-model/matryoshka
library/ResultSet/BufferedResultSet.php
BufferedResultSet.initialize
public function initialize($dataSource) { $this->position = 0; $this->count = null; $this->buffer = []; $this->resultSet->initialize($dataSource); return $this; }
php
public function initialize($dataSource) { $this->position = 0; $this->count = null; $this->buffer = []; $this->resultSet->initialize($dataSource); return $this; }
{@inheritdoc}
https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/ResultSet/BufferedResultSet.php#L57-L65
matryoshka-model/matryoshka
library/ResultSet/BufferedResultSet.php
BufferedResultSet.next
public function next() { if (!isset($this->buffer[++$this->position]) && $this->position != $this->resultSet->key() // Avoid calling next() when // a complete iteration was already done ) { $this->resultSet->next(); } }
php
public function next() { if (!isset($this->buffer[++$this->position]) && $this->position != $this->resultSet->key() // Avoid calling next() when // a complete iteration was already done ) { $this->resultSet->next(); } }
Iterator: move pointer to next item @return void
https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/ResultSet/BufferedResultSet.php#L111-L119
matryoshka-model/matryoshka
library/ResultSet/BufferedResultSet.php
BufferedResultSet.current
public function current() { if (isset($this->buffer[$this->position])) { return $this->buffer[$this->position]; } $this->ensurePosition(); $data = $this->resultSet->current(); $this->buffer[$this->position] = $data; return $data; }
php
public function current() { if (isset($this->buffer[$this->position])) { return $this->buffer[$this->position]; } $this->ensurePosition(); $data = $this->resultSet->current(); $this->buffer[$this->position] = $data; return $data; }
Iterator: get current item @return mixed
https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/ResultSet/BufferedResultSet.php#L136-L145
matryoshka-model/matryoshka
library/ResultSet/BufferedResultSet.php
BufferedResultSet.valid
public function valid() { if (isset($this->buffer[$this->position])) { return (bool) $this->buffer[$this->position]; } $this->ensurePosition(); return $this->resultSet->valid(); }
php
public function valid() { if (isset($this->buffer[$this->position])) { return (bool) $this->buffer[$this->position]; } $this->ensurePosition(); return $this->resultSet->valid(); }
Iterator: is pointer valid? @return bool
https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/ResultSet/BufferedResultSet.php#L152-L159
matryoshka-model/matryoshka
library/ResultSet/BufferedResultSet.php
BufferedResultSet.count
public function count() { if ($this->count === null) { $this->count = $this->resultSet->count(); } return $this->count; }
php
public function count() { if ($this->count === null) { $this->count = $this->resultSet->count(); } return $this->count; }
Countable: return count of items @return int @throws Exception\RuntimeException
https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/ResultSet/BufferedResultSet.php#L177-L183
IftekherSunny/Planet-Framework
src/Sun/Bus/CommandTranslator.php
CommandTranslator.translate
public function translate($object) { $commandBaseNamespace = app()->getNamespace() . "Commands"; $handlerBaseNamespace = app()->getNamespace(). "Handlers"; $reflectionObject = new ReflectionClass($object); $commandNamespace = $this->getCommandNamespace($commandBaseNamespace, $reflectionObject); $command = $this->getCommandName($reflectionObject); $handler = str_replace('Command', 'CommandHandler', $command); if($commandNamespace !== $commandBaseNamespace) { $handlerNamespace = $handlerBaseNamespace . $commandNamespace . "\\" . $handler; $commandNamespace = $commandBaseNamespace . $commandNamespace . "\\" . $command; } if(! class_exists($commandNamespace)) { throw new CommandNotFoundException("Command [ $command ] does not exist."); } if(! class_exists($handlerNamespace)) { throw new HandlerNotFoundException("Handler [ $handler ] does nto exist."); } return $handlerNamespace; }
php
public function translate($object) { $commandBaseNamespace = app()->getNamespace() . "Commands"; $handlerBaseNamespace = app()->getNamespace(). "Handlers"; $reflectionObject = new ReflectionClass($object); $commandNamespace = $this->getCommandNamespace($commandBaseNamespace, $reflectionObject); $command = $this->getCommandName($reflectionObject); $handler = str_replace('Command', 'CommandHandler', $command); if($commandNamespace !== $commandBaseNamespace) { $handlerNamespace = $handlerBaseNamespace . $commandNamespace . "\\" . $handler; $commandNamespace = $commandBaseNamespace . $commandNamespace . "\\" . $command; } if(! class_exists($commandNamespace)) { throw new CommandNotFoundException("Command [ $command ] does not exist."); } if(! class_exists($handlerNamespace)) { throw new HandlerNotFoundException("Handler [ $handler ] does nto exist."); } return $handlerNamespace; }
To translate command to command handler @param $object @return string @throws CommandNotFoundException @throws HandlerNotFoundException
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Bus/CommandTranslator.php#L19-L48
IftekherSunny/Planet-Framework
src/Sun/Support/Config.php
Config.find
public function find($item = null, $array = null) { if(is_null($item)) return null; if(strpos($item, '.')) { $arr = explode('.', $item); if(count($arr) > 2 ) { $itemToSearch = join('.', array_slice($arr, 1)); } else { $itemToSearch = $arr[1]; } return $this->findItemIn($itemToSearch, $arr[0]); } else { $array = !is_null($array) ? $array : $this->settings; foreach ($array as $key => $value) { if($key === $item) { $this->currentItem = $value; $this->found = true; break; } else { if(is_array($value)) { $this->find($item, $value); } } } } if(!$this->found) { return false; } return $this->currentItem; }
php
public function find($item = null, $array = null) { if(is_null($item)) return null; if(strpos($item, '.')) { $arr = explode('.', $item); if(count($arr) > 2 ) { $itemToSearch = join('.', array_slice($arr, 1)); } else { $itemToSearch = $arr[1]; } return $this->findItemIn($itemToSearch, $arr[0]); } else { $array = !is_null($array) ? $array : $this->settings; foreach ($array as $key => $value) { if($key === $item) { $this->currentItem = $value; $this->found = true; break; } else { if(is_array($value)) { $this->find($item, $value); } } } } if(!$this->found) { return false; } return $this->currentItem; }
Recursively finds an item from the settings array @param string $item @param array $array @return object/$this
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Support/Config.php#L191-L225
makinacorpus/drupal-calista
src/PropertyInfo/EntityProperyInfoExtractor.php
EntityProperyInfoExtractor.getLabelFor
private function getLabelFor($property) { switch ($property) { case 'nid': return t("Node ID."); case 'vid': return t("Revision ID."); case 'type': return t("Type"); case 'language': return t("Language"); case 'label': return t("Label"); case 'title': return t("Title"); case 'uid': return t("User ID."); case 'status': return t("Status"); case 'changed': return t("Latest update at"); case 'created': return t("Created at"); case 'promote': return t("Promoted"); case 'sticky': return t("Sticked"); case 'name': return t("Name"); case 'pass': return t("Password"); case 'mail': return t("E-mail"); case 'theme': return t("Theme"); case 'signature': return t("Signature"); case 'signature_format': return t("Signature format"); case 'access': return t("Lastest access at"); case 'login': return t("Lastest login at"); case 'timezone': return t("Timezone"); case 'description': return t("Description"); case 'format': return t("Format"); } return $property; }
php
private function getLabelFor($property) { switch ($property) { case 'nid': return t("Node ID."); case 'vid': return t("Revision ID."); case 'type': return t("Type"); case 'language': return t("Language"); case 'label': return t("Label"); case 'title': return t("Title"); case 'uid': return t("User ID."); case 'status': return t("Status"); case 'changed': return t("Latest update at"); case 'created': return t("Created at"); case 'promote': return t("Promoted"); case 'sticky': return t("Sticked"); case 'name': return t("Name"); case 'pass': return t("Password"); case 'mail': return t("E-mail"); case 'theme': return t("Theme"); case 'signature': return t("Signature"); case 'signature_format': return t("Signature format"); case 'access': return t("Lastest access at"); case 'login': return t("Lastest login at"); case 'timezone': return t("Timezone"); case 'description': return t("Description"); case 'format': return t("Format"); } return $property; }
Attempt to guess the property description, knowing that Drupalisms are strong and a lot of people will always use the same colum names @param string $property @param string
https://github.com/makinacorpus/drupal-calista/blob/cceb6b975fc3e80f0f83c803fc6f6a9ac5852b53/src/PropertyInfo/EntityProperyInfoExtractor.php#L43-L118
makinacorpus/drupal-calista
src/PropertyInfo/EntityProperyInfoExtractor.php
EntityProperyInfoExtractor.schemaApiTypeToPropertyInfoType
private function schemaApiTypeToPropertyInfoType($type) { switch ($type) { case 'serial': case 'int': return new Type(Type::BUILTIN_TYPE_INT, true); case 'float': case 'numeric': return new Type(Type::BUILTIN_TYPE_FLOAT, true); case 'varchar': case 'text': case 'blob': return new Type(Type::BUILTIN_TYPE_STRING, true); } }
php
private function schemaApiTypeToPropertyInfoType($type) { switch ($type) { case 'serial': case 'int': return new Type(Type::BUILTIN_TYPE_INT, true); case 'float': case 'numeric': return new Type(Type::BUILTIN_TYPE_FLOAT, true); case 'varchar': case 'text': case 'blob': return new Type(Type::BUILTIN_TYPE_STRING, true); } }
Convert schema API type to property info type @param string $type @return null|Type
https://github.com/makinacorpus/drupal-calista/blob/cceb6b975fc3e80f0f83c803fc6f6a9ac5852b53/src/PropertyInfo/EntityProperyInfoExtractor.php#L127-L144
makinacorpus/drupal-calista
src/PropertyInfo/EntityProperyInfoExtractor.php
EntityProperyInfoExtractor.getEntityTypeInfo
private function getEntityTypeInfo($class) { $entityType = $this->getEntityType($class); if (!$entityType) { return [null, null]; } $info = entity_get_info($entityType); if (!$info) { return [null, null]; } return [$entityType, $info]; }
php
private function getEntityTypeInfo($class) { $entityType = $this->getEntityType($class); if (!$entityType) { return [null, null]; } $info = entity_get_info($entityType); if (!$info) { return [null, null]; } return [$entityType, $info]; }
Get entity type info for the given class @param string $class @return array If entity type is found, first key is the entity type, second value is the entity info array
https://github.com/makinacorpus/drupal-calista/blob/cceb6b975fc3e80f0f83c803fc6f6a9ac5852b53/src/PropertyInfo/EntityProperyInfoExtractor.php#L155-L170
makinacorpus/drupal-calista
src/PropertyInfo/EntityProperyInfoExtractor.php
EntityProperyInfoExtractor.findFieldInstances
private function findFieldInstances($entityType, $entityInfo) { $ret = []; // Add field properties, since Drupal does not differenciate entity // bundles using different class for different object, we are just // gonna give the whole field list foreach (field_info_instances($entityType) as $fields) { foreach ($fields as $name => $instance) { if (isset($ret[$name])) { continue; } $ret[$name] = $instance; } } return $ret; }
php
private function findFieldInstances($entityType, $entityInfo) { $ret = []; // Add field properties, since Drupal does not differenciate entity // bundles using different class for different object, we are just // gonna give the whole field list foreach (field_info_instances($entityType) as $fields) { foreach ($fields as $name => $instance) { if (isset($ret[$name])) { continue; } $ret[$name] = $instance; } } return $ret; }
Guess the while field instances for the given entity type @param string $entityType @param array $entityInfo @param string $property @return null|array
https://github.com/makinacorpus/drupal-calista/blob/cceb6b975fc3e80f0f83c803fc6f6a9ac5852b53/src/PropertyInfo/EntityProperyInfoExtractor.php#L181-L200
makinacorpus/drupal-calista
src/PropertyInfo/EntityProperyInfoExtractor.php
EntityProperyInfoExtractor.findFieldInstanceFor
private function findFieldInstanceFor($entityType, $entityInfo, $property) { $instances = $this->findFieldInstances($entityType, $entityInfo); if (isset($instances[$property])) { return $instances[$property]; } }
php
private function findFieldInstanceFor($entityType, $entityInfo, $property) { $instances = $this->findFieldInstances($entityType, $entityInfo); if (isset($instances[$property])) { return $instances[$property]; } }
Guess the field instance for a single property of the given entity type @param string $entityType @param array $entityInfo @param string $property @return null|array
https://github.com/makinacorpus/drupal-calista/blob/cceb6b975fc3e80f0f83c803fc6f6a9ac5852b53/src/PropertyInfo/EntityProperyInfoExtractor.php#L211-L218
makinacorpus/drupal-calista
src/PropertyInfo/EntityProperyInfoExtractor.php
EntityProperyInfoExtractor.getShortDescription
public function getShortDescription($class, $property, array $context = []) { list($entityType, $entityInfo) = $this->getEntityTypeInfo($class); if (!$entityType) { return; } // Property lookup will be faster, do it before trying with fields if (isset($entityInfo['base table field types'][$property])) { return $this->getLabelFor($property); } $instance = $this->findFieldInstanceFor($entityType, $entityInfo, $property); if ($instance) { return isset($instance['label']) ? $instance['label'] : $property; } }
php
public function getShortDescription($class, $property, array $context = []) { list($entityType, $entityInfo) = $this->getEntityTypeInfo($class); if (!$entityType) { return; } // Property lookup will be faster, do it before trying with fields if (isset($entityInfo['base table field types'][$property])) { return $this->getLabelFor($property); } $instance = $this->findFieldInstanceFor($entityType, $entityInfo, $property); if ($instance) { return isset($instance['label']) ? $instance['label'] : $property; } }
{@inheritdoc}
https://github.com/makinacorpus/drupal-calista/blob/cceb6b975fc3e80f0f83c803fc6f6a9ac5852b53/src/PropertyInfo/EntityProperyInfoExtractor.php#L223-L241
makinacorpus/drupal-calista
src/PropertyInfo/EntityProperyInfoExtractor.php
EntityProperyInfoExtractor.getProperties
public function getProperties($class, array $context = []) { list($entityType, $entityInfo) = $this->getEntityTypeInfo($class); if (!$entityType) { return; } $ret = []; // Add defined properties from the entity info array if (isset($entityInfo['base table field types'])) { foreach ($entityInfo['base table field types'] as $name => $type) { $ret[$name] = $name; } } // Add field properties, since Drupal does not differenciate entity // bundles using different class for different object, we are just // gonna give the whole field list foreach ($this->findFieldInstances($entityType, $entityInfo) as $instance) { if (isset($instance['label'])) { $ret[$name] = $instance['label']; } else { $ret[$name] = $name; } } // Because Drupal never stop to amaze me, it calls the accessors with // the same name as properties, and sometime they're not even accessors // and have a different business meaning, await for required arguments, // then explode when the PropertyAccessor attempt to call the method // as if it was a simple accessor. if ('node' === $entityType || 'user' === $entityType) { unset($ret['access']); } return $ret; }
php
public function getProperties($class, array $context = []) { list($entityType, $entityInfo) = $this->getEntityTypeInfo($class); if (!$entityType) { return; } $ret = []; // Add defined properties from the entity info array if (isset($entityInfo['base table field types'])) { foreach ($entityInfo['base table field types'] as $name => $type) { $ret[$name] = $name; } } // Add field properties, since Drupal does not differenciate entity // bundles using different class for different object, we are just // gonna give the whole field list foreach ($this->findFieldInstances($entityType, $entityInfo) as $instance) { if (isset($instance['label'])) { $ret[$name] = $instance['label']; } else { $ret[$name] = $name; } } // Because Drupal never stop to amaze me, it calls the accessors with // the same name as properties, and sometime they're not even accessors // and have a different business meaning, await for required arguments, // then explode when the PropertyAccessor attempt to call the method // as if it was a simple accessor. if ('node' === $entityType || 'user' === $entityType) { unset($ret['access']); } return $ret; }
{@inheritdoc}
https://github.com/makinacorpus/drupal-calista/blob/cceb6b975fc3e80f0f83c803fc6f6a9ac5852b53/src/PropertyInfo/EntityProperyInfoExtractor.php#L246-L284
makinacorpus/drupal-calista
src/PropertyInfo/EntityProperyInfoExtractor.php
EntityProperyInfoExtractor.getTypes
public function getTypes($class, $property, array $context = []) { list($entityType, $entityInfo) = $this->getEntityTypeInfo($class); if (!$entityType) { return; } // Property lookup will be faster, do it before trying with fields if (isset($entityInfo['base table field types'][$property])) { // We need to use the schema API here, and a bit of guessing return [$this->schemaApiTypeToPropertyInfoType($entityInfo['base table field types'][$property])]; } $instance = $this->findFieldInstanceFor($entityType, $entityInfo, $property); if ($instance) { return new Type(Type::BUILTIN_TYPE_ARRAY, true, null, false); } }
php
public function getTypes($class, $property, array $context = []) { list($entityType, $entityInfo) = $this->getEntityTypeInfo($class); if (!$entityType) { return; } // Property lookup will be faster, do it before trying with fields if (isset($entityInfo['base table field types'][$property])) { // We need to use the schema API here, and a bit of guessing return [$this->schemaApiTypeToPropertyInfoType($entityInfo['base table field types'][$property])]; } $instance = $this->findFieldInstanceFor($entityType, $entityInfo, $property); if ($instance) { return new Type(Type::BUILTIN_TYPE_ARRAY, true, null, false); } }
{@inheritdoc}
https://github.com/makinacorpus/drupal-calista/blob/cceb6b975fc3e80f0f83c803fc6f6a9ac5852b53/src/PropertyInfo/EntityProperyInfoExtractor.php#L296-L315
schpill/thin
src/Messages.php
Messages.unique
protected function unique($key, $message) { return !isset($this->messages[$key]) || !Arrays::in($message, $this->messages[$key]); }
php
protected function unique($key, $message) { return !isset($this->messages[$key]) || !Arrays::in($message, $this->messages[$key]); }
Determine if a key and message combination already exists. @param string $key @param string $message @return bool
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Messages.php#L54-L57
schpill/thin
src/Messages.php
Messages.get
public function get($key, $format = null) { $format = (null === $format) ? $this->format : $format; if (Arrays::exists($key, $this->messages)) { return $this->transform($this->messages[$key], $format); } return array(); }
php
public function get($key, $format = null) { $format = (null === $format) ? $this->format : $format; if (Arrays::exists($key, $this->messages)) { return $this->transform($this->messages[$key], $format); } return array(); }
Get all of the messages from the container for a given key. <code> // Echo all of the messages for the e-mail attribute echo $messages->get('email'); // Format all of the messages for the e-mail attribute echo $messages->get('email', '<p>:message</p>'); </code> @param string $key @param string $format @return array
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Messages.php#L135-L144
schpill/thin
src/Messages.php
Messages.transform
protected function transform($messages, $format) { $messages = (array) $messages; foreach ($messages as $key => &$message) { $message = repl(':message', $message, $format); } return $messages; }
php
protected function transform($messages, $format) { $messages = (array) $messages; foreach ($messages as $key => &$message) { $message = repl(':message', $message, $format); } return $messages; }
Format an array of messages. @param array $messages @param string $format @return array
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Messages.php#L180-L189
salernolabs/camelize
src/Camel.php
Camel.camelize
public function camelize($input) { $input = trim($input); if (empty($input)) { throw new \Exception("Can not camelize an empty string."); } $output = ''; $capitalizeNext = $this->shouldCapitalizeFirstLetter; for ($i = 0; $i < mb_strlen($input); ++$i) { $character = mb_substr($input, $i, 1); if ($character == '_' || $character == ' ') { $capitalizeNext = true; } else { if ($capitalizeNext) { $capitalizeNext = false; $output .= mb_strtoupper($character); } else { $output .= mb_strtolower($character); } } } return $output; }
php
public function camelize($input) { $input = trim($input); if (empty($input)) { throw new \Exception("Can not camelize an empty string."); } $output = ''; $capitalizeNext = $this->shouldCapitalizeFirstLetter; for ($i = 0; $i < mb_strlen($input); ++$i) { $character = mb_substr($input, $i, 1); if ($character == '_' || $character == ' ') { $capitalizeNext = true; } else { if ($capitalizeNext) { $capitalizeNext = false; $output .= mb_strtoupper($character); } else { $output .= mb_strtolower($character); } } } return $output; }
Camel Case a String @param $input @return string
https://github.com/salernolabs/camelize/blob/6098e9827fd21509592fc7062b653582d0dd00d1/src/Camel.php#L37-L72
brick/validation
src/Validator/DateValidator.php
DateValidator.validate
protected function validate(string $value) : void { if (preg_match('/^([0-9]{4})\-([0-9]{2})\-([0-9]{2})$/', $value, $matches) !== 1) { $this->addFailureMessage('validator.date.invalid-format'); return; } $year = (int) $matches[1]; $month = (int) $matches[2]; $day = (int) $matches[3]; if (! $this->isDateValid($year, $month, $day)) { $this->addFailureMessage('validator.date.invalid-date'); } }
php
protected function validate(string $value) : void { if (preg_match('/^([0-9]{4})\-([0-9]{2})\-([0-9]{2})$/', $value, $matches) !== 1) { $this->addFailureMessage('validator.date.invalid-format'); return; } $year = (int) $matches[1]; $month = (int) $matches[2]; $day = (int) $matches[3]; if (! $this->isDateValid($year, $month, $day)) { $this->addFailureMessage('validator.date.invalid-date'); } }
{@inheritdoc}
https://github.com/brick/validation/blob/b33593f75df80530417007bde97c4772807563ab/src/Validator/DateValidator.php#L28-L43
brick/validation
src/Validator/DateValidator.php
DateValidator.isDateValid
private function isDateValid(int $year, int $month, int $day) : bool { if ($day === 0) { return false; } switch ($month) { case 2: $days = $this->isLeapYear($year) ? 29 : 28; break; case 4: case 6: case 9: case 11: $days = 30; break; case 1: case 3: case 5: case 7: case 8: case 10: case 12: $days = 31; break; default: return false; } return $day <= $days; }
php
private function isDateValid(int $year, int $month, int $day) : bool { if ($day === 0) { return false; } switch ($month) { case 2: $days = $this->isLeapYear($year) ? 29 : 28; break; case 4: case 6: case 9: case 11: $days = 30; break; case 1: case 3: case 5: case 7: case 8: case 10: case 12: $days = 31; break; default: return false; } return $day <= $days; }
@param int $year @param int $month @param int $day @return bool
https://github.com/brick/validation/blob/b33593f75df80530417007bde97c4772807563ab/src/Validator/DateValidator.php#L52-L85