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
nyeholt/silverstripe-performant
code/services/SiteDataService.php
SiteDataService.createMenuNode
public function createMenuNode($data) { $cls = $this->itemClass; $node = $cls::create($data, $this); $this->items[$node->ID] = $node; return $node; }
php
public function createMenuNode($data) { $cls = $this->itemClass; $node = $cls::create($data, $this); $this->items[$node->ID] = $node; return $node; }
Creates a menu item from an array of data @param array $data @returns MenuItem
https://github.com/nyeholt/silverstripe-performant/blob/2c9d2570ddf4a43ced38487184da4de453a4863c/code/services/SiteDataService.php#L235-L240
airbornfoxx/commandcenter
src/Flyingfoxx/CommandCenter/MainCommandTranslator.php
MainCommandTranslator.toHandler
public function toHandler($command) { $class = get_class($command); $offset = ($this->positionAt('Command', $class)) ?: $this->positionAt('Request', $class); $handlerClass = substr_replace($class, 'Handler', $offset); if (!class_exists($handlerClass)) { $message = "Command handler [$handlerClass] does not exist."; throw new HandlerNotRegisteredException($message); } return $handlerClass; }
php
public function toHandler($command) { $class = get_class($command); $offset = ($this->positionAt('Command', $class)) ?: $this->positionAt('Request', $class); $handlerClass = substr_replace($class, 'Handler', $offset); if (!class_exists($handlerClass)) { $message = "Command handler [$handlerClass] does not exist."; throw new HandlerNotRegisteredException($message); } return $handlerClass; }
Translate a command to its respective handler. @param $command @return mixed @throws HandlerNotRegisteredException
https://github.com/airbornfoxx/commandcenter/blob/ee4f8d0981c69f8cd3410793988def4d809fdaa6/src/Flyingfoxx/CommandCenter/MainCommandTranslator.php#L19-L31
airbornfoxx/commandcenter
src/Flyingfoxx/CommandCenter/MainCommandTranslator.php
MainCommandTranslator.toValidator
public function toValidator($command) { $class = get_class($command); $offset = ($this->positionAt('Command', $class)) ?: $this->positionAt('Request', $class); return substr_replace($class, 'Validator', $offset); }
php
public function toValidator($command) { $class = get_class($command); $offset = ($this->positionAt('Command', $class)) ?: $this->positionAt('Request', $class); return substr_replace($class, 'Validator', $offset); }
Translate a command to its respective validator. @param $command @return mixed
https://github.com/airbornfoxx/commandcenter/blob/ee4f8d0981c69f8cd3410793988def4d809fdaa6/src/Flyingfoxx/CommandCenter/MainCommandTranslator.php#L39-L45
ekyna/AdminBundle
Settings/GeneralSettingsSchema.php
GeneralSettingsSchema.buildForm
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('site_name', 'text', [ 'label' => 'ekyna_admin.settings.general.site_name', 'constraints' => [ new Constraints\NotBlank() ] ]) ->add('admin_name', 'text', [ 'label' => 'ekyna_admin.settings.general.admin_name', 'constraints' => [ new Constraints\NotBlank() ] ]) ->add('admin_email', 'text', [ 'label' => 'ekyna_admin.settings.general.admin_email', 'constraints' => [ new Constraints\NotBlank(), new Constraints\Email(), ] ]) ->add('site_address', new SiteAddressType(), [ 'label' => 'ekyna_admin.settings.general.siteaddress', 'cascade_validation' => true, ]) ; }
php
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('site_name', 'text', [ 'label' => 'ekyna_admin.settings.general.site_name', 'constraints' => [ new Constraints\NotBlank() ] ]) ->add('admin_name', 'text', [ 'label' => 'ekyna_admin.settings.general.admin_name', 'constraints' => [ new Constraints\NotBlank() ] ]) ->add('admin_email', 'text', [ 'label' => 'ekyna_admin.settings.general.admin_email', 'constraints' => [ new Constraints\NotBlank(), new Constraints\Email(), ] ]) ->add('site_address', new SiteAddressType(), [ 'label' => 'ekyna_admin.settings.general.siteaddress', 'cascade_validation' => true, ]) ; }
{@inheritdoc}
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Settings/GeneralSettingsSchema.php#L41-L68
digipolisgent/robo-digipolis-deploy
src/Commands/DatabaseBackup.php
DatabaseBackup.digipolisDatabaseBackup
public function digipolisDatabaseBackup($database = 'default', $opts = [ 'file-system-config|fsconf' => null, 'database-config|dbconf' => null, 'compression|c' => 'gzip', 'destination|d' => null, 'destination-type|dtype' => 'local', ]) { if (is_callable([$this, 'readProperties'])) { $this->readProperties(); } $destination = $opts['destination'] ? $opts['destination'] : realpath(getcwd()) . '/project.tar.gz'; if (!$opts['file-system-config']) { $opts['file-system-config'] = [ $opts['destination-type'] => [ 'type' => ucfirst($opts['destination-type']), 'root' => realpath(dirname($destination)), ], ]; $destination = basename($destination); } return $this->createDbTask('taskDatabaseBackup', $database, $opts) ->destination($destination, $opts['destination-type']) ->run(); }
php
public function digipolisDatabaseBackup($database = 'default', $opts = [ 'file-system-config|fsconf' => null, 'database-config|dbconf' => null, 'compression|c' => 'gzip', 'destination|d' => null, 'destination-type|dtype' => 'local', ]) { if (is_callable([$this, 'readProperties'])) { $this->readProperties(); } $destination = $opts['destination'] ? $opts['destination'] : realpath(getcwd()) . '/project.tar.gz'; if (!$opts['file-system-config']) { $opts['file-system-config'] = [ $opts['destination-type'] => [ 'type' => ucfirst($opts['destination-type']), 'root' => realpath(dirname($destination)), ], ]; $destination = basename($destination); } return $this->createDbTask('taskDatabaseBackup', $database, $opts) ->destination($destination, $opts['destination-type']) ->run(); }
Command digipolis:database-backup. @param string $database The database command argument. @param array $opts The command options.
https://github.com/digipolisgent/robo-digipolis-deploy/blob/fafa8967d98ed4d3f2265b17f4b1abe53bf0b5ab/src/Commands/DatabaseBackup.php#L19-L45
antaresproject/translations
src/Http/Breadcrumb/Breadcrumb.php
Breadcrumb.onTranslationList
public function onTranslationList() { $this->breadcrumbs->register('translations', function($breadcrumbs) { $breadcrumbs->push('Translations', handles('antares::translations/index/' . area())); }); $this->shareOnView('translations'); }
php
public function onTranslationList() { $this->breadcrumbs->register('translations', function($breadcrumbs) { $breadcrumbs->push('Translations', handles('antares::translations/index/' . area())); }); $this->shareOnView('translations'); }
on translations list
https://github.com/antaresproject/translations/blob/63097aeb97f18c5aeeef7dcf15f0c67959951685/src/Http/Breadcrumb/Breadcrumb.php#L33-L40
antaresproject/translations
src/Http/Breadcrumb/Breadcrumb.php
Breadcrumb.onLanguageAdd
public function onLanguageAdd() { $this->onTranslationList(); $this->breadcrumbs->register('languages', function($breadcrumbs) { $breadcrumbs->parent('translations'); $breadcrumbs->push('Languages', handles('antares::translations/languages/index')); }); $this->breadcrumbs->register('language-add', function($breadcrumbs) { $breadcrumbs->parent('languages'); $breadcrumbs->push('Language add'); }); $this->shareOnView('language-add'); }
php
public function onLanguageAdd() { $this->onTranslationList(); $this->breadcrumbs->register('languages', function($breadcrumbs) { $breadcrumbs->parent('translations'); $breadcrumbs->push('Languages', handles('antares::translations/languages/index')); }); $this->breadcrumbs->register('language-add', function($breadcrumbs) { $breadcrumbs->parent('languages'); $breadcrumbs->push('Language add'); }); $this->shareOnView('language-add'); }
on language add
https://github.com/antaresproject/translations/blob/63097aeb97f18c5aeeef7dcf15f0c67959951685/src/Http/Breadcrumb/Breadcrumb.php#L45-L57
antaresproject/translations
src/Http/Breadcrumb/Breadcrumb.php
Breadcrumb.onImportTranslations
public function onImportTranslations() { $this->onTranslationList(); $this->breadcrumbs->register('translations-import', function($breadcrumbs) { $breadcrumbs->parent('translations'); $breadcrumbs->push('Import translations'); }); $this->shareOnView('translations-import'); }
php
public function onImportTranslations() { $this->onTranslationList(); $this->breadcrumbs->register('translations-import', function($breadcrumbs) { $breadcrumbs->parent('translations'); $breadcrumbs->push('Import translations'); }); $this->shareOnView('translations-import'); }
on import translations
https://github.com/antaresproject/translations/blob/63097aeb97f18c5aeeef7dcf15f0c67959951685/src/Http/Breadcrumb/Breadcrumb.php#L62-L70
antaresproject/translations
src/Http/Breadcrumb/Breadcrumb.php
Breadcrumb.onLanguagesList
public function onLanguagesList() { $this->breadcrumbs->register('translations', function($breadcrumbs) { $breadcrumbs->push('Translations', handles('antares::translations/index/' . area()), ['force_link' => true]); }); $this->shareOnView('translations'); }
php
public function onLanguagesList() { $this->breadcrumbs->register('translations', function($breadcrumbs) { $breadcrumbs->push('Translations', handles('antares::translations/index/' . area()), ['force_link' => true]); }); $this->shareOnView('translations'); }
On languages list
https://github.com/antaresproject/translations/blob/63097aeb97f18c5aeeef7dcf15f0c67959951685/src/Http/Breadcrumb/Breadcrumb.php#L75-L82
schpill/thin
src/Helpers/Arraytoxml.php
Arraytoxml.init
public static function init($version = '1.0', $encoding = 'UTF-8', $formatOutput = true) { self::$xml = new \DomDocument($version, $encoding); self::$xml->formatOutput = $formatOutput; self::$encoding = $encoding; }
php
public static function init($version = '1.0', $encoding = 'UTF-8', $formatOutput = true) { self::$xml = new \DomDocument($version, $encoding); self::$xml->formatOutput = $formatOutput; self::$encoding = $encoding; }
Initialize the root XML node [optional] @param $version @param $encoding @param $formatOutput
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Helpers/Arraytoxml.php#L18-L23
schpill/thin
src/Helpers/Arraytoxml.php
Arraytoxml.&
public static function &create($nodeName, $arr = array()) { $xml = self::getXmlRoot(); $xml->appendChild(self::convert($nodeName, $arr)); self::$xml = null; // clear the xml node in the class for 2nd time use. return $xml; }
php
public static function &create($nodeName, $arr = array()) { $xml = self::getXmlRoot(); $xml->appendChild(self::convert($nodeName, $arr)); self::$xml = null; // clear the xml node in the class for 2nd time use. return $xml; }
Convert an Array to XML @param string $nodeName - name of the root node to be converted @param array $arr - aray to be converterd @return DomDocument
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Helpers/Arraytoxml.php#L31-L39
schpill/thin
src/Helpers/Arraytoxml.php
Arraytoxml.&
private static function &convert($nodeName, $arr = array()) { //print_arr($nodeName); $xml = self::getXmlRoot(); $node = $xml->createElement($nodeName); if (Arrays::is($arr)){ // get the attributes first.; if (isset($arr['@attributes'])) { foreach ($arr['@attributes'] as $key => $value) { if (!self::isValidTagName($key)) { throw new \Exception('[Arraytoxml] Illegal character in attribute name. attribute: ' . $key . ' in node: ' . $nodeName); } $node->setAttribute($key, self::boolToString($value)); } unset($arr['@attributes']); //remove the key from the array once done. } // check if it has a value stored in @value, if yes store the value and return // else check if its directly stored as string if (isset($arr['@value'])) { $node->appendChild($xml->createTextNode(self::boolToString($arr['@value']))); unset($arr['@value']); //remove the key from the array once done. //return from recursion, as a note with value cannot have child nodes. return $node; } elseif (isset($arr['@cdata'])) { $node->appendChild($xml->createCDATASection(self::boolToString($arr['@cdata']))); unset($arr['@cdata']); //remove the key from the array once done. //return from recursion, as a note with cdata cannot have child nodes. return $node; } } //create subnodes using recursion if (Arrays::is($arr)) { // recurse to get the node for that key foreach ($arr as $key => $value) { if(!self::isValidTagName($key)) { throw new \Exception('[Arraytoxml] Illegal character in tag name. tag: '.$key.' in node: '.$nodeName); } if (Arrays::is($value) && is_numeric(key($value))) { // MORE THAN ONE NODE OF ITS KIND; // if the new array is numeric index, means it is array of nodes of the same kind // it should follow the parent key name foreach($value as $k => $v){ $node->appendChild(self::convert($key, $v)); } } else { // ONLY ONE NODE OF ITS KIND $node->appendChild(self::convert($key, $value)); } unset($arr[$key]); //remove the key from the array once done. } } // after we are done with all the keys in the array (if it is one) // we check if it has any text value, if yes, append it. if (!Arrays::is($arr)) { $node->appendChild($xml->createTextNode(self::boolToString($arr))); } return $node; }
php
private static function &convert($nodeName, $arr = array()) { //print_arr($nodeName); $xml = self::getXmlRoot(); $node = $xml->createElement($nodeName); if (Arrays::is($arr)){ // get the attributes first.; if (isset($arr['@attributes'])) { foreach ($arr['@attributes'] as $key => $value) { if (!self::isValidTagName($key)) { throw new \Exception('[Arraytoxml] Illegal character in attribute name. attribute: ' . $key . ' in node: ' . $nodeName); } $node->setAttribute($key, self::boolToString($value)); } unset($arr['@attributes']); //remove the key from the array once done. } // check if it has a value stored in @value, if yes store the value and return // else check if its directly stored as string if (isset($arr['@value'])) { $node->appendChild($xml->createTextNode(self::boolToString($arr['@value']))); unset($arr['@value']); //remove the key from the array once done. //return from recursion, as a note with value cannot have child nodes. return $node; } elseif (isset($arr['@cdata'])) { $node->appendChild($xml->createCDATASection(self::boolToString($arr['@cdata']))); unset($arr['@cdata']); //remove the key from the array once done. //return from recursion, as a note with cdata cannot have child nodes. return $node; } } //create subnodes using recursion if (Arrays::is($arr)) { // recurse to get the node for that key foreach ($arr as $key => $value) { if(!self::isValidTagName($key)) { throw new \Exception('[Arraytoxml] Illegal character in tag name. tag: '.$key.' in node: '.$nodeName); } if (Arrays::is($value) && is_numeric(key($value))) { // MORE THAN ONE NODE OF ITS KIND; // if the new array is numeric index, means it is array of nodes of the same kind // it should follow the parent key name foreach($value as $k => $v){ $node->appendChild(self::convert($key, $v)); } } else { // ONLY ONE NODE OF ITS KIND $node->appendChild(self::convert($key, $value)); } unset($arr[$key]); //remove the key from the array once done. } } // after we are done with all the keys in the array (if it is one) // we check if it has any text value, if yes, append it. if (!Arrays::is($arr)) { $node->appendChild($xml->createTextNode(self::boolToString($arr))); } return $node; }
Convert an Array to XML @param string $nodeName - name of the root node to be converted @param array $arr - aray to be converterd @return DOMNode
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Helpers/Arraytoxml.php#L47-L116
schpill/thin
src/Helpers/Arraytoxml.php
Arraytoxml.boolToString
private static function boolToString($v) { //convert boolean to text value. $v = $v === true ? 'true' : $v; $v = $v === false ? 'false' : $v; return $v; }
php
private static function boolToString($v) { //convert boolean to text value. $v = $v === true ? 'true' : $v; $v = $v === false ? 'false' : $v; return $v; }
/* Get string representation of boolean value
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Helpers/Arraytoxml.php#L133-L140
WellCommerce/CatalogBundle
Controller/Admin/AttributeController.php
AttributeController.ajaxIndexAction
public function ajaxIndexAction(Request $request): Response { if (!$request->isXmlHttpRequest()) { return $this->redirectToAction('index'); } $attributeGroupId = (int)$request->request->get('id'); $attributeGroup = $this->getManager()->findAttributeGroup($attributeGroupId); return $this->jsonResponse([ 'attributes' => $this->getManager()->getRepository()->getAttributeSet($attributeGroup), ]); }
php
public function ajaxIndexAction(Request $request): Response { if (!$request->isXmlHttpRequest()) { return $this->redirectToAction('index'); } $attributeGroupId = (int)$request->request->get('id'); $attributeGroup = $this->getManager()->findAttributeGroup($attributeGroupId); return $this->jsonResponse([ 'attributes' => $this->getManager()->getRepository()->getAttributeSet($attributeGroup), ]); }
Ajax action for listing attributes in variants editor @param Request $request @return Response
https://github.com/WellCommerce/CatalogBundle/blob/b1809190298f6c6c04c472dbfd763c1ad0b68630/Controller/Admin/AttributeController.php#L35-L47
WellCommerce/CatalogBundle
Controller/Admin/AttributeController.php
AttributeController.ajaxAddAction
public function ajaxAddAction(Request $request): Response { if (!$request->isXmlHttpRequest()) { return $this->redirectToAction('index'); } $attributeName = $request->request->get('name'); $attributeGroupId = (int)$request->request->get('set'); try { $attribute = $this->getManager()->createAttribute($attributeName, $attributeGroupId); return $this->jsonResponse([ 'id' => $attribute->getId(), ]); } catch (\Exception $e) { return $this->jsonResponse([ 'error' => $e->getMessage(), ]); } }
php
public function ajaxAddAction(Request $request): Response { if (!$request->isXmlHttpRequest()) { return $this->redirectToAction('index'); } $attributeName = $request->request->get('name'); $attributeGroupId = (int)$request->request->get('set'); try { $attribute = $this->getManager()->createAttribute($attributeName, $attributeGroupId); return $this->jsonResponse([ 'id' => $attribute->getId(), ]); } catch (\Exception $e) { return $this->jsonResponse([ 'error' => $e->getMessage(), ]); } }
Adds new attribute value using ajax request @param Request $request @return Response
https://github.com/WellCommerce/CatalogBundle/blob/b1809190298f6c6c04c472dbfd763c1ad0b68630/Controller/Admin/AttributeController.php#L56-L78
twistor/flysystem-memory-adapter
src/MemoryAdapter.php
MemoryAdapter.createFromPath
public static function createFromPath($path) { if (!is_dir($path) || !is_readable($path)) { throw new \LogicException(sprintf('%s does not exist or is not readable.', $path)); } return static::createFromFilesystem(new Filesystem(new Local($path))); }
php
public static function createFromPath($path) { if (!is_dir($path) || !is_readable($path)) { throw new \LogicException(sprintf('%s does not exist or is not readable.', $path)); } return static::createFromFilesystem(new Filesystem(new Local($path))); }
Creates a Memory adapter from a filesystem folder. @param string $path The path to the folder. @return MemoryAdapter A new memory adapter.
https://github.com/twistor/flysystem-memory-adapter/blob/614f184d855135c1d55b1a579feabaf577de62b1/src/MemoryAdapter.php#L37-L44
twistor/flysystem-memory-adapter
src/MemoryAdapter.php
MemoryAdapter.createFromFilesystem
public static function createFromFilesystem(FilesystemInterface $filesystem) { $filesystem->addPlugin(new ListWith()); $adapter = new static(); $config = new Config(); foreach ($filesystem->listWith(['timestamp', 'visibility'], '', true) as $meta) { if ($meta['type'] === 'dir') { $adapter->createDir($meta['path'], $config); continue; } $adapter->write($meta['path'], (string) $filesystem->read($meta['path']), $config); $adapter->setVisibility($meta['path'], $meta['visibility']); $adapter->setTimestamp($meta['path'], $meta['timestamp']); } return $adapter; }
php
public static function createFromFilesystem(FilesystemInterface $filesystem) { $filesystem->addPlugin(new ListWith()); $adapter = new static(); $config = new Config(); foreach ($filesystem->listWith(['timestamp', 'visibility'], '', true) as $meta) { if ($meta['type'] === 'dir') { $adapter->createDir($meta['path'], $config); continue; } $adapter->write($meta['path'], (string) $filesystem->read($meta['path']), $config); $adapter->setVisibility($meta['path'], $meta['visibility']); $adapter->setTimestamp($meta['path'], $meta['timestamp']); } return $adapter; }
Creates a Memory adapter from a Flysystem filesystem. @param FilesystemInterface $filesystem The Flysystem filesystem. @return self A new memory adapter.
https://github.com/twistor/flysystem-memory-adapter/blob/614f184d855135c1d55b1a579feabaf577de62b1/src/MemoryAdapter.php#L53-L72
twistor/flysystem-memory-adapter
src/MemoryAdapter.php
MemoryAdapter.copy
public function copy($path, $newpath) { // Make sure all the destination sub-directories exist. if (!$this->ensureSubDirs($newpath)) { return false; } $this->storage[$newpath] = $this->storage[$path]; return true; }
php
public function copy($path, $newpath) { // Make sure all the destination sub-directories exist. if (!$this->ensureSubDirs($newpath)) { return false; } $this->storage[$newpath] = $this->storage[$path]; return true; }
{@inheritdoc}
https://github.com/twistor/flysystem-memory-adapter/blob/614f184d855135c1d55b1a579feabaf577de62b1/src/MemoryAdapter.php#L77-L87
twistor/flysystem-memory-adapter
src/MemoryAdapter.php
MemoryAdapter.createDir
public function createDir($dirname, Config $config) { // Ensure sub-directories. if ($this->hasFile($dirname) || $dirname !== '' && !$this->ensureSubDirs($dirname, $config)) { return false; } $this->storage[$dirname]['type'] = 'dir'; return $this->getMetadata($dirname); }
php
public function createDir($dirname, Config $config) { // Ensure sub-directories. if ($this->hasFile($dirname) || $dirname !== '' && !$this->ensureSubDirs($dirname, $config)) { return false; } $this->storage[$dirname]['type'] = 'dir'; return $this->getMetadata($dirname); }
{@inheritdoc}
https://github.com/twistor/flysystem-memory-adapter/blob/614f184d855135c1d55b1a579feabaf577de62b1/src/MemoryAdapter.php#L92-L102
twistor/flysystem-memory-adapter
src/MemoryAdapter.php
MemoryAdapter.deleteDir
public function deleteDir($dirname) { if (!$this->hasDirectory($dirname)) { return false; } $this->emptyDirectory($dirname); return $this->deletePath($dirname); }
php
public function deleteDir($dirname) { if (!$this->hasDirectory($dirname)) { return false; } $this->emptyDirectory($dirname); return $this->deletePath($dirname); }
{@inheritdoc}
https://github.com/twistor/flysystem-memory-adapter/blob/614f184d855135c1d55b1a579feabaf577de62b1/src/MemoryAdapter.php#L115-L124
twistor/flysystem-memory-adapter
src/MemoryAdapter.php
MemoryAdapter.listContents
public function listContents($directory = '', $recursive = false) { $contents = $this->doListContents($directory, $recursive); $contents = array_values(array_filter($contents, function ($path) { return $path !== ''; })); return array_map(function ($path) { return $this->getMetadata($path); }, $contents); }
php
public function listContents($directory = '', $recursive = false) { $contents = $this->doListContents($directory, $recursive); $contents = array_values(array_filter($contents, function ($path) { return $path !== ''; })); return array_map(function ($path) { return $this->getMetadata($path); }, $contents); }
{@inheritdoc}
https://github.com/twistor/flysystem-memory-adapter/blob/614f184d855135c1d55b1a579feabaf577de62b1/src/MemoryAdapter.php#L177-L188
twistor/flysystem-memory-adapter
src/MemoryAdapter.php
MemoryAdapter.readStream
public function readStream($path) { if (!$result = $this->read($path)) { return false; } $result['stream'] = fopen('php://temp', 'w+b'); fwrite($result['stream'], $result['contents']); rewind($result['stream']); unset($result['contents']); return $result; }
php
public function readStream($path) { if (!$result = $this->read($path)) { return false; } $result['stream'] = fopen('php://temp', 'w+b'); fwrite($result['stream'], $result['contents']); rewind($result['stream']); unset($result['contents']); return $result; }
{@inheritdoc}
https://github.com/twistor/flysystem-memory-adapter/blob/614f184d855135c1d55b1a579feabaf577de62b1/src/MemoryAdapter.php#L201-L213
twistor/flysystem-memory-adapter
src/MemoryAdapter.php
MemoryAdapter.rename
public function rename($path, $newpath) { return $this->copy($path, $newpath) && $this->deletePath($path); }
php
public function rename($path, $newpath) { return $this->copy($path, $newpath) && $this->deletePath($path); }
{@inheritdoc}
https://github.com/twistor/flysystem-memory-adapter/blob/614f184d855135c1d55b1a579feabaf577de62b1/src/MemoryAdapter.php#L218-L221
twistor/flysystem-memory-adapter
src/MemoryAdapter.php
MemoryAdapter.update
public function update($path, $contents, Config $config) { if (!$this->hasFile($path)) { return false; } $this->storage[$path]['contents'] = $contents; $this->storage[$path]['timestamp'] = time(); $this->storage[$path]['size'] = Util::contentSize($contents); $this->storage[$path]['mimetype'] = Util::guessMimeType($path, $contents); if ($visibility = $config->get('visibility')) { $this->setVisibility($path, $visibility); } return $this->getMetadata($path); }
php
public function update($path, $contents, Config $config) { if (!$this->hasFile($path)) { return false; } $this->storage[$path]['contents'] = $contents; $this->storage[$path]['timestamp'] = time(); $this->storage[$path]['size'] = Util::contentSize($contents); $this->storage[$path]['mimetype'] = Util::guessMimeType($path, $contents); if ($visibility = $config->get('visibility')) { $this->setVisibility($path, $visibility); } return $this->getMetadata($path); }
{@inheritdoc}
https://github.com/twistor/flysystem-memory-adapter/blob/614f184d855135c1d55b1a579feabaf577de62b1/src/MemoryAdapter.php#L240-L256
twistor/flysystem-memory-adapter
src/MemoryAdapter.php
MemoryAdapter.write
public function write($path, $contents, Config $config) { if ($this->has($path) || !$this->ensureSubDirs($path, $config)) { return false; } $this->storage[$path]['type'] = 'file'; $this->storage[$path]['visibility'] = AdapterInterface::VISIBILITY_PUBLIC; return $this->update($path, $contents, $config); }
php
public function write($path, $contents, Config $config) { if ($this->has($path) || !$this->ensureSubDirs($path, $config)) { return false; } $this->storage[$path]['type'] = 'file'; $this->storage[$path]['visibility'] = AdapterInterface::VISIBILITY_PUBLIC; return $this->update($path, $contents, $config); }
{@inheritdoc}
https://github.com/twistor/flysystem-memory-adapter/blob/614f184d855135c1d55b1a579feabaf577de62b1/src/MemoryAdapter.php#L261-L271
twistor/flysystem-memory-adapter
src/MemoryAdapter.php
MemoryAdapter.emptyDirectory
protected function emptyDirectory($directory) { foreach ($this->doListContents($directory, true) as $path) { $this->deletePath($path); } }
php
protected function emptyDirectory($directory) { foreach ($this->doListContents($directory, true) as $path) { $this->deletePath($path); } }
Empties a directory. @param string $directory
https://github.com/twistor/flysystem-memory-adapter/blob/614f184d855135c1d55b1a579feabaf577de62b1/src/MemoryAdapter.php#L313-L318
twistor/flysystem-memory-adapter
src/MemoryAdapter.php
MemoryAdapter.ensureSubDirs
protected function ensureSubDirs($directory, Config $config = null) { $config = $config ?: new Config(); return $this->createDir(Util::dirname($directory), $config); }
php
protected function ensureSubDirs($directory, Config $config = null) { $config = $config ?: new Config(); return $this->createDir(Util::dirname($directory), $config); }
Ensures that the sub-directories of a directory exist. @param string $directory The directory. @param Config|null $config Optionl configuration. @return bool True on success, false on failure.
https://github.com/twistor/flysystem-memory-adapter/blob/614f184d855135c1d55b1a579feabaf577de62b1/src/MemoryAdapter.php#L328-L333
twistor/flysystem-memory-adapter
src/MemoryAdapter.php
MemoryAdapter.getFileKeys
protected function getFileKeys($path, array $keys) { if (!$this->hasFile($path)) { return false; } return $this->getKeys($path, $keys); }
php
protected function getFileKeys($path, array $keys) { if (!$this->hasFile($path)) { return false; } return $this->getKeys($path, $keys); }
Returns the keys for a file. @param string $path @param array $keys @return array|false
https://github.com/twistor/flysystem-memory-adapter/blob/614f184d855135c1d55b1a579feabaf577de62b1/src/MemoryAdapter.php#L343-L350
twistor/flysystem-memory-adapter
src/MemoryAdapter.php
MemoryAdapter.getKeys
protected function getKeys($path, array $keys) { if (!$this->has($path)) { return false; } $return = []; foreach ($keys as $key) { if ($key === 'path') { $return[$key] = $path; continue; } $return[$key] = $this->storage[$path][$key]; } return $return; }
php
protected function getKeys($path, array $keys) { if (!$this->has($path)) { return false; } $return = []; foreach ($keys as $key) { if ($key === 'path') { $return[$key] = $path; continue; } $return[$key] = $this->storage[$path][$key]; } return $return; }
Returns the keys for a path. @param string $path @param array $keys @return array|false
https://github.com/twistor/flysystem-memory-adapter/blob/614f184d855135c1d55b1a579feabaf577de62b1/src/MemoryAdapter.php#L360-L377
orchestral/optimize
src/OptimizeServiceProvider.php
OptimizeServiceProvider.registerCommand
protected function registerCommand() { $this->app->singleton('orchestra.commands.optimize', function ($app) { return new OptimizeCommand($app->make('orchestra.optimize')); }); $this->commands('orchestra.commands.optimize'); }
php
protected function registerCommand() { $this->app->singleton('orchestra.commands.optimize', function ($app) { return new OptimizeCommand($app->make('orchestra.optimize')); }); $this->commands('orchestra.commands.optimize'); }
Register the service provider. @return void
https://github.com/orchestral/optimize/blob/fa9a574944f066231bcb5c4a0b779ba00a12958d/src/OptimizeServiceProvider.php#L33-L40
orchestral/optimize
src/OptimizeServiceProvider.php
OptimizeServiceProvider.registerCompiler
protected function registerCompiler() { $this->app->singleton('orchestra.optimize', function ($app) { $files = $app->make('files'); $components = $files->getRequire(__DIR__.'/compile.php'); $path = realpath($app->basePath().'/vendor'); return new Compiler($app->make('config'), $files, $path, $components); }); }
php
protected function registerCompiler() { $this->app->singleton('orchestra.optimize', function ($app) { $files = $app->make('files'); $components = $files->getRequire(__DIR__.'/compile.php'); $path = realpath($app->basePath().'/vendor'); return new Compiler($app->make('config'), $files, $path, $components); }); }
Register the service provider. @return void
https://github.com/orchestral/optimize/blob/fa9a574944f066231bcb5c4a0b779ba00a12958d/src/OptimizeServiceProvider.php#L47-L56
ekyna/AdminBundle
Controller/Resource/SortableTrait.php
SortableTrait.moveUpAction
public function moveUpAction(Request $request) { $context = $this->loadContext($request); $resource = $context->getResource(); $this->isGranted('EDIT', $resource); $this->move($resource, -1); return $this->redirectToReferer($this->generateUrl( $this->config->getRoute('list'), $context->getIdentifiers() )); }
php
public function moveUpAction(Request $request) { $context = $this->loadContext($request); $resource = $context->getResource(); $this->isGranted('EDIT', $resource); $this->move($resource, -1); return $this->redirectToReferer($this->generateUrl( $this->config->getRoute('list'), $context->getIdentifiers() )); }
Move up the resource. @param Request $request @return \Symfony\Component\HttpFoundation\Response
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Controller/Resource/SortableTrait.php#L20-L34
ekyna/AdminBundle
Controller/Resource/SortableTrait.php
SortableTrait.move
protected function move($resource, $movement) { $resource->setPosition($resource->getPosition() + $movement); // TODO use ResourceManager $event = $this->getOperator()->update($resource); $event->toFlashes($this->getFlashBag()); }
php
protected function move($resource, $movement) { $resource->setPosition($resource->getPosition() + $movement); // TODO use ResourceManager $event = $this->getOperator()->update($resource); $event->toFlashes($this->getFlashBag()); }
Move the resource. @param $resource @param $movement
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Controller/Resource/SortableTrait.php#L64-L71
chilimatic/chilimatic-framework
lib/route/map/StrategyFactory.php
StrategyFactory.make
public static function make($type, $config, IFlyWeightParser $parser = null) { switch ($type) { case Map::TYPE_O: return new MapObject($config, $parser); break; case Map::TYPE_F: //return new MFunction($config); break; case Map::TYPE_LF: //return new LambdaFunction($config); break; default: throw new RouteException("Invalid Call type" . __METHOD__); break; } }
php
public static function make($type, $config, IFlyWeightParser $parser = null) { switch ($type) { case Map::TYPE_O: return new MapObject($config, $parser); break; case Map::TYPE_F: //return new MFunction($config); break; case Map::TYPE_LF: //return new LambdaFunction($config); break; default: throw new RouteException("Invalid Call type" . __METHOD__); break; } }
@param $type @param $config @param IFlyWeightParser $parser @return MapClosure|MapFunction|MapObject|mixed
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/route/map/StrategyFactory.php#L18-L34
4devs/serializer
Accessor/Property.php
Property.getValue
public function getValue($object, array $options = [], array $context = []) { $value = null; try { $value = $this->propertyAccessor->getValue($object, $options['property']); } catch (ExceptionInterface $e) { if ($this->logger) { $this->logger->error($e->getMessage(), ['exception' => $e]); } if ($options['strict']) { throw $e; } } return $value; }
php
public function getValue($object, array $options = [], array $context = []) { $value = null; try { $value = $this->propertyAccessor->getValue($object, $options['property']); } catch (ExceptionInterface $e) { if ($this->logger) { $this->logger->error($e->getMessage(), ['exception' => $e]); } if ($options['strict']) { throw $e; } } return $value; }
{@inheritdoc}
https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Accessor/Property.php#L42-L57
4devs/serializer
Accessor/Property.php
Property.setValue
public function setValue(&$object, $value, array $options = [], array $context = []) { $this->propertyAccessor->setValue($object, $options['property'], $value); }
php
public function setValue(&$object, $value, array $options = [], array $context = []) { $this->propertyAccessor->setValue($object, $options['property'], $value); }
{@inheritdoc}
https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Accessor/Property.php#L62-L65
4devs/serializer
Accessor/Property.php
Property.configureOptions
public function configureOptions(OptionsResolver $resolver) { $resolver ->setRequired(['property']) ->setDefined(['strict']) ->setDefaults(['strict' => true]) ->addAllowedTypes('property', ['string', PropertyPathInterface::class]) ->addAllowedTypes('strict', ['boolean']); }
php
public function configureOptions(OptionsResolver $resolver) { $resolver ->setRequired(['property']) ->setDefined(['strict']) ->setDefaults(['strict' => true]) ->addAllowedTypes('property', ['string', PropertyPathInterface::class]) ->addAllowedTypes('strict', ['boolean']); }
{@inheritdoc}
https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Accessor/Property.php#L70-L78
praxisnetau/silverware-navigation
src/Components/AnchorNavigation.php
AnchorNavigation.getCMSFields
public function getCMSFields() { // Obtain Field Objects (from parent): $fields = parent::getCMSFields(); // Create Field Objects: $fields->fieldByName('Root.Options.TitleOptions')->push( CheckboxField::create( 'UseLevelTitle', $this->fieldLabel('UseLevelTitle') ) ); // Answer Field Objects: return $fields; }
php
public function getCMSFields() { // Obtain Field Objects (from parent): $fields = parent::getCMSFields(); // Create Field Objects: $fields->fieldByName('Root.Options.TitleOptions')->push( CheckboxField::create( 'UseLevelTitle', $this->fieldLabel('UseLevelTitle') ) ); // Answer Field Objects: return $fields; }
Answers a list of field objects for the CMS interface. @return FieldList
https://github.com/praxisnetau/silverware-navigation/blob/04e6f3003c2871348d5bba7869d4fc273641627e/src/Components/AnchorNavigation.php#L131-L149
praxisnetau/silverware-navigation
src/Components/AnchorNavigation.php
AnchorNavigation.getTitleText
public function getTitleText() { if ($this->UseLevelTitle && ($page = $this->getCurrentPage(Page::class))) { return $page->MenuTitle; } return parent::getTitleText(); }
php
public function getTitleText() { if ($this->UseLevelTitle && ($page = $this->getCurrentPage(Page::class))) { return $page->MenuTitle; } return parent::getTitleText(); }
Answers the title of the component for the template. @return string
https://github.com/praxisnetau/silverware-navigation/blob/04e6f3003c2871348d5bba7869d4fc273641627e/src/Components/AnchorNavigation.php#L178-L185
praxisnetau/silverware-navigation
src/Components/AnchorNavigation.php
AnchorNavigation.getAnchors
public function getAnchors() { $list = ArrayList::create(); if ($page = $this->getCurrentPage(Page::class)) { $html = HTMLValue::create($page->Content); $anchors = $html->query("//*[@id]"); foreach ($anchors as $anchor) { $list->push( ArrayData::create([ 'Link' => $page->Link(sprintf('#%s', $anchor->getAttribute('id'))), 'Text' => $anchor->textContent ]) ); } } return $list; }
php
public function getAnchors() { $list = ArrayList::create(); if ($page = $this->getCurrentPage(Page::class)) { $html = HTMLValue::create($page->Content); $anchors = $html->query("//*[@id]"); foreach ($anchors as $anchor) { $list->push( ArrayData::create([ 'Link' => $page->Link(sprintf('#%s', $anchor->getAttribute('id'))), 'Text' => $anchor->textContent ]) ); } } return $list; }
Answers an array list of anchors identified within the current page content. @return ArrayList
https://github.com/praxisnetau/silverware-navigation/blob/04e6f3003c2871348d5bba7869d4fc273641627e/src/Components/AnchorNavigation.php#L232-L256
praxisnetau/silverware-navigation
src/Components/AnchorNavigation.php
AnchorNavigation.isDisabled
public function isDisabled() { if ($page = $this->getCurrentPage(Page::class)) { if ($this->hasAnchors()) { return parent::isDisabled(); } } return true; }
php
public function isDisabled() { if ($page = $this->getCurrentPage(Page::class)) { if ($this->hasAnchors()) { return parent::isDisabled(); } } return true; }
Answers true if the object is disabled within the template. @return boolean
https://github.com/praxisnetau/silverware-navigation/blob/04e6f3003c2871348d5bba7869d4fc273641627e/src/Components/AnchorNavigation.php#L273-L284
phPoirot/Client-OAuth2
src/Assertion/AssertByInternalServer.php
AssertByInternalServer.assertToken
function assertToken($tokenStr) { if (false === $token = $this->_accessTokens->findByIdentifier((string) $tokenStr)) throw new exOAuthAccessDenied; $accessToken = new AccessTokenEntity( new HydrateGetters($token) ); return $accessToken; }
php
function assertToken($tokenStr) { if (false === $token = $this->_accessTokens->findByIdentifier((string) $tokenStr)) throw new exOAuthAccessDenied; $accessToken = new AccessTokenEntity( new HydrateGetters($token) ); return $accessToken; }
Validate Authorize Token With OAuth Server note: implement grant extension http request @param string $tokenStr @return iAccessTokenEntity @throws exOAuthAccessDenied Access Denied
https://github.com/phPoirot/Client-OAuth2/blob/8745fd54afbbb185669b9e38b1241ecc8ffc7268/src/Assertion/AssertByInternalServer.php#L42-L52
Etenil/assegai
src/assegai/modules/forms/fields/Field.php
Field.getType
function getType() { if($this->_type) { return $this->_type; } else { $myclass = get_class($this); return strtolower(substr($myclass, strrpos($myclass, '\\') + 1, -5)); } }
php
function getType() { if($this->_type) { return $this->_type; } else { $myclass = get_class($this); return strtolower(substr($myclass, strrpos($myclass, '\\') + 1, -5)); } }
This essentially returns the field's class name without the "Field" part.
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/forms/fields/Field.php#L111-L120
jongpak/prob-handler
src/ParameterMap.php
ParameterMap.getValueBy
public function getValueBy(ParameterInterface $parameter) { if ($this->isExistBy($parameter) === false) { throw new NoBindParameterException('No parameter: ' . (string) $parameter); } return $this->parameters[$parameter->getHash()]; }
php
public function getValueBy(ParameterInterface $parameter) { if ($this->isExistBy($parameter) === false) { throw new NoBindParameterException('No parameter: ' . (string) $parameter); } return $this->parameters[$parameter->getHash()]; }
Get a parameter @param ParameterInterface $parameter @return mixed
https://github.com/jongpak/prob-handler/blob/a4cd03cc5fbb0ddc68dc91a6410ee6b07df7c32b/src/ParameterMap.php#L32-L39
flipbox/relay-salesforce
src/Middleware/Client.php
Client.call
private function call(RequestInterface $request, ResponseInterface $response) { try { $this->info( "SALESFORCE API REQUEST - URI: {uri}, METHOD: {method}, PAYLOAD: {payload}", [ 'uri' => $request->getUri(), 'method' => $request->getMethod(), 'payload' => $request->getBody() ] ); $httpResponse = (new GuzzleHttpClient()) ->send($request); } catch (ClientException $e) { $this->error( "SALESFORCE API EXCEPTION: {exception}", [ 'exception' => $e ] ); $httpResponse = $e->getResponse(); } // Sync responses if ($httpResponse !== null) { $this->info( "SALESFORCE API RESPONSE: {response}", [ 'response' => $httpResponse->getBody() ] ); $httpResponse->getBody()->rewind(); $response = $this->syncResponse($httpResponse, $response); } return $response; }
php
private function call(RequestInterface $request, ResponseInterface $response) { try { $this->info( "SALESFORCE API REQUEST - URI: {uri}, METHOD: {method}, PAYLOAD: {payload}", [ 'uri' => $request->getUri(), 'method' => $request->getMethod(), 'payload' => $request->getBody() ] ); $httpResponse = (new GuzzleHttpClient()) ->send($request); } catch (ClientException $e) { $this->error( "SALESFORCE API EXCEPTION: {exception}", [ 'exception' => $e ] ); $httpResponse = $e->getResponse(); } // Sync responses if ($httpResponse !== null) { $this->info( "SALESFORCE API RESPONSE: {response}", [ 'response' => $httpResponse->getBody() ] ); $httpResponse->getBody()->rewind(); $response = $this->syncResponse($httpResponse, $response); } return $response; }
Call the API @param RequestInterface $request @param ResponseInterface $response @return ResponseInterface
https://github.com/flipbox/relay-salesforce/blob/a06ae43dc8f9149df6468a4a4a82760e39ecd647/src/Middleware/Client.php#L42-L81
inhere/php-library-plus
libs/Asset/AssetPublisher.php
AssetPublisher.publish
public function publish($override = false) { // publish files foreach ($this->publishAssets['files'] as $from => $to) { $this->publishFile($from, $to, $override); } // publish directory foreach ($this->publishAssets['dirs'] as $fromDir => $toDir) { $this->publishDir($fromDir, $toDir, $override); } // no define asset to publish, will publish source-path to publish-path if (!$this->hasAssetToPublish()) { $this->publishDir($this->sourcePath, $this->publishPath, $override); } return $this; }
php
public function publish($override = false) { // publish files foreach ($this->publishAssets['files'] as $from => $to) { $this->publishFile($from, $to, $override); } // publish directory foreach ($this->publishAssets['dirs'] as $fromDir => $toDir) { $this->publishDir($fromDir, $toDir, $override); } // no define asset to publish, will publish source-path to publish-path if (!$this->hasAssetToPublish()) { $this->publishDir($this->sourcePath, $this->publishPath, $override); } return $this; }
target path is {@see $publishPath} + $path ( is param of the method `source($path)` ) @param bool|false $override @return $this @throws FileSystemException
https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Asset/AssetPublisher.php#L154-L172
schpill/thin
src/Navigation/Page/Uri.php
Zend_Navigation_Page_Uri.setUri
public function setUri($uri) { if (null !== $uri && !is_string($uri)) { require_once 'Zend/Navigation/Exception.php'; throw new Zend_Navigation_Exception( 'Invalid argument: $uri must be a string or null'); } $this->_uri = $uri; return $this; }
php
public function setUri($uri) { if (null !== $uri && !is_string($uri)) { require_once 'Zend/Navigation/Exception.php'; throw new Zend_Navigation_Exception( 'Invalid argument: $uri must be a string or null'); } $this->_uri = $uri; return $this; }
Sets page URI @param string $uri page URI, must a string or null @return Zend_Navigation_Page_Uri fluent interface, returns self @throws Zend_Navigation_Exception if $uri is invalid
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page/Uri.php#L53-L63
schpill/thin
src/Navigation/Page/Uri.php
Zend_Navigation_Page_Uri.getHref
public function getHref() { $uri = $this->getUri(); $fragment = $this->getFragment(); if (null !== $fragment) { if ('#' == substr($uri, -1)) { return $uri . $fragment; } else { return $uri . '#' . $fragment; } } return $uri; }
php
public function getHref() { $uri = $this->getUri(); $fragment = $this->getFragment(); if (null !== $fragment) { if ('#' == substr($uri, -1)) { return $uri . $fragment; } else { return $uri . '#' . $fragment; } } return $uri; }
Returns href for this page @return string
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Navigation/Page/Uri.php#L80-L94
kibao/mailcatcher
src/MailCatcher/Connection/GuzzleConnection.php
GuzzleConnection.getMessages
public function getMessages() { try { return $this->guzzle->get('/messages')->send()->json(); } catch (GuzzleException $e) { throw new ConnectionException("", 0, $e); } }
php
public function getMessages() { try { return $this->guzzle->get('/messages')->send()->json(); } catch (GuzzleException $e) { throw new ConnectionException("", 0, $e); } }
{@inheritdoc}
https://github.com/kibao/mailcatcher/blob/8a14a25ac1f95db3c02d8ce3e6c3a4f74e63617f/src/MailCatcher/Connection/GuzzleConnection.php#L49-L56
kibao/mailcatcher
src/MailCatcher/Connection/GuzzleConnection.php
GuzzleConnection.getMessage
public function getMessage($id) { try { return $this->guzzle->get('/messages/' . $id . '.json')->send()->json(); } catch (GuzzleException $e) { throw new ConnectionException("", 0, $e); } }
php
public function getMessage($id) { try { return $this->guzzle->get('/messages/' . $id . '.json')->send()->json(); } catch (GuzzleException $e) { throw new ConnectionException("", 0, $e); } }
{@inheritdoc}
https://github.com/kibao/mailcatcher/blob/8a14a25ac1f95db3c02d8ce3e6c3a4f74e63617f/src/MailCatcher/Connection/GuzzleConnection.php#L61-L68
Synapse-Cmf/synapse-cmf
src/Synapse/Page/Bundle/Action/Page/CreateAction.php
CreateAction.resolve
public function resolve() { $this->page ->setName($this->name) ->setOnline(!empty($this->online)) ->setTitle($this->title) ->setMeta(array('title' => $this->title)) ->setPath($this->getFullPath()) ; $this->assertEntityIsValid($this->page, array('Page', 'creation')); $this->fireEvent( PageEvents::PAGE_CREATED, new PageEvent($this->page, $this) ); return $this->page; }
php
public function resolve() { $this->page ->setName($this->name) ->setOnline(!empty($this->online)) ->setTitle($this->title) ->setMeta(array('title' => $this->title)) ->setPath($this->getFullPath()) ; $this->assertEntityIsValid($this->page, array('Page', 'creation')); $this->fireEvent( PageEvents::PAGE_CREATED, new PageEvent($this->page, $this) ); return $this->page; }
Page creation method. @return Page
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Page/Bundle/Action/Page/CreateAction.php#L62-L80
Synapse-Cmf/synapse-cmf
src/Synapse/Page/Bundle/Action/Page/CreateAction.php
CreateAction.generateFullPath
protected function generateFullPath() { return $this->fullPath = $this->pathGenerator ->generatePath($this->page, $this->path ?: '') ; }
php
protected function generateFullPath() { return $this->fullPath = $this->pathGenerator ->generatePath($this->page, $this->path ?: '') ; }
Generate page full path. @return string
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Page/Bundle/Action/Page/CreateAction.php#L136-L141
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Abstract/Send.php
EbayEnterprise_Order_Model_Abstract_Send._checkTypes
protected function _checkTypes( IBidirectionalApi $api, IPayload $request, EbayEnterprise_Order_Helper_Data $orderHelper, Radial_Core_Model_Config_Registry $orderCfg, Radial_Core_Helper_Data $coreHelper, EbayEnterprise_MageLog_Helper_Data $logger, EbayEnterprise_MageLog_Helper_Context $logContext ) { return [$api, $request, $orderHelper, $orderCfg, $coreHelper, $logger, $logContext]; }
php
protected function _checkTypes( IBidirectionalApi $api, IPayload $request, EbayEnterprise_Order_Helper_Data $orderHelper, Radial_Core_Model_Config_Registry $orderCfg, Radial_Core_Helper_Data $coreHelper, EbayEnterprise_MageLog_Helper_Data $logger, EbayEnterprise_MageLog_Helper_Context $logContext ) { return [$api, $request, $orderHelper, $orderCfg, $coreHelper, $logger, $logContext]; }
Type hinting for self::__construct $initParams @param IBidirectionalApi @param IPayload @param EbayEnterprise_Order_Helper_Data @param Radial_Core_Model_Config_Registry @param Radial_Core_Helper_Data @param EbayEnterprise_MageLog_Helper_Data @param EbayEnterprise_MageLog_Helper_Context @return array
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Abstract/Send.php#L72-L82
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Abstract/Send.php
EbayEnterprise_Order_Model_Abstract_Send._sendRequest
protected function _sendRequest() { $logger = $this->_logger; $logContext = $this->_logContext; $response = null; try { $response = $this->_api ->setRequestBody($this->_request) ->send() ->getResponseBody(); } catch (InvalidPayload $e) { $logMessage = "Invalid payload for {$this->_getPayloadName()}. See exception log for more details."; $logger->warning($logMessage, $logContext->getMetaData(__CLASS__, ['exception_message' => $e->getMessage()])); $logger->logException($e, $logContext->getMetaData(__CLASS__, [], $e)); } catch (NetworkError $e) { $logMessage = "Caught a network error sending {$this->_getPayloadName()}. See exception log for more details."; $logger->warning($logMessage, $logContext->getMetaData(__CLASS__, ['exception_message' => $e->getMessage()])); $logger->logException($e, $logContext->getMetaData(__CLASS__, [], $e)); } catch (UnsupportedOperation $e) { $logMessage = "{$this->_getPayloadName()} operation is unsupported in the current configuration. See exception log for more details."; $logger->critical($logMessage, $logContext->getMetaData(__CLASS__, ['exception_message' => $e->getMessage()])); $logger->logException($e, $logContext->getMetaData(__CLASS__, [], $e)); } catch (UnsupportedHttpAction $e) { $logMessage = "{$this->_getPayloadName()} request is configured with an unsupported HTTP action. See exception log for more details."; $logger->critical($logMessage, $logContext->getMetaData(__CLASS__, ['exception_message' => $e->getMessage()])); $logger->logException($e, $logContext->getMetaData(__CLASS__, [], $e)); } catch (Exception $e) { $logMessage = "Encountered unexpected exception sending {$this->_getPayloadName()}. See exception log for more details."; $logger->warning($logMessage, $logContext->getMetaData(__CLASS__, ['exception_message' => $e->getMessage()])); $logger->logException($e, $logContext->getMetaData(__CLASS__, [], $e)); } return $response; }
php
protected function _sendRequest() { $logger = $this->_logger; $logContext = $this->_logContext; $response = null; try { $response = $this->_api ->setRequestBody($this->_request) ->send() ->getResponseBody(); } catch (InvalidPayload $e) { $logMessage = "Invalid payload for {$this->_getPayloadName()}. See exception log for more details."; $logger->warning($logMessage, $logContext->getMetaData(__CLASS__, ['exception_message' => $e->getMessage()])); $logger->logException($e, $logContext->getMetaData(__CLASS__, [], $e)); } catch (NetworkError $e) { $logMessage = "Caught a network error sending {$this->_getPayloadName()}. See exception log for more details."; $logger->warning($logMessage, $logContext->getMetaData(__CLASS__, ['exception_message' => $e->getMessage()])); $logger->logException($e, $logContext->getMetaData(__CLASS__, [], $e)); } catch (UnsupportedOperation $e) { $logMessage = "{$this->_getPayloadName()} operation is unsupported in the current configuration. See exception log for more details."; $logger->critical($logMessage, $logContext->getMetaData(__CLASS__, ['exception_message' => $e->getMessage()])); $logger->logException($e, $logContext->getMetaData(__CLASS__, [], $e)); } catch (UnsupportedHttpAction $e) { $logMessage = "{$this->_getPayloadName()} request is configured with an unsupported HTTP action. See exception log for more details."; $logger->critical($logMessage, $logContext->getMetaData(__CLASS__, ['exception_message' => $e->getMessage()])); $logger->logException($e, $logContext->getMetaData(__CLASS__, [], $e)); } catch (Exception $e) { $logMessage = "Encountered unexpected exception sending {$this->_getPayloadName()}. See exception log for more details."; $logger->warning($logMessage, $logContext->getMetaData(__CLASS__, ['exception_message' => $e->getMessage()])); $logger->logException($e, $logContext->getMetaData(__CLASS__, [], $e)); } return $response; }
Sending the payload request and returning the response. @return IPayload | null
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Abstract/Send.php#L119-L152
mlocati/concrete5-translation-library
src/Parser/DynamicItem/AttributeSet.php
AttributeSet.parseManual
public function parseManual(\Gettext\Translations $translations, $concrete5version) { if (class_exists('\AttributeKeyCategory', true) && class_exists('\AttributeSet', true)) { foreach (\AttributeKeyCategory::getList() as $akc) { foreach ($akc->getAttributeSets() as $as) { $this->addTranslation($translations, $as->getAttributeSetName(), 'AttributeSetName'); } } } }
php
public function parseManual(\Gettext\Translations $translations, $concrete5version) { if (class_exists('\AttributeKeyCategory', true) && class_exists('\AttributeSet', true)) { foreach (\AttributeKeyCategory::getList() as $akc) { foreach ($akc->getAttributeSets() as $as) { $this->addTranslation($translations, $as->getAttributeSetName(), 'AttributeSetName'); } } } }
{@inheritdoc} @see \C5TL\Parser\DynamicItem\DynamicItem::parseManual()
https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Parser/DynamicItem/AttributeSet.php#L35-L44
phavour/phavour
Phavour/Application.php
Application.setCacheAdapter
public function setCacheAdapter(AdapterAbstract $adapter) { if ($this->isSetup) { $e = new ApplicationIsAlreadySetupException('You cannot set the cache after calling setup()'); $this->error($e); } $this->cache = $adapter; }
php
public function setCacheAdapter(AdapterAbstract $adapter) { if ($this->isSetup) { $e = new ApplicationIsAlreadySetupException('You cannot set the cache after calling setup()'); $this->error($e); } $this->cache = $adapter; }
Set an application level cache adapter. This adapter will be made available to all runnables @param AdapterAbstract $adapter
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Application.php#L134-L142
phavour/phavour
Phavour/Application.php
Application.setup
public function setup() { $this->request = new Request(); $this->response = new Response(); $this->env = new Environment(); $this->mode = $this->env->getMode(); if (!$this->env->isProduction() || $this->cache == null) { $this->cache = new AdapterNull(); } $this->loadPackages(); $this->loadConfig(); // @codeCoverageIgnoreStart if (array_key_exists('ini.set', $this->config)) { foreach ($this->config['ini.set'] as $iniName => $iniValue) { ini_set($iniName, $iniValue); } } // @codeCoverageIgnoreEnd $this->loadRoutes(); $this->isSetup = true; }
php
public function setup() { $this->request = new Request(); $this->response = new Response(); $this->env = new Environment(); $this->mode = $this->env->getMode(); if (!$this->env->isProduction() || $this->cache == null) { $this->cache = new AdapterNull(); } $this->loadPackages(); $this->loadConfig(); // @codeCoverageIgnoreStart if (array_key_exists('ini.set', $this->config)) { foreach ($this->config['ini.set'] as $iniName => $iniValue) { ini_set($iniName, $iniValue); } } // @codeCoverageIgnoreEnd $this->loadRoutes(); $this->isSetup = true; }
Setup the application, assigns all the packages, config, routes
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Application.php#L148-L168
phavour/phavour
Phavour/Application.php
Application.run
public function run() { if (empty($this->packagesMetadata)) { $this->setup(); if (empty($this->packagesMetadata)) { // @codeCoverageIgnoreStart $e = new PackagesNotFoundException('Application has no packages.'); $e->setAdditionalData('Application Path', $this->appDirectory); $this->error($e); return; // @codeCoverageIgnoreEnd } } $this->router = new Router(); $this->router->setRoutes($this->routes); $this->router->setMethod($this->request->getRequestMethod()); $this->router->setPath($this->request->getRequestUri()); $this->router->setIp($this->request->getClientIp()); try { $route = $this->router->getRoute(); } catch (RouteNotFoundException $e) { $this->notFound($e); return; } $middleware = false; if ($this->hasMiddleware()) { $middleware = new MiddlewareProcessor($this->config['Middleware']); } $package = $this->getPackage($route['package']); $runnable = $route['runnable']; $runnables = explode('::', $runnable); // Check if it's a view script only. if ($route['view.directRender'] === true) { try { if ($middleware) { $middleware->runBefore($this->request, $this->response); } $view = $this->getViewFor($package['package_name'], $runnables[0], $runnables[1]); if ($route['view.layout'] !== false) { $view->setLayout($route['view.layout']); } $view->setResponse($this->response); $view->render(); if ($middleware) { $middleware->runAfter(); } return; // @codeCoverageIgnoreStart } catch (\Exception $e) { $this->error($e); return; } } $classString = $package['namespace'] . '\\src\\' . $runnables[0]; if (class_exists($classString)) { try { if ($middleware) { $middleware->runBefore($this->request, $this->response); } $instance = $this->getRunnable($package['package_name'], $runnables[0], $runnables[1], $classString); if (is_callable(array($instance, $runnables[1]))) { if ($route['view.layout'] !== false) { $instance->getView()->setLayout($route['view.layout']); } call_user_func_array(array($instance, $runnables[1]), $route['params']); $instance->finalise(); if ($middleware) { $middleware->runAfter(); } return; } // @codeCoverageIgnoreStart } catch (\Exception $e) { $this->error($e); return; } $this->notFound(new RunnableNotFoundException('No such runnable: ' . $classString . '::' . $runnables[1])); } $this->notFound(new RunnableNotFoundException('No such runnable: ' . $classString . '::' . $runnables[1])); }
php
public function run() { if (empty($this->packagesMetadata)) { $this->setup(); if (empty($this->packagesMetadata)) { // @codeCoverageIgnoreStart $e = new PackagesNotFoundException('Application has no packages.'); $e->setAdditionalData('Application Path', $this->appDirectory); $this->error($e); return; // @codeCoverageIgnoreEnd } } $this->router = new Router(); $this->router->setRoutes($this->routes); $this->router->setMethod($this->request->getRequestMethod()); $this->router->setPath($this->request->getRequestUri()); $this->router->setIp($this->request->getClientIp()); try { $route = $this->router->getRoute(); } catch (RouteNotFoundException $e) { $this->notFound($e); return; } $middleware = false; if ($this->hasMiddleware()) { $middleware = new MiddlewareProcessor($this->config['Middleware']); } $package = $this->getPackage($route['package']); $runnable = $route['runnable']; $runnables = explode('::', $runnable); // Check if it's a view script only. if ($route['view.directRender'] === true) { try { if ($middleware) { $middleware->runBefore($this->request, $this->response); } $view = $this->getViewFor($package['package_name'], $runnables[0], $runnables[1]); if ($route['view.layout'] !== false) { $view->setLayout($route['view.layout']); } $view->setResponse($this->response); $view->render(); if ($middleware) { $middleware->runAfter(); } return; // @codeCoverageIgnoreStart } catch (\Exception $e) { $this->error($e); return; } } $classString = $package['namespace'] . '\\src\\' . $runnables[0]; if (class_exists($classString)) { try { if ($middleware) { $middleware->runBefore($this->request, $this->response); } $instance = $this->getRunnable($package['package_name'], $runnables[0], $runnables[1], $classString); if (is_callable(array($instance, $runnables[1]))) { if ($route['view.layout'] !== false) { $instance->getView()->setLayout($route['view.layout']); } call_user_func_array(array($instance, $runnables[1]), $route['params']); $instance->finalise(); if ($middleware) { $middleware->runAfter(); } return; } // @codeCoverageIgnoreStart } catch (\Exception $e) { $this->error($e); return; } $this->notFound(new RunnableNotFoundException('No such runnable: ' . $classString . '::' . $runnables[1])); } $this->notFound(new RunnableNotFoundException('No such runnable: ' . $classString . '::' . $runnables[1])); }
Run the application.
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Application.php#L173-L259
phavour/phavour
Phavour/Application.php
Application.loadPackages
private function loadPackages() { foreach ($this->packages as $package) { /** @var $package \Phavour\Package */ $this->packagesMetadata[$package->getPackageName()] = array( 'namespace' => $package->getNamespace(), 'route_path' => $package->getRoutePath(), 'config_path' => $package->getConfigPath(), 'package_path' => $package->getPackagePath(), 'package_name' => $package->getPackageName() ); } }
php
private function loadPackages() { foreach ($this->packages as $package) { /** @var $package \Phavour\Package */ $this->packagesMetadata[$package->getPackageName()] = array( 'namespace' => $package->getNamespace(), 'route_path' => $package->getRoutePath(), 'config_path' => $package->getConfigPath(), 'package_path' => $package->getPackagePath(), 'package_name' => $package->getPackageName() ); } }
Load the package metadata from the given list
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Application.php#L281-L293
phavour/phavour
Phavour/Application.php
Application.loadConfig
private function loadConfig() { $cacheName = $this->mode . '_Phavour_Application_config'; if (false != ($configs = $this->cache->get($cacheName))) { // @codeCoverageIgnoreStart $this->config = $configs; return; // @codeCoverageIgnoreEnd } $config = array(); foreach ($this->packagesMetadata as $package) { try { $finder = new FromArray($package['config_path']); $proposedConfig = $finder->getArrayWhereKeysBeginWith($package['package_name']); if (is_array($proposedConfig)) { $config = array_merge($config, $proposedConfig); } } catch (\Exception $e) { // Package doesn't have config } } try { $finder = new FromArray( $this->appDirectory . DIRECTORY_SEPARATOR . 'res' . DIRECTORY_SEPARATOR . 'config.php' ); $appConfig = $finder->getArray(); if (is_array($appConfig)) { $config = array_merge($config, $appConfig); } } catch (\Exception $e) { // No config overrides set } $this->config = $config; $this->cache->set($cacheName, $this->config, 86400); }
php
private function loadConfig() { $cacheName = $this->mode . '_Phavour_Application_config'; if (false != ($configs = $this->cache->get($cacheName))) { // @codeCoverageIgnoreStart $this->config = $configs; return; // @codeCoverageIgnoreEnd } $config = array(); foreach ($this->packagesMetadata as $package) { try { $finder = new FromArray($package['config_path']); $proposedConfig = $finder->getArrayWhereKeysBeginWith($package['package_name']); if (is_array($proposedConfig)) { $config = array_merge($config, $proposedConfig); } } catch (\Exception $e) { // Package doesn't have config } } try { $finder = new FromArray( $this->appDirectory . DIRECTORY_SEPARATOR . 'res' . DIRECTORY_SEPARATOR . 'config.php' ); $appConfig = $finder->getArray(); if (is_array($appConfig)) { $config = array_merge($config, $appConfig); } } catch (\Exception $e) { // No config overrides set } $this->config = $config; $this->cache->set($cacheName, $this->config, 86400); }
Load and assign the config files from the packages and the main /res/config.php file
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Application.php#L299-L337
phavour/phavour
Phavour/Application.php
Application.loadRoutes
private function loadRoutes() { $cacheName = $this->mode . '_Phavour_Application_routes'; if (false != ($routes = $this->cache->get($cacheName))) { // @codeCoverageIgnoreStart $this->routes = $routes; return; // @codeCoverageIgnoreEnd } $routes = array(); foreach ($this->packagesMetadata as $package) { try { $finder = new FromArray($package['route_path']); $proposedRoutes = $finder->getArray(); if (is_array($proposedRoutes)) { foreach ($proposedRoutes as $key => $routeDetails) { if (!array_key_exists('package', $routeDetails)) { $proposedRoutes[$key]['package'] = $package['package_name']; } $proposedRoutes[$key]['package'] = $package['package_name']; } $routes = array_merge($routes, $proposedRoutes); } } catch (\Exception $e) { // Package doesn't have routes } } try { $finder = new FromArray( $this->appDirectory . DIRECTORY_SEPARATOR . 'res' . DIRECTORY_SEPARATOR . 'routes.php' ); $appRoutes = $finder->getArray(); if (is_array($appRoutes)) { foreach ($appRoutes as $routeDetails) { // @codeCoverageIgnoreStart if (!array_key_exists('package', $routeDetails)) { throw new RouteMissingPackageNameException(); } // @codeCoverageIgnoreEnd } $routes = array_merge($routes, $appRoutes); } } catch (\Exception $e) { // No route overrides set } $this->routes = $routes; $this->cache->set($cacheName, $this->routes, 86400); }
php
private function loadRoutes() { $cacheName = $this->mode . '_Phavour_Application_routes'; if (false != ($routes = $this->cache->get($cacheName))) { // @codeCoverageIgnoreStart $this->routes = $routes; return; // @codeCoverageIgnoreEnd } $routes = array(); foreach ($this->packagesMetadata as $package) { try { $finder = new FromArray($package['route_path']); $proposedRoutes = $finder->getArray(); if (is_array($proposedRoutes)) { foreach ($proposedRoutes as $key => $routeDetails) { if (!array_key_exists('package', $routeDetails)) { $proposedRoutes[$key]['package'] = $package['package_name']; } $proposedRoutes[$key]['package'] = $package['package_name']; } $routes = array_merge($routes, $proposedRoutes); } } catch (\Exception $e) { // Package doesn't have routes } } try { $finder = new FromArray( $this->appDirectory . DIRECTORY_SEPARATOR . 'res' . DIRECTORY_SEPARATOR . 'routes.php' ); $appRoutes = $finder->getArray(); if (is_array($appRoutes)) { foreach ($appRoutes as $routeDetails) { // @codeCoverageIgnoreStart if (!array_key_exists('package', $routeDetails)) { throw new RouteMissingPackageNameException(); } // @codeCoverageIgnoreEnd } $routes = array_merge($routes, $appRoutes); } } catch (\Exception $e) { // No route overrides set } $this->routes = $routes; $this->cache->set($cacheName, $this->routes, 86400); }
Load and assign the route files from the packages and the main /res/routes.php file
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Application.php#L343-L393
phavour/phavour
Phavour/Application.php
Application.notFound
private function notFound(\Exception $throwable) { if ($this->env->isProduction()) { if (false != ($errorClass = $this->getErrorClass())) { try { // TODO : This needs to be moved into a $this->boot() method $this->response->setStatus(404); $instance = $this->getRunnable('DefaultPackage', 'Error', 'notFound', $errorClass); if (is_callable(array($instance, 'notFound'))) { $instance->notFound(); } else { // @codeCoverageIgnoreStart $e = new RunnableNotFoundException('Runnable not found'); $e->setAdditionalData('Expected: ', '\\DefaultPackage\\src\\Error::notFound()'); throw $e; // @codeCoverageIgnoreEnd } $instance->finalise(); return; // @codeCoverageIgnoreStart } catch (\Exception $e) { $this->error($e); return; // @codeCoverageIgnoreEnd } } // @codeCoverageIgnoreStart @ob_get_clean(); $this->response->setStatus(404); $this->response->setBody('<h1 style="font:28px/1.5 Helvetica,Arial,Verdana,sans-serif;">404 Not Found</h1>'); $this->response->sendResponse(); return; // @codeCoverageIgnoreEnd } else { // @codeCoverageIgnoreStart FormattedException::display($throwable); return; // @codeCoverageIgnoreEnd } }
php
private function notFound(\Exception $throwable) { if ($this->env->isProduction()) { if (false != ($errorClass = $this->getErrorClass())) { try { // TODO : This needs to be moved into a $this->boot() method $this->response->setStatus(404); $instance = $this->getRunnable('DefaultPackage', 'Error', 'notFound', $errorClass); if (is_callable(array($instance, 'notFound'))) { $instance->notFound(); } else { // @codeCoverageIgnoreStart $e = new RunnableNotFoundException('Runnable not found'); $e->setAdditionalData('Expected: ', '\\DefaultPackage\\src\\Error::notFound()'); throw $e; // @codeCoverageIgnoreEnd } $instance->finalise(); return; // @codeCoverageIgnoreStart } catch (\Exception $e) { $this->error($e); return; // @codeCoverageIgnoreEnd } } // @codeCoverageIgnoreStart @ob_get_clean(); $this->response->setStatus(404); $this->response->setBody('<h1 style="font:28px/1.5 Helvetica,Arial,Verdana,sans-serif;">404 Not Found</h1>'); $this->response->sendResponse(); return; // @codeCoverageIgnoreEnd } else { // @codeCoverageIgnoreStart FormattedException::display($throwable); return; // @codeCoverageIgnoreEnd } }
In the event of an invalid route, this method will be called by default it'll look for 'DefaultPackage::Error::notFound' before manipulating the response directly and returning to the user. It's environmental sensitive, so will format things accordingly. @param \Exception $throwable
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Application.php#L411-L451
phavour/phavour
Phavour/Application.php
Application.getErrorClass
private function getErrorClass() { try { $package = $this->getPackage('DefaultPackage'); } catch (PackageNotFoundException $e) { // @codeCoverageIgnoreStart return false; // @codeCoverageIgnoreEnd } $controller = $package['namespace'] . '\\src\\Error'; if (!class_exists($controller)) { // @codeCoverageIgnoreStart return false; // @codeCoverageIgnoreEnd } return $controller; }
php
private function getErrorClass() { try { $package = $this->getPackage('DefaultPackage'); } catch (PackageNotFoundException $e) { // @codeCoverageIgnoreStart return false; // @codeCoverageIgnoreEnd } $controller = $package['namespace'] . '\\src\\Error'; if (!class_exists($controller)) { // @codeCoverageIgnoreStart return false; // @codeCoverageIgnoreEnd } return $controller; }
Get the class name of the \DefaultPackage\src\Error (if it exists) @return string|boolean false for failure
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Application.php#L497-L516
phavour/phavour
Phavour/Application.php
Application.getRunnable
private function getRunnable($package, $class, $method, $className) { $view = $this->getViewFor($package, $class, $method); $instance = new $className($this->request, $this->response, $view, $this->env, $this->cache, $this->router, $this->config); /* @var $instance Runnable */ $instance->init(); return $instance; }
php
private function getRunnable($package, $class, $method, $className) { $view = $this->getViewFor($package, $class, $method); $instance = new $className($this->request, $this->response, $view, $this->env, $this->cache, $this->router, $this->config); /* @var $instance Runnable */ $instance->init(); return $instance; }
Get the corresponding runnable for the given parameters @param string $package @param string $class @param string $method @param string $className @return \Phavour\Runnable
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Application.php#L526-L534
phavour/phavour
Phavour/Application.php
Application.getViewFor
private function getViewFor($package, $class, $method) { $view = new View($this, $package, $class, $method); $view->setRouter($this->router); $view->setConfig($this->config); return $view; }
php
private function getViewFor($package, $class, $method) { $view = new View($this, $package, $class, $method); $view->setRouter($this->router); $view->setConfig($this->config); return $view; }
Retrieve an instance of View for a given package, class, method combination @param string $package @param string $class @param string $method @return \Phavour\Runnable\View
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Application.php#L543-L550
diasbruno/stc
lib/stc/Files.php
Files.load
public function load($data_folder = '', $pages_data = '') { $this->data_path = '/' . $pages_data; $files = $this->read_dir($data_folder . $this->data_path); $pattern = '/(.+).json$/'; $data_loader = new DataLoader(); foreach($files as $file) { if (preg_match($pattern, $file, $match)) { $f = $data_loader->load( $data_folder . $this->data_path, $file ); $f['file'] = $file; $this->files[] = $f; } } }
php
public function load($data_folder = '', $pages_data = '') { $this->data_path = '/' . $pages_data; $files = $this->read_dir($data_folder . $this->data_path); $pattern = '/(.+).json$/'; $data_loader = new DataLoader(); foreach($files as $file) { if (preg_match($pattern, $file, $match)) { $f = $data_loader->load( $data_folder . $this->data_path, $file ); $f['file'] = $file; $this->files[] = $f; } } }
Load files from a given directory. @param $data_folder string | The folder name. @return array
https://github.com/diasbruno/stc/blob/43f62c3b28167bff76274f954e235413a9e9c707/lib/stc/Files.php#L39-L58
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Api.php
Radial_Core_Model_Api.request
public function request( DOMDocument $doc, $xsdName, $uri, $timeout = self::DEFAULT_TIMEOUT, $adapter = self::DEFAULT_ADAPTER, Zend_Http_Client $client = null, $apiKey = null ) { if (!$apiKey) { $apiKey = Mage::helper('radial_core')->getConfigModel()->apiKey; } $xmlStr = $doc->C14N(); $logData = array_merge(['rom_request_body' => $xmlStr], $this->_logAppContext); $logMessage = 'Validating request.'; $this->_logger->debug($logMessage, $this->_context->getMetaData(__CLASS__, $logData)); $this->schemaValidate($doc, $xsdName); $client = $this->_setupClient($client, $apiKey, $uri, $xmlStr, $adapter, $timeout); $logData = array_merge(['rom_request_url' => $uri], $this->_logAppContext); $logMessage = 'Sending request.'; $this->_logger->info($logMessage, $this->_context->getMetaData(__CLASS__, $logData)); try { $response = $client->request(self::DEFAULT_METHOD); return $this->_processResponse($response, $uri); } catch (Zend_Http_Client_Exception $e) { return $this->_processException($e, $uri); } }
php
public function request( DOMDocument $doc, $xsdName, $uri, $timeout = self::DEFAULT_TIMEOUT, $adapter = self::DEFAULT_ADAPTER, Zend_Http_Client $client = null, $apiKey = null ) { if (!$apiKey) { $apiKey = Mage::helper('radial_core')->getConfigModel()->apiKey; } $xmlStr = $doc->C14N(); $logData = array_merge(['rom_request_body' => $xmlStr], $this->_logAppContext); $logMessage = 'Validating request.'; $this->_logger->debug($logMessage, $this->_context->getMetaData(__CLASS__, $logData)); $this->schemaValidate($doc, $xsdName); $client = $this->_setupClient($client, $apiKey, $uri, $xmlStr, $adapter, $timeout); $logData = array_merge(['rom_request_url' => $uri], $this->_logAppContext); $logMessage = 'Sending request.'; $this->_logger->info($logMessage, $this->_context->getMetaData(__CLASS__, $logData)); try { $response = $client->request(self::DEFAULT_METHOD); return $this->_processResponse($response, $uri); } catch (Zend_Http_Client_Exception $e) { return $this->_processException($e, $uri); } }
Call the API. @param DOMDocument $doc The document to send in the request body @param string $xsdName The basename of the xsd file to validate $doc (The dirname is in config.xml) @param string $uri The uri to send the request to @param int $timeout The amount of time in seconds after which the connection is terminated @param string $adapter The classname of a Zend_Http_Client_Adapter @param Zend_Http_Client $client @param string $apiKey Alternate API Key to use @return string The response from the server
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Api.php#L73-L102
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Api.php
Radial_Core_Model_Api._setupClient
protected function _setupClient(Zend_Http_Client $client = null, $apiKey, $uri, $data, $adapter, $timeout) { $client = $client ?: new Varien_Http_Client(); $client ->setHeaders('apiKey', $apiKey) ->setUri($uri) ->setRawData($data) ->setEncType('text/xml') ->setConfig(array( 'adapter' => $adapter, 'timeout' => $timeout, )); return $client; }
php
protected function _setupClient(Zend_Http_Client $client = null, $apiKey, $uri, $data, $adapter, $timeout) { $client = $client ?: new Varien_Http_Client(); $client ->setHeaders('apiKey', $apiKey) ->setUri($uri) ->setRawData($data) ->setEncType('text/xml') ->setConfig(array( 'adapter' => $adapter, 'timeout' => $timeout, )); return $client; }
Instantiate (if necessary) and set up the http client. @param Zend_Http_Client $client @param string $apiKey for authentication @param string $uri @param string $data raw data to send @param string $adapter the classname of a Zend_Http_Client_Adapter @param int $timeout @return Zend_Http_Client
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Api.php#L114-L127
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Api.php
Radial_Core_Model_Api._processResponse
protected function _processResponse(Zend_Http_Response $response, $uri) { $this->_status = $response->getStatus(); $config = $this->_getHandlerConfig($this->_getHandlerKey($response)); $logMethod = isset($config['logger']) ? $config['logger'] : 'debug'; $logData = array_merge(['rom_request_url' => $uri], $this->_logAppContext); $this->_logger->$logMethod('Received response from.', $this->_context->getMetaData(__CLASS__, $logData)); $responseData = $logData; $responseData['rom_response_body'] = $response->asString(); $logMessage = 'Response data.'; $this->_logger->debug($logMessage, $this->_context->getMetaData(__CLASS__, $responseData)); if (!$response->getBody()) { $logMessage = "Received response with no body from {$uri} with status {$this->_status}."; $this->_logger->warning($logMessage, $this->_context->getMetaData(__CLASS__, $logData)); } $callbackConfig = isset($config['callback']) ? $config['callback'] : array(); $callbackConfig['parameters'] = array($response); return Mage::helper('radial_core')->invokeCallBack($callbackConfig); }
php
protected function _processResponse(Zend_Http_Response $response, $uri) { $this->_status = $response->getStatus(); $config = $this->_getHandlerConfig($this->_getHandlerKey($response)); $logMethod = isset($config['logger']) ? $config['logger'] : 'debug'; $logData = array_merge(['rom_request_url' => $uri], $this->_logAppContext); $this->_logger->$logMethod('Received response from.', $this->_context->getMetaData(__CLASS__, $logData)); $responseData = $logData; $responseData['rom_response_body'] = $response->asString(); $logMessage = 'Response data.'; $this->_logger->debug($logMessage, $this->_context->getMetaData(__CLASS__, $responseData)); if (!$response->getBody()) { $logMessage = "Received response with no body from {$uri} with status {$this->_status}."; $this->_logger->warning($logMessage, $this->_context->getMetaData(__CLASS__, $logData)); } $callbackConfig = isset($config['callback']) ? $config['callback'] : array(); $callbackConfig['parameters'] = array($response); return Mage::helper('radial_core')->invokeCallBack($callbackConfig); }
log the response and return the result of the configured handler method. @param Zend_Http_Response $response @param string $uri @return string response body or empty
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Api.php#L136-L154
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Api.php
Radial_Core_Model_Api.schemaValidate
public function schemaValidate(DOMDocument $doc, $xsdName) { $errors = array(); set_error_handler(function ($errno, $errstr) use (&$errors) { $errors[] = "'$errstr' [Errno $errno]"; }); $cfg = Mage::helper('radial_core')->getConfigModel(); $isValid = $doc->schemaValidate(Mage::getBaseDir() . DS . $cfg->apiXsdPath . DS . $xsdName); restore_error_handler(); if (!$isValid) { $msg = sprintf( "[ %s ] Schema validation failed, encountering the following errors:\n%s", __CLASS__, implode("\n", $errors) ); throw new Radial_Core_Exception_InvalidXml($msg); } return $this; }
php
public function schemaValidate(DOMDocument $doc, $xsdName) { $errors = array(); set_error_handler(function ($errno, $errstr) use (&$errors) { $errors[] = "'$errstr' [Errno $errno]"; }); $cfg = Mage::helper('radial_core')->getConfigModel(); $isValid = $doc->schemaValidate(Mage::getBaseDir() . DS . $cfg->apiXsdPath . DS . $xsdName); restore_error_handler(); if (!$isValid) { $msg = sprintf( "[ %s ] Schema validation failed, encountering the following errors:\n%s", __CLASS__, implode("\n", $errors) ); throw new Radial_Core_Exception_InvalidXml($msg); } return $this; }
Validates the DOM against a validation schema, which should be a full path to an xsd for this DOMDocument. @param DomDocument $doc The document to validate @param string $xsdName xsd file basename with which to validate the doc @throws Radial_Core_Exception_InvalidXml when the schema is invalid @return self
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Api.php#L171-L189
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Api.php
Radial_Core_Model_Api._processException
protected function _processException(Zend_Http_Client_Exception $exception, $uri) { $this->_status = 0; $config = $this->_getHandlerConfig($this->_getHandlerKey()); $logMethod = isset($config['logger']) ? $config['logger'] : 'debug'; // the zend http client throws exceptions that are generic and make it impractical to // generate a message that is more representative of what went wrong. $logData = array_merge(['rom_request_url' => $uri], $this->_logAppContext); $logMessage = "Problem with request to {$uri}:\n{$exception->getMessage()}"; $this->_logger->$logMethod($logMessage, $this->_context->getMetaData(__CLASS__, $logData, $exception)); $callbackConfig = isset($config['callback']) ? $config['callback'] : array(); return Mage::helper('radial_core')->invokeCallBack($callbackConfig); }
php
protected function _processException(Zend_Http_Client_Exception $exception, $uri) { $this->_status = 0; $config = $this->_getHandlerConfig($this->_getHandlerKey()); $logMethod = isset($config['logger']) ? $config['logger'] : 'debug'; // the zend http client throws exceptions that are generic and make it impractical to // generate a message that is more representative of what went wrong. $logData = array_merge(['rom_request_url' => $uri], $this->_logAppContext); $logMessage = "Problem with request to {$uri}:\n{$exception->getMessage()}"; $this->_logger->$logMethod($logMessage, $this->_context->getMetaData(__CLASS__, $logData, $exception)); $callbackConfig = isset($config['callback']) ? $config['callback'] : array(); return Mage::helper('radial_core')->invokeCallBack($callbackConfig); }
handle the exception thrown by the zend client and return the result of the configured handler. @param Zend_Http_Client_Exception $exception @param string $uri @return string
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Api.php#L197-L209
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Api.php
Radial_Core_Model_Api._getHandlerKey
protected function _getHandlerKey(Zend_Http_Response $response = null) { if ($response) { $code = $response->getStatus(); if ($response->isSuccessful() || $response->isRedirect()) { return 'success'; } elseif ($code < 500 && $code >= 400) { return 'client_error'; } elseif ($code >= 500) { return 'server_error'; } // @codeCoverageIgnoreStart } // @codeCoverageIgnoreEnd return 'no_response'; }
php
protected function _getHandlerKey(Zend_Http_Response $response = null) { if ($response) { $code = $response->getStatus(); if ($response->isSuccessful() || $response->isRedirect()) { return 'success'; } elseif ($code < 500 && $code >= 400) { return 'client_error'; } elseif ($code >= 500) { return 'server_error'; } // @codeCoverageIgnoreStart } // @codeCoverageIgnoreEnd return 'no_response'; }
return a string that is a key to the handler config for the class of status codes. @param Zend_Http_Response $response @return string
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Api.php#L239-L254
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Api.php
Radial_Core_Model_Api._getMergedHandlerConfig
protected function _getMergedHandlerConfig(array $config = array()) { $cfg = Mage::helper('radial_core')->getConfigModel(); $defaultConfig = $cfg->getConfigData(static::DEFAULT_HANDLER_CONFIG); if (isset($config['alert_level']) && $config['alert_level'] === 'loud') { $defaultConfig = array_replace_recursive( $defaultConfig, $cfg->getConfigData(static::DEFAULT_LOUD_HANDLER_CONFIG) ); } return array_replace_recursive($defaultConfig, $config); }
php
protected function _getMergedHandlerConfig(array $config = array()) { $cfg = Mage::helper('radial_core')->getConfigModel(); $defaultConfig = $cfg->getConfigData(static::DEFAULT_HANDLER_CONFIG); if (isset($config['alert_level']) && $config['alert_level'] === 'loud') { $defaultConfig = array_replace_recursive( $defaultConfig, $cfg->getConfigData(static::DEFAULT_LOUD_HANDLER_CONFIG) ); } return array_replace_recursive($defaultConfig, $config); }
return the merged contents of the default (silent) config and the loud config and the passed in array such that the loud config's values override the silent config's values and the passed config's values override the loud config's values. @param array $config @return array
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Api.php#L262-L273
beyoio/beyod
Parser.php
Parser.input
public function input($buffer, $connection) { $len = strlen($buffer); if ($this->max_packet_size >0 && $len >= $this->max_packet_size) { throw new \Exception($connection.' request packet size exceed max_packet_size ', Server::ERROR_LARGE_PACKET); } return $len; }
php
public function input($buffer, $connection) { $len = strlen($buffer); if ($this->max_packet_size >0 && $len >= $this->max_packet_size) { throw new \Exception($connection.' request packet size exceed max_packet_size ', Server::ERROR_LARGE_PACKET); } return $len; }
Determines whether the current connection has received the complete packet, zero value indicates that a complete packet is not received yet, positive value indicates that a complete packet has been received and represents the number of bytes of the packet, negative value indicates that the data is invalid or unrecognized @param string $buffer @param Connection|StreamClient $connection, for udp packet it is null @return int
https://github.com/beyoio/beyod/blob/11941db9c4ae4abbca6c8e634d21873c690efc79/Parser.php#L51-L60
old-town/workflow-zf2
src/Factory/WorkflowServiceFactory.php
WorkflowServiceFactory.createService
public function createService(ServiceLocatorInterface $serviceLocator) { /** @var ModuleOptions $moduleOptions */ $moduleOptions = $serviceLocator->get(ModuleOptions::class); $options = [ 'serviceLocator' => $serviceLocator, 'moduleOptions' => $moduleOptions ]; $wf = new Workflow($options); /** @var ModuleOptions $moduleOptions */ $moduleOptions = $serviceLocator->get(ModuleOptions::class); $wf->setWorkflowManagerServiceNamePattern($moduleOptions->getWorkflowManagerServiceNamePattern()); return $wf; }
php
public function createService(ServiceLocatorInterface $serviceLocator) { /** @var ModuleOptions $moduleOptions */ $moduleOptions = $serviceLocator->get(ModuleOptions::class); $options = [ 'serviceLocator' => $serviceLocator, 'moduleOptions' => $moduleOptions ]; $wf = new Workflow($options); /** @var ModuleOptions $moduleOptions */ $moduleOptions = $serviceLocator->get(ModuleOptions::class); $wf->setWorkflowManagerServiceNamePattern($moduleOptions->getWorkflowManagerServiceNamePattern()); return $wf; }
@param ServiceLocatorInterface $serviceLocator @return Workflow @throws \Zend\Stdlib\Exception\InvalidArgumentException @throws \OldTown\Workflow\ZF2\Service\Exception\InvalidArgumentException @throws \OldTown\Workflow\ZF2\ServiceEngine\Exception\InvalidArgumentException @throws \Zend\ServiceManager\Exception\ServiceNotFoundException
https://github.com/old-town/workflow-zf2/blob/b63910bd0f4c05855e19cfa29e3376eee7c16c77/src/Factory/WorkflowServiceFactory.php#L35-L55
kiwi-26/line-bot-test-helper
src/WebhookEvent.php
WebhookEvent.body
public function body() { $event = []; if (!empty($this->replyToken)) { $event['replyToken'] = $this->replyToken; } $event['type'] = $this->eventType(); $event['timestamp'] = time(); $event['source'] = $this->source; $event['message'] = $this->message; $result = ['events' => [$event]]; return json_encode($result); }
php
public function body() { $event = []; if (!empty($this->replyToken)) { $event['replyToken'] = $this->replyToken; } $event['type'] = $this->eventType(); $event['timestamp'] = time(); $event['source'] = $this->source; $event['message'] = $this->message; $result = ['events' => [$event]]; return json_encode($result); }
Build webhook event and return body. Original webhook request body has this signature. @return String json encoded body.
https://github.com/kiwi-26/line-bot-test-helper/blob/e1d6fb611e73016a5242c4b28238686926f262ba/src/WebhookEvent.php#L40-L51
ddvphp/wechat
org/old_version/Thinkphp/Wechatpay.class.php
Wechatpay.resetAuth
public function resetAuth($appid=''){ if (!$appid) $appid = $this->appid; $this->access_token = ''; $authname = 'wechat_access_token'.$appid; S($authname,null); return true; }
php
public function resetAuth($appid=''){ if (!$appid) $appid = $this->appid; $this->access_token = ''; $authname = 'wechat_access_token'.$appid; S($authname,null); return true; }
删除验证数据 @param string $appid
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/org/old_version/Thinkphp/Wechatpay.class.php#L165-L171
ddvphp/wechat
org/old_version/Thinkphp/Wechatpay.class.php
Wechatpay.createNativeUrl
public function createNativeUrl($productid){ $nativeObj["appid"] = $this->appid; $nativeObj["appkey"] = $this->paysignkey; $nativeObj["productid"] = urlencode($productid); $nativeObj["timestamp"] = time(); $nativeObj["noncestr"] = $this->generateNonceStr(); $nativeObj["sign"] = $this->getSignature($nativeObj); unset($nativeObj["appkey"]); $bizString = ""; foreach($nativeObj as $key => $value) { if(strlen($bizString) == 0) $bizString .= $key . "=" . $value; else $bizString .= "&" . $key . "=" . $value; } return "weixin://wxpay/bizpayurl?".$bizString; //weixin://wxpay/bizpayurl?sign=XXXXX&appid=XXXXXX&productid=XXXXXX&timestamp=XXXXXX&noncestr=XXXXXX }
php
public function createNativeUrl($productid){ $nativeObj["appid"] = $this->appid; $nativeObj["appkey"] = $this->paysignkey; $nativeObj["productid"] = urlencode($productid); $nativeObj["timestamp"] = time(); $nativeObj["noncestr"] = $this->generateNonceStr(); $nativeObj["sign"] = $this->getSignature($nativeObj); unset($nativeObj["appkey"]); $bizString = ""; foreach($nativeObj as $key => $value) { if(strlen($bizString) == 0) $bizString .= $key . "=" . $value; else $bizString .= "&" . $key . "=" . $value; } return "weixin://wxpay/bizpayurl?".$bizString; //weixin://wxpay/bizpayurl?sign=XXXXX&appid=XXXXXX&productid=XXXXXX&timestamp=XXXXXX&noncestr=XXXXXX }
生成原生支付url @param number $productid 商品编号,最长为32字节 @return string
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/org/old_version/Thinkphp/Wechatpay.class.php#L263-L281
ddvphp/wechat
org/old_version/Thinkphp/Wechatpay.class.php
Wechatpay.createPackage
public function createPackage($out_trade_no,$body,$total_fee,$notify_url,$spbill_create_ip,$fee_type=1,$bank_type="WX",$input_charset="UTF-8",$time_start="",$time_expire="",$transport_fee="",$product_fee="",$goods_tag="",$attach=""){ $arrdata = array("bank_type" => $bank_type, "body" => $body, "partner" => $this->partnerid, "out_trade_no" => $out_trade_no, "total_fee" => $total_fee, "fee_type" => $fee_type, "notify_url" => $notify_url, "spbill_create_ip" => $spbill_create_ip, "input_charset" => $input_charset); if ($time_start) $arrdata['time_start'] = $time_start; if ($time_expire) $arrdata['time_expire'] = $time_expire; if ($transport_fee) $arrdata['transport_fee'] = $transport_fee; if ($product_fee) $arrdata['product_fee'] = $product_fee; if ($goods_tag) $arrdata['goods_tag'] = $goods_tag; if ($attach) $arrdata['attach'] = $attach; ksort($arrdata); $paramstring = ""; foreach($arrdata as $key => $value) { if(strlen($paramstring) == 0) $paramstring .= $key . "=" . $value; else $paramstring .= "&" . $key . "=" . $value; } $stringSignTemp = $paramstring . "&key=" . $this->partnerkey; $signValue = strtoupper(md5($stringSignTemp)); $package = http_build_query($arrdata) . "&sign=" . $signValue; return $package; }
php
public function createPackage($out_trade_no,$body,$total_fee,$notify_url,$spbill_create_ip,$fee_type=1,$bank_type="WX",$input_charset="UTF-8",$time_start="",$time_expire="",$transport_fee="",$product_fee="",$goods_tag="",$attach=""){ $arrdata = array("bank_type" => $bank_type, "body" => $body, "partner" => $this->partnerid, "out_trade_no" => $out_trade_no, "total_fee" => $total_fee, "fee_type" => $fee_type, "notify_url" => $notify_url, "spbill_create_ip" => $spbill_create_ip, "input_charset" => $input_charset); if ($time_start) $arrdata['time_start'] = $time_start; if ($time_expire) $arrdata['time_expire'] = $time_expire; if ($transport_fee) $arrdata['transport_fee'] = $transport_fee; if ($product_fee) $arrdata['product_fee'] = $product_fee; if ($goods_tag) $arrdata['goods_tag'] = $goods_tag; if ($attach) $arrdata['attach'] = $attach; ksort($arrdata); $paramstring = ""; foreach($arrdata as $key => $value) { if(strlen($paramstring) == 0) $paramstring .= $key . "=" . $value; else $paramstring .= "&" . $key . "=" . $value; } $stringSignTemp = $paramstring . "&key=" . $this->partnerkey; $signValue = strtoupper(md5($stringSignTemp)); $package = http_build_query($arrdata) . "&sign=" . $signValue; return $package; }
生成订单package字符串 @param string $out_trade_no 必填,商户系统内部的订单号,32个字符内,确保在商户系统唯一 @param string $body 必填,商品描述,128 字节以下 @param int $total_fee 必填,订单总金额,单位为分 @param string $notify_url 必填,支付完成通知回调接口,255 字节以内 @param string $spbill_create_ip 必填,用户终端IP,IPV4字串,15字节内 @param int $fee_type 必填,现金支付币种,默认1:人民币 @param string $bank_type 必填,银行通道类型,默认WX @param string $input_charset 必填,传入参数字符编码,默认UTF-8,取值有UTF-8和GBK @param string $time_start 交易起始时间,订单生成时间,格式yyyyMMddHHmmss @param string $time_expire 交易结束时间,也是订单失效时间 @param int $transport_fee 物流费用,单位为分 @param int $product_fee 商品费用,单位为分,必须保证 transport_fee + product_fee=total_fee @param string $goods_tag 商品标记,优惠券时可能用到 @param string $attach 附加数据,notify接口原样返回 @return string
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/org/old_version/Thinkphp/Wechatpay.class.php#L302-L323
ddvphp/wechat
org/old_version/Thinkphp/Wechatpay.class.php
Wechatpay.getPaySign
public function getPaySign($package, $timeStamp, $nonceStr){ $arrdata = array("appid" => $this->appid, "timestamp" => $timeStamp, "noncestr" => $nonceStr, "package" => $package, "appkey" => $this->paysignkey); $paySign = $this->getSignature($arrdata); return $paySign; }
php
public function getPaySign($package, $timeStamp, $nonceStr){ $arrdata = array("appid" => $this->appid, "timestamp" => $timeStamp, "noncestr" => $nonceStr, "package" => $package, "appkey" => $this->paysignkey); $paySign = $this->getSignature($arrdata); return $paySign; }
支付签名(paySign)生成方法 @param string $package 订单详情字串 @param string $timeStamp 当前时间戳(需与JS输出的一致) @param string $nonceStr 随机串(需与JS输出的一致) @return string 返回签名字串
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/org/old_version/Thinkphp/Wechatpay.class.php#L332-L336
ddvphp/wechat
org/old_version/Thinkphp/Wechatpay.class.php
Wechatpay.checkOrderSignature
public function checkOrderSignature($orderxml=''){ if (!$orderxml) { $postStr = file_get_contents("php://input"); if (!empty($postStr)) { $orderxml = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); } else return false; } $arrdata = array('appid'=>$orderxml['AppId'],'appkey'=>$this->paysignkey,'timestamp'=>$orderxml['TimeStamp'],'noncestr'=>$orderxml['NonceStr'],'openid'=>$orderxml['OpenId'],'issubscribe'=>$orderxml['IsSubscribe']); $paySign = $this->getSignature($arrdata); if ($paySign!=$orderxml['AppSignature']) return false; return true; }
php
public function checkOrderSignature($orderxml=''){ if (!$orderxml) { $postStr = file_get_contents("php://input"); if (!empty($postStr)) { $orderxml = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); } else return false; } $arrdata = array('appid'=>$orderxml['AppId'],'appkey'=>$this->paysignkey,'timestamp'=>$orderxml['TimeStamp'],'noncestr'=>$orderxml['NonceStr'],'openid'=>$orderxml['OpenId'],'issubscribe'=>$orderxml['IsSubscribe']); $paySign = $this->getSignature($arrdata); if ($paySign!=$orderxml['AppSignature']) return false; return true; }
回调通知签名验证 @param array $orderxml 返回的orderXml的数组表示,留空则自动从post数据获取 @return boolean
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/org/old_version/Thinkphp/Wechatpay.class.php#L343-L354
ddvphp/wechat
org/old_version/Thinkphp/Wechatpay.class.php
Wechatpay.sendPayDeliverNotify
public function sendPayDeliverNotify($openid,$transid,$out_trade_no,$status=1,$msg='ok'){ if (!$this->access_token && !$this->checkAuth()) return false; $postdata = array( "appid"=>$this->appid, "appkey"=>$this->paysignkey, "openid"=>$openid, "transid"=>strval($transid), "out_trade_no"=>strval($out_trade_no), "deliver_timestamp"=>strval(time()), "deliver_status"=>strval($status), "deliver_msg"=>$msg, ); $postdata['app_signature'] = $this->getSignature($postdata); $postdata['sign_method'] = 'sha1'; unset($postdata['appkey']); $result = $this->http_post(self::API_BASE_URL_PREFIX.self::PAY_DELIVERNOTIFY.'access_token='.$this->access_token,self::json_encode($postdata)); if ($result) { $json = json_decode($result,true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return false; } return $json; } return false; }
php
public function sendPayDeliverNotify($openid,$transid,$out_trade_no,$status=1,$msg='ok'){ if (!$this->access_token && !$this->checkAuth()) return false; $postdata = array( "appid"=>$this->appid, "appkey"=>$this->paysignkey, "openid"=>$openid, "transid"=>strval($transid), "out_trade_no"=>strval($out_trade_no), "deliver_timestamp"=>strval(time()), "deliver_status"=>strval($status), "deliver_msg"=>$msg, ); $postdata['app_signature'] = $this->getSignature($postdata); $postdata['sign_method'] = 'sha1'; unset($postdata['appkey']); $result = $this->http_post(self::API_BASE_URL_PREFIX.self::PAY_DELIVERNOTIFY.'access_token='.$this->access_token,self::json_encode($postdata)); if ($result) { $json = json_decode($result,true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return false; } return $json; } return false; }
发货通知 @param string $openid 用户open_id @param string $transid 交易单号 @param string $out_trade_no 第三方订单号 @param int $status 0:发货失败;1:已发货 @param string $msg 失败原因 @return boolean|array
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/org/old_version/Thinkphp/Wechatpay.class.php#L365-L392
ddvphp/wechat
org/old_version/Thinkphp/Wechatpay.class.php
Wechatpay.getPayOrder
public function getPayOrder($out_trade_no) { if (!$this->access_token && !$this->checkAuth()) return false; $sign = strtoupper(md5("out_trade_no=$out_trade_no&partner={$this->partnerid}&key={$this->partnerkey}")); $postdata = array( "appid"=>$this->appid, "appkey"=>$this->paysignkey, "package"=>"out_trade_no=$out_trade_no&partner={$this->partnerid}&sign=$sign", "timestamp"=>strval(time()), ); $postdata['app_signature'] = $this->getSignature($postdata); $postdata['sign_method'] = 'sha1'; unset($postdata['appkey']); $result = $this->http_post(self::API_BASE_URL_PREFIX.self::PAY_ORDERQUERY.'access_token='.$this->access_token,self::json_encode($postdata)); if ($result) { $json = json_decode($result,true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg'].json_encode($postdata); return false; } return $json["order_info"]; } return false; }
php
public function getPayOrder($out_trade_no) { if (!$this->access_token && !$this->checkAuth()) return false; $sign = strtoupper(md5("out_trade_no=$out_trade_no&partner={$this->partnerid}&key={$this->partnerkey}")); $postdata = array( "appid"=>$this->appid, "appkey"=>$this->paysignkey, "package"=>"out_trade_no=$out_trade_no&partner={$this->partnerid}&sign=$sign", "timestamp"=>strval(time()), ); $postdata['app_signature'] = $this->getSignature($postdata); $postdata['sign_method'] = 'sha1'; unset($postdata['appkey']); $result = $this->http_post(self::API_BASE_URL_PREFIX.self::PAY_ORDERQUERY.'access_token='.$this->access_token,self::json_encode($postdata)); if ($result) { $json = json_decode($result,true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg'].json_encode($postdata); return false; } return $json["order_info"]; } return false; }
查询订单信息 @param string $out_trade_no 订单号 @return boolean|array
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/org/old_version/Thinkphp/Wechatpay.class.php#L399-L423
ddvphp/wechat
org/old_version/Thinkphp/Wechatpay.class.php
Wechatpay.getAddrSign
public function getAddrSign($url, $timeStamp, $nonceStr, $user_token=''){ if (!$user_token) $user_token = $this->user_token; if (!$user_token) { $this->errMsg = 'no user access token found!'; return false; } $url = htmlspecialchars_decode($url); $arrdata = array( 'appid'=>$this->appid, 'url'=>$url, 'timestamp'=>strval($timeStamp), 'noncestr'=>$nonceStr, 'accesstoken'=>$user_token ); return $this->getSignature($arrdata); }
php
public function getAddrSign($url, $timeStamp, $nonceStr, $user_token=''){ if (!$user_token) $user_token = $this->user_token; if (!$user_token) { $this->errMsg = 'no user access token found!'; return false; } $url = htmlspecialchars_decode($url); $arrdata = array( 'appid'=>$this->appid, 'url'=>$url, 'timestamp'=>strval($timeStamp), 'noncestr'=>$nonceStr, 'accesstoken'=>$user_token ); return $this->getSignature($arrdata); }
获取收货地址JS的签名 @tutorial 参考weixin.js脚本的WeixinJS.editAddress方法调用 @param string $appId @param string $url @param int $timeStamp @param string $nonceStr @param string $user_token @return Ambigous <boolean, string>
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/org/old_version/Thinkphp/Wechatpay.class.php#L444-L459
luoxiaojun1992/lb_framework
components/traits/lb/Config.php
Config.getCustomConfig
public function getCustomConfig($name = '') { $custom_config = $this->getConfigByName('custom'); return $name ? ($custom_config[$name] ?? null) : $custom_config; }
php
public function getCustomConfig($name = '') { $custom_config = $this->getConfigByName('custom'); return $name ? ($custom_config[$name] ?? null) : $custom_config; }
Get Custom Configuration @param string $name @return array|null
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/traits/lb/Config.php#L100-L104
luoxiaojun1992/lb_framework
components/traits/lb/Config.php
Config.getConfigByName
public function getConfigByName($config_name) { if ($this->isSingle()) { if (isset($this->containers['config'])) { return $this->containers['config']->get($config_name); } } return []; }
php
public function getConfigByName($config_name) { if ($this->isSingle()) { if (isset($this->containers['config'])) { return $this->containers['config']->get($config_name); } } return []; }
Get Configuration By Name @param $config_name @return array
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/traits/lb/Config.php#L215-L223
luoxiaojun1992/lb_framework
components/traits/lb/Config.php
Config.getUrlManagerConfig
public function getUrlManagerConfig($item) { $urlManager = $this->getConfigByName('urlManager'); if (isset($urlManager[$item])) { return $urlManager[$item]; } return false; }
php
public function getUrlManagerConfig($item) { $urlManager = $this->getConfigByName('urlManager'); if (isset($urlManager[$item])) { return $urlManager[$item]; } return false; }
Get Url Manager Config By Item Name @param $item @return bool
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/traits/lb/Config.php#L231-L238
luoxiaojun1992/lb_framework
components/traits/lb/Config.php
Config.getJsFiles
public function getJsFiles($controller_id, $template_id) { $js_files = []; $asset_config = $this->getConfigByName('assets'); if (isset($asset_config[$controller_id][$template_id]['js'])) { $js_files = $asset_config[$controller_id][$template_id]['js']; } return $js_files; }
php
public function getJsFiles($controller_id, $template_id) { $js_files = []; $asset_config = $this->getConfigByName('assets'); if (isset($asset_config[$controller_id][$template_id]['js'])) { $js_files = $asset_config[$controller_id][$template_id]['js']; } return $js_files; }
Get Js Files @param $controller_id @param $template_id @return array
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/traits/lb/Config.php#L267-L275
luoxiaojun1992/lb_framework
components/traits/lb/Config.php
Config.getCssFiles
public function getCssFiles($controller_id, $template_id) { $css_files = []; $asset_config = $this->getConfigByName('assets'); if (isset($asset_config[$controller_id][$template_id]['css'])) { $css_files = $asset_config[$controller_id][$template_id]['css']; } return $css_files; }
php
public function getCssFiles($controller_id, $template_id) { $css_files = []; $asset_config = $this->getConfigByName('assets'); if (isset($asset_config[$controller_id][$template_id]['css'])) { $css_files = $asset_config[$controller_id][$template_id]['css']; } return $css_files; }
Get Css Files @param $controller_id @param $template_id @return array
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/traits/lb/Config.php#L284-L292
luoxiaojun1992/lb_framework
components/traits/lb/Config.php
Config.initConfig
protected function initConfig() { if (defined('CONFIG_FILE') && file_exists(CONFIG_FILE)) { $this->config = include_once CONFIG_FILE; } // Inject Config Container $config_container = ConfigContainer::component(); foreach ($this->config as $config_name => $config_content) { $config_container->set($config_name, $config_content); yield; } $this->config = []; Lb::app()->containers['config'] = $config_container; }
php
protected function initConfig() { if (defined('CONFIG_FILE') && file_exists(CONFIG_FILE)) { $this->config = include_once CONFIG_FILE; } // Inject Config Container $config_container = ConfigContainer::component(); foreach ($this->config as $config_name => $config_content) { $config_container->set($config_name, $config_content); yield; } $this->config = []; Lb::app()->containers['config'] = $config_container; }
Init Configuration
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/traits/lb/Config.php#L417-L431
Synapse-Cmf/synapse-cmf
src/Synapse/Cmf/Framework/Engine/Decorator/Component/ComponentDecorator.php
ComponentDecorator.prepare
public function prepare( $content, ThemeInterface $theme, TemplateInterface $template, ZoneInterface $zone, ComponentInterface $component ) { $this->contextStack->push( $this->contextBuilder ->setContent($content) ->setTheme($theme) ->setTemplate($template) ->setZone($zone) ->setComponent($component) ->createContext() ); return $this; }
php
public function prepare( $content, ThemeInterface $theme, TemplateInterface $template, ZoneInterface $zone, ComponentInterface $component ) { $this->contextStack->push( $this->contextBuilder ->setContent($content) ->setTheme($theme) ->setTemplate($template) ->setZone($zone) ->setComponent($component) ->createContext() ); return $this; }
Prepare decorator context. @param ContentInterface|Content $content @param ThemeInterface $theme @param TemplateInterface $template @param ZoneInterface $zone @param ComponentInterface $component @return self
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Framework/Engine/Decorator/Component/ComponentDecorator.php#L64-L82
znframework/package-hypertext
BootstrapAttributes.php
BootstrapAttributes.popover
public function popover(String $placement, $content = NULL) { if( is_string($content) ) { return $this->dataContainer('body')->dataToggle('popover')->dataPlacement($placement)->dataContent($content); } return $this->usePropertyOptions($placement, $content, __FUNCTION__); }
php
public function popover(String $placement, $content = NULL) { if( is_string($content) ) { return $this->dataContainer('body')->dataToggle('popover')->dataPlacement($placement)->dataContent($content); } return $this->usePropertyOptions($placement, $content, __FUNCTION__); }
Bootstrap opover attribute @param string $placement @param string $content @return this
https://github.com/znframework/package-hypertext/blob/12bbc3bd47a2fae735f638a3e01cc82c1b9c9005/BootstrapAttributes.php#L24-L32
znframework/package-hypertext
BootstrapAttributes.php
BootstrapAttributes.tooltip
public function tooltip(String $placement, $content = NULL, Bool $html = NULL) { if( is_string($content) ) { return $this->title($content)->dataHtml($html === true ? 'true' : $html)->dataToggle('tooltip')->dataPlacement($placement); } return $this->usePropertyOptions($placement, $content, __FUNCTION__); }
php
public function tooltip(String $placement, $content = NULL, Bool $html = NULL) { if( is_string($content) ) { return $this->title($content)->dataHtml($html === true ? 'true' : $html)->dataToggle('tooltip')->dataPlacement($placement); } return $this->usePropertyOptions($placement, $content, __FUNCTION__); }
Bootstrap opover attribute @param string $placement @param string $content @param bool $html = NULL @return this
https://github.com/znframework/package-hypertext/blob/12bbc3bd47a2fae735f638a3e01cc82c1b9c9005/BootstrapAttributes.php#L43-L51
znframework/package-hypertext
BootstrapAttributes.php
BootstrapAttributes.usePropertyOptions
protected function usePropertyOptions($selector, $content, $type) { $this->isBootstrapAttribute('on', function($return) use($type) { $this->settings['attr']['on'] = Base::suffix($return, '.bs.' . $type); }); return $this->bootstrapObjectOptions($selector === 'all' ? '[data-toggle="'.$type.'"]' : $selector, $content ?? [], $type); }
php
protected function usePropertyOptions($selector, $content, $type) { $this->isBootstrapAttribute('on', function($return) use($type) { $this->settings['attr']['on'] = Base::suffix($return, '.bs.' . $type); }); return $this->bootstrapObjectOptions($selector === 'all' ? '[data-toggle="'.$type.'"]' : $selector, $content ?? [], $type); }
Protected use property options
https://github.com/znframework/package-hypertext/blob/12bbc3bd47a2fae735f638a3e01cc82c1b9c9005/BootstrapAttributes.php#L56-L64
eloquent/endec
src/Base64/Base64MimeEncodeTransform.php
Base64MimeEncodeTransform.transform
public function transform($data, &$context, $isEnd = false) { if (null === $context) { $context = ''; } $context .= $data; $bufferSize = strlen($context); $output = ''; $consume = $this->blocksSize($bufferSize, 57, $isEnd); if ($consume) { $output = chunk_split( base64_encode(substr($context, 0, $consume)) ); if ($bufferSize === $consume) { $context = ''; } else { $context = substr($context, $consume); } } return array($output, strlen($data), null); }
php
public function transform($data, &$context, $isEnd = false) { if (null === $context) { $context = ''; } $context .= $data; $bufferSize = strlen($context); $output = ''; $consume = $this->blocksSize($bufferSize, 57, $isEnd); if ($consume) { $output = chunk_split( base64_encode(substr($context, 0, $consume)) ); if ($bufferSize === $consume) { $context = ''; } else { $context = substr($context, $consume); } } return array($output, strlen($data), null); }
Transform the supplied data. This method may transform only part of the supplied data. The return value includes information about how much data was actually consumed. The transform can be forced to consume all data by passing a boolean true as the $isEnd argument. The $context argument will initially be null, but any value assigned to this variable will persist until the stream transformation is complete. It can be used as a place to store state, such as a buffer. It is guaranteed that this method will be called with $isEnd = true once, and only once, at the end of the stream transformation. @param string $data The data to transform. @param mixed &$context An arbitrary context value. @param boolean $isEnd True if all supplied data must be transformed. @return tuple<string,integer,mixed> A 3-tuple of the transformed data, the number of bytes consumed, and any resulting error.
https://github.com/eloquent/endec/blob/90043a26439739d6bac631cc57dab3ecf5cafdc3/src/Base64/Base64MimeEncodeTransform.php#L60-L83
Etenil/assegai
src/assegai/modules/mail/services/ses/utilities/complextype.class.php
CFComplexType.json
public static function json($json, $member = '', $default_key = '') { return self::option_group(json_decode($json, true), $member, $default_key); }
php
public static function json($json, $member = '', $default_key = '') { return self::option_group(json_decode($json, true), $member, $default_key); }
Takes a JSON object, as a string, to convert to query string keys. @param string $json (Required) A JSON object. The JSON string should use canonical rules (e.g., double quotes, quoted keys) as is required by PHP's <php:json_encode()> function. @param string $member (Optional) The name of the "member" property that AWS uses for lists in certain services. Defaults to an empty string. @param string $default_key (Optional) The default key to use when the value for `$data` is a string. Defaults to an empty string. @return array The option group parameters to merge into another method's `$opt` parameter.
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mail/services/ses/utilities/complextype.class.php#L39-L42
Etenil/assegai
src/assegai/modules/mail/services/ses/utilities/complextype.class.php
CFComplexType.yaml
public static function yaml($yaml, $member = '', $default_key = '') { return self::option_group(sfYaml::load($yaml), $member, $default_key); }
php
public static function yaml($yaml, $member = '', $default_key = '') { return self::option_group(sfYaml::load($yaml), $member, $default_key); }
Takes a YAML object, as a string, to convert to query string keys. @param string $yaml (Required) A YAML object. @param string $member (Optional) The name of the "member" property that AWS uses for lists in certain services. Defaults to an empty string. @param string $default_key (Optional) The default key to use when the value for `$data` is a string. Defaults to an empty string. @return array The option group parameters to merge into another method's `$opt` parameter.
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mail/services/ses/utilities/complextype.class.php#L52-L55
Etenil/assegai
src/assegai/modules/mail/services/ses/utilities/complextype.class.php
CFComplexType.option_group
public static function option_group($data, $member = '', $key = '', &$out = array()) { $reset = $key; if (is_array($data)) { foreach ($data as $k => $v) { // Avoid 0-based indexes. if (is_int($k)) { $k = $k + 1; if ($member !== '') { $key .= '.' . $member; } } $key .= (($key === '') ? $k : '.' . $k); if (is_array($v)) { self::option_group($v, $member, $key, $out); } elseif ($v instanceof CFStepConfig) { self::option_group($v->get_config(), $member, $key, $out); } else { $out[$key] = $v; } $key = $reset; } } else { $out[$key] = $data; } return $out; }
php
public static function option_group($data, $member = '', $key = '', &$out = array()) { $reset = $key; if (is_array($data)) { foreach ($data as $k => $v) { // Avoid 0-based indexes. if (is_int($k)) { $k = $k + 1; if ($member !== '') { $key .= '.' . $member; } } $key .= (($key === '') ? $k : '.' . $k); if (is_array($v)) { self::option_group($v, $member, $key, $out); } elseif ($v instanceof CFStepConfig) { self::option_group($v->get_config(), $member, $key, $out); } else { $out[$key] = $v; } $key = $reset; } } else { $out[$key] = $data; } return $out; }
A protected method that is used by <json()>, <yaml()> and <map()>. @param string|array $data (Required) The data to iterate over. @param string $member (Optional) The name of the "member" property that AWS uses for lists in certain services. Defaults to an empty string. @param string $key (Optional) The default key to use when the value for `$data` is a string. Defaults to an empty string. @param array $out (Optional) INTERNAL ONLY. The array that contains the calculated values up to this point. @return array The option group parameters to merge into another method's `$opt` parameter.
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mail/services/ses/utilities/complextype.class.php#L79-L122
alekitto/metadata
lib/Exception/InvalidArgumentException.php
InvalidArgumentException.create
public static function create($reason): self { $arguments = func_get_args(); switch ($reason) { case static::CLASS_DOES_NOT_EXIST: $message = sprintf('Class %s does not exist. Cannot retrieve its metadata', $arguments[1]); return new static($message); case static::VALUE_IS_NOT_AN_OBJECT: $message = sprintf('Cannot create metadata for non-objects. Got: "%s"', gettype($arguments[1])); return new static($message); case static::NOT_MERGEABLE_METADATA: $message = sprintf( 'Cannot merge metadata of class "%s" with "%s"', is_object($arguments[2]) ? get_class($arguments[2]) : $arguments[2], is_object($arguments[1]) ? get_class($arguments[1]) : $arguments[1] ); return new static($message); case static::INVALID_METADATA_CLASS: $message = sprintf( '"%s" is not a valid metadata object class', is_object($arguments[1]) ? get_class($arguments[1]) : $arguments[1] ); return new static($message); case static::INVALID_PROCESSOR_INTERFACE_CLASS: $message = sprintf( '"%s" is not a valid ProcessorInterface class', $arguments[1] ); return new static($message); } return new static(call_user_func_array('sprintf', $arguments)); }
php
public static function create($reason): self { $arguments = func_get_args(); switch ($reason) { case static::CLASS_DOES_NOT_EXIST: $message = sprintf('Class %s does not exist. Cannot retrieve its metadata', $arguments[1]); return new static($message); case static::VALUE_IS_NOT_AN_OBJECT: $message = sprintf('Cannot create metadata for non-objects. Got: "%s"', gettype($arguments[1])); return new static($message); case static::NOT_MERGEABLE_METADATA: $message = sprintf( 'Cannot merge metadata of class "%s" with "%s"', is_object($arguments[2]) ? get_class($arguments[2]) : $arguments[2], is_object($arguments[1]) ? get_class($arguments[1]) : $arguments[1] ); return new static($message); case static::INVALID_METADATA_CLASS: $message = sprintf( '"%s" is not a valid metadata object class', is_object($arguments[1]) ? get_class($arguments[1]) : $arguments[1] ); return new static($message); case static::INVALID_PROCESSOR_INTERFACE_CLASS: $message = sprintf( '"%s" is not a valid ProcessorInterface class', $arguments[1] ); return new static($message); } return new static(call_user_func_array('sprintf', $arguments)); }
Create a new instance of InvalidArgumentException with meaningful message. @param $reason @return self
https://github.com/alekitto/metadata/blob/0422ac8d7fe72d5fa8cc51b6f1e173866e8afb2c/lib/Exception/InvalidArgumentException.php#L20-L62
event-bus/event-dispatcher
src/Util/Pattern/PatternFactory.php
PatternFactory.getPatternFor
public static function getPatternFor(Pattern $parent, $word) { if (self::isWildcard($word)) { return self::getWildcardPattern($parent, $word); } return new Word($word); }
php
public static function getPatternFor(Pattern $parent, $word) { if (self::isWildcard($word)) { return self::getWildcardPattern($parent, $word); } return new Word($word); }
Builds a pattern node based on a given word and its parent. @param Pattern $parent The parent pattern object, in case a loop node will be built. @param string $word A single word from a composite pattern. @return Pattern A pattern object.
https://github.com/event-bus/event-dispatcher/blob/0954a9fe0084fbd096b1c32e386c21fb4754b5ff/src/Util/Pattern/PatternFactory.php#L20-L27