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
asbamboo/http
RedirectResponse.php
RedirectResponse.setTargetUri
public function setTargetUri(string $target_uri) : self { $this->target_uri = $target_uri; $this->addHeader('location', $target_uri); $this->setBody(new Stream('php://temp', 'w+b'))->getBody()->write(sprintf(' <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta http-equiv="refresh" content="0;url=%1$s" /> <title>Redirecting to %1$s</title> </head> <body> Redirecting to <a href="%1$s">%1$s</a>. </body> </html>', htmlspecialchars($target_uri, ENT_QUOTES, 'UTF-8') )); $this->getBody()->rewind(); return $this; }
php
public function setTargetUri(string $target_uri) : self { $this->target_uri = $target_uri; $this->addHeader('location', $target_uri); $this->setBody(new Stream('php://temp', 'w+b'))->getBody()->write(sprintf(' <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta http-equiv="refresh" content="0;url=%1$s" /> <title>Redirecting to %1$s</title> </head> <body> Redirecting to <a href="%1$s">%1$s</a>. </body> </html>', htmlspecialchars($target_uri, ENT_QUOTES, 'UTF-8') )); $this->getBody()->rewind(); return $this; }
设置跳转目标 @param string $target_uri @return self
https://github.com/asbamboo/http/blob/721156e29227854b787a1232eaa995ab2ccd4f25/RedirectResponse.php#L38-L59
ben-gibson/foursquare-venue-client
src/Options/Search.php
Search.parametrise
public function parametrise() { return array_filter([ 'limit' => $this->limit, 'll' => $this->coordinates, 'near' => $this->place, 'radius' => $this->radius, 'query' => $this->query, 'categoryId' => implode(',', $this->categoryIds) ]); }
php
public function parametrise() { return array_filter([ 'limit' => $this->limit, 'll' => $this->coordinates, 'near' => $this->place, 'radius' => $this->radius, 'query' => $this->query, 'categoryId' => implode(',', $this->categoryIds) ]); }
{@inheritdoc}
https://github.com/ben-gibson/foursquare-venue-client/blob/ce5e7c308f87d5ccc28ab8d27a9cb51bd106d969/src/Options/Search.php#L103-L113
pmdevelopment/tool-bundle
Controller/SitemapController.php
SitemapController.defaultAction
public function defaultAction(Request $request) { $localeDefault = $request->getDefaultLocale(); $locales = $this->getParameter('pm__tool.configuration.sitemap.locales'); if (true === empty($locales)) { $locales = []; } else { $locales = explode('|', $locales); } $router = $this->get('router'); $xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8" ?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"></urlset>'); foreach ($router->getRouteCollection()->all() as $routeKey => $routeAnnotation) { if (false === array_key_exists('sitemap', $routeAnnotation->getOptions())) { continue; } $routeOptions = $routeAnnotation->getOptions(); if (true !== $routeOptions['sitemap']) { continue; } $url = $router->generate($routeKey, [ '_locale' => $localeDefault, ], RouterInterface::ABSOLUTE_URL); $xmlUrl = $xml->addChild('url'); /* Default locale */ $xmlUrl->addChild('loc', $url); /* All locales */ foreach ($locales as $locale) { $url = $router->generate($routeKey, [ '_locale' => $locale, ], RouterInterface::ABSOLUTE_URL); $xmlLocale = $xmlUrl->addChild('xhtml:link', null); $xmlLocale->addAttribute('rel', 'alternate'); $xmlLocale->addAttribute('hreflang', $locale); $xmlLocale->addAttribute('href', $url); } } return new Response( $xml->asXML(), Response::HTTP_OK, [ 'Content-Type' => 'application/xml', ] ); }
php
public function defaultAction(Request $request) { $localeDefault = $request->getDefaultLocale(); $locales = $this->getParameter('pm__tool.configuration.sitemap.locales'); if (true === empty($locales)) { $locales = []; } else { $locales = explode('|', $locales); } $router = $this->get('router'); $xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8" ?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"></urlset>'); foreach ($router->getRouteCollection()->all() as $routeKey => $routeAnnotation) { if (false === array_key_exists('sitemap', $routeAnnotation->getOptions())) { continue; } $routeOptions = $routeAnnotation->getOptions(); if (true !== $routeOptions['sitemap']) { continue; } $url = $router->generate($routeKey, [ '_locale' => $localeDefault, ], RouterInterface::ABSOLUTE_URL); $xmlUrl = $xml->addChild('url'); /* Default locale */ $xmlUrl->addChild('loc', $url); /* All locales */ foreach ($locales as $locale) { $url = $router->generate($routeKey, [ '_locale' => $locale, ], RouterInterface::ABSOLUTE_URL); $xmlLocale = $xmlUrl->addChild('xhtml:link', null); $xmlLocale->addAttribute('rel', 'alternate'); $xmlLocale->addAttribute('hreflang', $locale); $xmlLocale->addAttribute('href', $url); } } return new Response( $xml->asXML(), Response::HTTP_OK, [ 'Content-Type' => 'application/xml', ] ); }
Default @return Response @Route("/sitemap.xml")
https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Controller/SitemapController.php#L32-L87
austinkregel/formmodel
src/FormModel/Frameworks/Bootstrap.php
Bootstrap.form
public function form(array $options = []) { $method = empty($options['method']) ? $options['method'] : ''; if (in_array(strtolower($method), ['get', 'post'])) { $real_method = $method; } else { $real_method = 'POST'; } $options['method'] = $real_method; $options['action'] = $this->location; return '<form '.$this->attributes($options).'>'.// Pass the method through so the form knows how to handle it's self (with laravel) $this->method($method).// Check and fill the csrf token if it's configured for it. $this->csrf().$this->buildForm().$this->submit([]).'</form>'; }
php
public function form(array $options = []) { $method = empty($options['method']) ? $options['method'] : ''; if (in_array(strtolower($method), ['get', 'post'])) { $real_method = $method; } else { $real_method = 'POST'; } $options['method'] = $real_method; $options['action'] = $this->location; return '<form '.$this->attributes($options).'>'.// Pass the method through so the form knows how to handle it's self (with laravel) $this->method($method).// Check and fill the csrf token if it's configured for it. $this->csrf().$this->buildForm().$this->submit([]).'</form>'; }
Generate the form. @param array $options @return string
https://github.com/austinkregel/formmodel/blob/49943a8f563d2e9028f6bc992708e104f9be22e3/src/FormModel/Frameworks/Bootstrap.php#L14-L28
selikhovleonid/nadir
src/core/Headers.php
Headers.add
public function add($sHeader) { foreach ($this->headerList as $sTmp) { if ($sTmp == $sHeader) { throw new Exception("The '{$sHeader}' header has already been added."); } } $this->headerList[] = $sHeader; return self::$instance; }
php
public function add($sHeader) { foreach ($this->headerList as $sTmp) { if ($sTmp == $sHeader) { throw new Exception("The '{$sHeader}' header has already been added."); } } $this->headerList[] = $sHeader; return self::$instance; }
It adds the header to the stack. @param string $sHeader The page header. @return self. @throws \core\Exception It throws if passed header was already added earlier.
https://github.com/selikhovleonid/nadir/blob/47545fccd8516c8f0a20c02ba62f68269c7199da/src/core/Headers.php#L136-L145
selikhovleonid/nadir
src/core/Headers.php
Headers.addByHttpCode
public function addByHttpCode($nCode) { $sProtocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1'; $sHeader = "{$sProtocol} {$nCode} " .self::getHTTPExplanationByCode($nCode); return $this->add($sHeader); }
php
public function addByHttpCode($nCode) { $sProtocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1'; $sHeader = "{$sProtocol} {$nCode} " .self::getHTTPExplanationByCode($nCode); return $this->add($sHeader); }
It adds the header to the stack by HTTP code. @param integer $nCode The code. @return self.
https://github.com/selikhovleonid/nadir/blob/47545fccd8516c8f0a20c02ba62f68269c7199da/src/core/Headers.php#L152-L159
selikhovleonid/nadir
src/core/Headers.php
Headers.run
public function run() { $this->isRan = true; foreach ($this->headerList as $sHeader) { header($sHeader); } }
php
public function run() { $this->isRan = true; foreach ($this->headerList as $sHeader) { header($sHeader); } }
The main execution method. It sets all added headers into the page. @return void.
https://github.com/selikhovleonid/nadir/blob/47545fccd8516c8f0a20c02ba62f68269c7199da/src/core/Headers.php#L183-L189
Speicher210/fastbill-api
src/Serializer/Handler/DateHandler.php
DateHandler.serializeDateTime
public function serializeDateTime(VisitorInterface $visitor, \DateTime $date, array $type, Context $context) { // All dates send to Fastbill should be in Europe/Berlin timezone. $date->setTimezone(new \DateTimeZone('Europe/Berlin')); return parent::serializeDateTime($visitor, $date, $type, $context); }
php
public function serializeDateTime(VisitorInterface $visitor, \DateTime $date, array $type, Context $context) { // All dates send to Fastbill should be in Europe/Berlin timezone. $date->setTimezone(new \DateTimeZone('Europe/Berlin')); return parent::serializeDateTime($visitor, $date, $type, $context); }
{@inheritdoc}
https://github.com/Speicher210/fastbill-api/blob/37034324c35a2c6ed7d2c3b64aad670721aba22e/src/Serializer/Handler/DateHandler.php#L23-L29
LoggerEssentials/LoggerEssentials
src/Formatters/ContextJsonFormatter.php
ContextJsonFormatter.log
public function log($level, $message, array $context = array()) { $ctx = $context; if(!count($ctx)) { $ctx = new \stdClass(); } $message = sprintf($this->format, $message, json_encode($ctx, $this->jsonOptions)); $this->logger()->log($level, $message, $context); }
php
public function log($level, $message, array $context = array()) { $ctx = $context; if(!count($ctx)) { $ctx = new \stdClass(); } $message = sprintf($this->format, $message, json_encode($ctx, $this->jsonOptions)); $this->logger()->log($level, $message, $context); }
Logs with an arbitrary level. @param string $level @param string $message @param array $context @return void
https://github.com/LoggerEssentials/LoggerEssentials/blob/f32f9b865eacfccced90697f3eb69dc4ad80dc96/src/Formatters/ContextJsonFormatter.php#L31-L38
andyburton/Sonic-Framework
src/Controller/Tools.php
Tools.clearcache
public function clearcache () { if ($this->view instanceof \Sonic\View\Smarty) { $this->view->clearCompiledTemplate (); $this->view->clearAllCache (); } new \Sonic\Message ('success', 'Cache Cleared'); $this->template = 'tools/index.tpl'; }
php
public function clearcache () { if ($this->view instanceof \Sonic\View\Smarty) { $this->view->clearCompiledTemplate (); $this->view->clearAllCache (); } new \Sonic\Message ('success', 'Cache Cleared'); $this->template = 'tools/index.tpl'; }
Clear the view cache
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Controller/Tools.php#L41-L53
andyburton/Sonic-Framework
src/Controller/Tools.php
Tools.comment
public function comment () { // Set comment variables $comment = ''; $commentClean = ''; // If the form is submitted if (isset ($_POST['create_comment'])) { // Set clean comment $commentClean = Comment::cleanComment ($_POST['comment']); // Switch the type switch ($_POST['comment_type']) { // Line comment case 'line': $comment = Comment::lineComment ($_POST['comment']); break; // PHPDoc comment case 'phpdoc': $comment = Comment::phpdocComment ($_POST['comment']); break; // Star comment case 'star': default: $comment = Comment::starComment ($_POST['comment']); break; } } // Set comment $this->view->assign ('comment', $comment); $this->view->assign ('clean_comment', $commentClean); }
php
public function comment () { // Set comment variables $comment = ''; $commentClean = ''; // If the form is submitted if (isset ($_POST['create_comment'])) { // Set clean comment $commentClean = Comment::cleanComment ($_POST['comment']); // Switch the type switch ($_POST['comment_type']) { // Line comment case 'line': $comment = Comment::lineComment ($_POST['comment']); break; // PHPDoc comment case 'phpdoc': $comment = Comment::phpdocComment ($_POST['comment']); break; // Star comment case 'star': default: $comment = Comment::starComment ($_POST['comment']); break; } } // Set comment $this->view->assign ('comment', $comment); $this->view->assign ('clean_comment', $commentClean); }
Comment
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Controller/Tools.php#L87-L137
andyburton/Sonic-Framework
src/Controller/Tools.php
Tools.crypt
public function crypt () { // Set variables $original = ''; $type = ''; $crypt = ''; // If the form is submitted if (isset ($_POST['crypt'])) { // Get variables $original = $_POST['original']; $type = $_POST['type']; // Crypt switch ($type) { case 'md5': $crypt = md5 ($original); break; case 'sha1': $crypt = sha1 ($original); break; case 'sha256': $crypt = \Sonic\Resource\Crypt::_sha256 ($original); break; case 'bcrypt': $crypt = \Sonic\Resource\User::_Hash ($original); break; } } // Set template variables $this->view->assign ('original', $original); $this->view->assign ('type', $type); $this->view->assign ('crypt', $crypt); $this->view->assign ('options', [ 'bcrypt' => 'bcrypt', 'md5' => 'md5', 'sha1' => 'sha1', 'sha256' => 'sha256' ]); }
php
public function crypt () { // Set variables $original = ''; $type = ''; $crypt = ''; // If the form is submitted if (isset ($_POST['crypt'])) { // Get variables $original = $_POST['original']; $type = $_POST['type']; // Crypt switch ($type) { case 'md5': $crypt = md5 ($original); break; case 'sha1': $crypt = sha1 ($original); break; case 'sha256': $crypt = \Sonic\Resource\Crypt::_sha256 ($original); break; case 'bcrypt': $crypt = \Sonic\Resource\User::_Hash ($original); break; } } // Set template variables $this->view->assign ('original', $original); $this->view->assign ('type', $type); $this->view->assign ('crypt', $crypt); $this->view->assign ('options', [ 'bcrypt' => 'bcrypt', 'md5' => 'md5', 'sha1' => 'sha1', 'sha256' => 'sha256' ]); }
Crypt
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Controller/Tools.php#L144-L200
andyburton/Sonic-Framework
src/Controller/Tools.php
Tools.timestamp
public function timestamp () { // Set variables $date = ''; $format = 'd/m/Y H:i:s'; $timestamp = ''; // If the form is submitted if (isset ($_POST['format_timestamp'])) { // Get variables $format = $_POST['date_format']; $timestamp = $_POST['timestamp']; // Format $date = date ($format, $timestamp); } // Else if format date else if (isset ($_POST['format_date'])) { // Get variables $format = $_POST['date_format']; $date = $_POST['date']; // Convert to timestamp $timestamp = \Sonic\Resource\Parser::_convertToUnixtime ($date); } // Set template variables $this->view->assign ('date', $date); $this->view->assign ('date_format', $format); $this->view->assign ('timestamp', $timestamp); }
php
public function timestamp () { // Set variables $date = ''; $format = 'd/m/Y H:i:s'; $timestamp = ''; // If the form is submitted if (isset ($_POST['format_timestamp'])) { // Get variables $format = $_POST['date_format']; $timestamp = $_POST['timestamp']; // Format $date = date ($format, $timestamp); } // Else if format date else if (isset ($_POST['format_date'])) { // Get variables $format = $_POST['date_format']; $date = $_POST['date']; // Convert to timestamp $timestamp = \Sonic\Resource\Parser::_convertToUnixtime ($date); } // Set template variables $this->view->assign ('date', $date); $this->view->assign ('date_format', $format); $this->view->assign ('timestamp', $timestamp); }
Timestamps
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Controller/Tools.php#L217-L264
andyburton/Sonic-Framework
src/Controller/Tools.php
Tools.newclass
public function newclass () { // Create tool classes $class = new \Sonic\Model\Tools\NewClass; $db = new \Sonic\Model\Tools\Db; // If there is a table reload if (isset ($_POST['reload_tables']) && $_POST['reload_tables'] == '1') { $class->fromPost (); } // If the form is submitted or there is a URL action (from an overwrite/merge request) if (isset ($_POST['create_class']) || isset ($_POST['create_save_class']) || (isset ($_POST['create_action']) && !empty ($_POST['create_action']))) { // Set action, overwrite and merge status $action = $_POST['create_action'] == 'save' || isset ($_POST['create_save_class'])? 'save' : 'view'; $overwrite = $_POST['class_overwrite'] == '1'; $merge = $_POST['class_merge'] == '1'; // Get the class details from the form $class->fromPost (); // Split namespace to work out directory $namespace = explode ('\\', $class->get ('namespace')); // Set class path $classDir = ABS_CLASSES . implode ('/', $namespace) . '/'; $className = $class->get ('name') . '.php'; $classPath = $classDir . $className; // If the class already exists and there is no overwrite or merge if (file_exists ($classPath) && !$overwrite && !$merge) { // Request whether to overwrite or merge $this->template = 'tools/newclass_exists.tpl'; $this->view->assign ('action', $action); } // Else the class doesn't exist or we are overwriting or merging it else { // If we are merging if ($merge) { // Load the existing class $classData = file_get_contents ($classPath); // Generate new attributes $class->tabUp (FALSE); $class->generateAttributes (); // Replace attributes $properties = Comment::phpdocComment ($class->generateProperties ()); if (preg_match ('/\/\*\*\n \* Class Properties:\n(.*?)\n \*\//si', $classData) == 1) { $classData = preg_replace ('/\/\*\*\n \* Class Properties:\n(.*?)\n \*\//si', $properties, $classData); } else { $classData = preg_replace ('/\nclass ' . $class->get ('name') . '/si', "\n" . $properties . "\n\n" . 'class ' . $class->get ('name'), $classData); } $classData = preg_replace ('/\tprotected static \$attributes(.*?)\);\n/si', $class->class, $classData); } // Else just generate the class from scratch else { $classData = $class->Generate (); } // Set page variables $this->view->assign ('class_generated', $classData); $this->template = 'tools/newclass_submitted.tpl'; // If save if ($action == 'save') { // Make directory if (!is_dir ($classDir)) { mkdir ($classDir, 0700, TRUE); } // Write class if (file_put_contents ($classPath, $classData)) { new \Sonic\Message ('success', 'Class saved to ' . $classPath); } else { new \Sonic\Message ('error', 'Class could not be saved to ' . $classPath); } } } } // Set classes $this->view->assign ('class', $class); $this->view->assign ('db', $db); }
php
public function newclass () { // Create tool classes $class = new \Sonic\Model\Tools\NewClass; $db = new \Sonic\Model\Tools\Db; // If there is a table reload if (isset ($_POST['reload_tables']) && $_POST['reload_tables'] == '1') { $class->fromPost (); } // If the form is submitted or there is a URL action (from an overwrite/merge request) if (isset ($_POST['create_class']) || isset ($_POST['create_save_class']) || (isset ($_POST['create_action']) && !empty ($_POST['create_action']))) { // Set action, overwrite and merge status $action = $_POST['create_action'] == 'save' || isset ($_POST['create_save_class'])? 'save' : 'view'; $overwrite = $_POST['class_overwrite'] == '1'; $merge = $_POST['class_merge'] == '1'; // Get the class details from the form $class->fromPost (); // Split namespace to work out directory $namespace = explode ('\\', $class->get ('namespace')); // Set class path $classDir = ABS_CLASSES . implode ('/', $namespace) . '/'; $className = $class->get ('name') . '.php'; $classPath = $classDir . $className; // If the class already exists and there is no overwrite or merge if (file_exists ($classPath) && !$overwrite && !$merge) { // Request whether to overwrite or merge $this->template = 'tools/newclass_exists.tpl'; $this->view->assign ('action', $action); } // Else the class doesn't exist or we are overwriting or merging it else { // If we are merging if ($merge) { // Load the existing class $classData = file_get_contents ($classPath); // Generate new attributes $class->tabUp (FALSE); $class->generateAttributes (); // Replace attributes $properties = Comment::phpdocComment ($class->generateProperties ()); if (preg_match ('/\/\*\*\n \* Class Properties:\n(.*?)\n \*\//si', $classData) == 1) { $classData = preg_replace ('/\/\*\*\n \* Class Properties:\n(.*?)\n \*\//si', $properties, $classData); } else { $classData = preg_replace ('/\nclass ' . $class->get ('name') . '/si', "\n" . $properties . "\n\n" . 'class ' . $class->get ('name'), $classData); } $classData = preg_replace ('/\tprotected static \$attributes(.*?)\);\n/si', $class->class, $classData); } // Else just generate the class from scratch else { $classData = $class->Generate (); } // Set page variables $this->view->assign ('class_generated', $classData); $this->template = 'tools/newclass_submitted.tpl'; // If save if ($action == 'save') { // Make directory if (!is_dir ($classDir)) { mkdir ($classDir, 0700, TRUE); } // Write class if (file_put_contents ($classPath, $classData)) { new \Sonic\Message ('success', 'Class saved to ' . $classPath); } else { new \Sonic\Message ('error', 'Class could not be saved to ' . $classPath); } } } } // Set classes $this->view->assign ('class', $class); $this->view->assign ('db', $db); }
New class
https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Controller/Tools.php#L271-L406
acacha/forge-publish
src/Console/Commands/PublishAssignments.php
PublishAssignments.handle
public function handle() { $this->abortCommandExecution(); $this->assignments = $this->fetchAssignments(); $headers = ['Id', 'Name','Repository','Repo Type','Forge site','Forge Server','Created','Updated']; $rows = []; foreach ($this->assignments as $assignment) { $rows[] = [ $assignment->id, $assignment->name, $assignment->repository_uri, $assignment->repository_type, $assignment->forge_site, $assignment->forge_server, $assignment->created_at, $assignment->updated_at ]; } $this->table($headers, $rows); }
php
public function handle() { $this->abortCommandExecution(); $this->assignments = $this->fetchAssignments(); $headers = ['Id', 'Name','Repository','Repo Type','Forge site','Forge Server','Created','Updated']; $rows = []; foreach ($this->assignments as $assignment) { $rows[] = [ $assignment->id, $assignment->name, $assignment->repository_uri, $assignment->repository_type, $assignment->forge_site, $assignment->forge_server, $assignment->created_at, $assignment->updated_at ]; } $this->table($headers, $rows); }
Execute the console command.
https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishAssignments.php#L62-L84
Phpillip/phpillip
src/Service/Pygments.php
Pygments.highlight
public function highlight($value, $language) { $path = tempnam($this->tmp, 'pyg'); if ($language === 'php' && substr($value, 0, 5) !== '<?php') { $value = '<?php ' . PHP_EOL . $value; } $this->files->dumpFile($path, $value); $value = $this->pygmentize($path, $language); unlink($path); if (preg_match('#^<div class="highlight"><pre>#', $value) && preg_match('#</pre></div>$#', $value)) { return substr($value, 28, strlen($value) - 40); } return $value; }
php
public function highlight($value, $language) { $path = tempnam($this->tmp, 'pyg'); if ($language === 'php' && substr($value, 0, 5) !== '<?php') { $value = '<?php ' . PHP_EOL . $value; } $this->files->dumpFile($path, $value); $value = $this->pygmentize($path, $language); unlink($path); if (preg_match('#^<div class="highlight"><pre>#', $value) && preg_match('#</pre></div>$#', $value)) { return substr($value, 28, strlen($value) - 40); } return $value; }
Highlight a portion of code with pygmentize @param string $value @param string $language @return string
https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/Service/Pygments.php#L47-L66
Phpillip/phpillip
src/Service/Pygments.php
Pygments.pygmentize
public function pygmentize($path, $language) { $process = new Process(sprintf('pygmentize -f html -l %s %s', $language, $path)); $process->run(); if (!$process->isSuccessful()) { throw new RuntimeException($process->getErrorOutput()); } return trim($process->getOutput()); }
php
public function pygmentize($path, $language) { $process = new Process(sprintf('pygmentize -f html -l %s %s', $language, $path)); $process->run(); if (!$process->isSuccessful()) { throw new RuntimeException($process->getErrorOutput()); } return trim($process->getOutput()); }
Run 'pygmentize' command on the given file @param string $path @param string $language @return string
https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/Service/Pygments.php#L76-L87
upiksaleh/codeup-yihai
src/theming/SideBar.php
SideBar.run
public function run() { if ($this->route === null && Cii::$app->controller !== null) { $this->route = Cii::$app->controller->getRoute(); } if ($this->params === null) { $this->params = Cii::$app->request->getQueryParams(); } $posDefaultAction = strpos($this->route, Cii::$app->controller->defaultAction); if ($posDefaultAction) { $this->noDefaultAction = rtrim(substr($this->route, 0, $posDefaultAction), '/'); } else { $this->noDefaultAction = false; } $posDefaultRoute = strpos($this->route, Cii::$app->controller->module->defaultRoute); if ($posDefaultRoute) { $this->noDefaultRoute = rtrim(substr($this->route, 0, $posDefaultRoute), '/'); } else { $this->noDefaultRoute = false; } $items = $this->normalizeItems($this->items, $hasActiveChild); if (!empty($items)) { $options = $this->options; $tag = ArrayHelper::remove($options, 'tag', 'ul'); echo Html::tag($tag, $this->renderItems($items), $options); } }
php
public function run() { if ($this->route === null && Cii::$app->controller !== null) { $this->route = Cii::$app->controller->getRoute(); } if ($this->params === null) { $this->params = Cii::$app->request->getQueryParams(); } $posDefaultAction = strpos($this->route, Cii::$app->controller->defaultAction); if ($posDefaultAction) { $this->noDefaultAction = rtrim(substr($this->route, 0, $posDefaultAction), '/'); } else { $this->noDefaultAction = false; } $posDefaultRoute = strpos($this->route, Cii::$app->controller->module->defaultRoute); if ($posDefaultRoute) { $this->noDefaultRoute = rtrim(substr($this->route, 0, $posDefaultRoute), '/'); } else { $this->noDefaultRoute = false; } $items = $this->normalizeItems($this->items, $hasActiveChild); if (!empty($items)) { $options = $this->options; $tag = ArrayHelper::remove($options, 'tag', 'ul'); echo Html::tag($tag, $this->renderItems($items), $options); } }
Renders the menu.
https://github.com/upiksaleh/codeup-yihai/blob/98f3db37963157f8fa18c1637acc8d3877f6c982/src/theming/SideBar.php#L50-L76
upiksaleh/codeup-yihai
src/theming/SideBar.php
SideBar.isItemActive
protected function isItemActive($item) { if (isset($item['url']) && is_array($item['url']) && isset($item['url'][0])) { $route = $item['url'][0]; if (isset($route[0]) && $route[0] !== '/' && Cii::$app->controller) { $route = ltrim(Cii::$app->controller->module->getUniqueId() . '/' . $route, '/'); } $route = ltrim($route, '/'); if(Cii::$app->controller->getUniqueId() == $route || Cii::$app->controller->getUniqueId() .'/index' == $route) return true; if ($route != $this->route && $route !== $this->noDefaultRoute && $route !== $this->noDefaultAction) { return false; } unset($item['url']['#']); if (count($item['url']) > 1) { foreach (array_splice($item['url'], 1) as $name => $value) { if ($value !== null && (!isset($this->params[$name]) || $this->params[$name] != $value)) { return false; } } } return true; } return false; }
php
protected function isItemActive($item) { if (isset($item['url']) && is_array($item['url']) && isset($item['url'][0])) { $route = $item['url'][0]; if (isset($route[0]) && $route[0] !== '/' && Cii::$app->controller) { $route = ltrim(Cii::$app->controller->module->getUniqueId() . '/' . $route, '/'); } $route = ltrim($route, '/'); if(Cii::$app->controller->getUniqueId() == $route || Cii::$app->controller->getUniqueId() .'/index' == $route) return true; if ($route != $this->route && $route !== $this->noDefaultRoute && $route !== $this->noDefaultAction) { return false; } unset($item['url']['#']); if (count($item['url']) > 1) { foreach (array_splice($item['url'], 1) as $name => $value) { if ($value !== null && (!isset($this->params[$name]) || $this->params[$name] != $value)) { return false; } } } return true; } return false; }
Checks whether a menu item is active. This is done by checking if [[route]] and [[params]] match that specified in the `url` option of the menu item. When the `url` option of a menu item is specified in terms of an array, its first element is treated as the route for the item and the rest of the elements are the associated parameters. Only when its route and parameters match [[route]] and [[params]], respectively, will a menu item be considered active. @param array $item the menu item to be checked @return boolean whether the menu item is active
https://github.com/upiksaleh/codeup-yihai/blob/98f3db37963157f8fa18c1637acc8d3877f6c982/src/theming/SideBar.php#L196-L221
payapi/payapi-sdk-php
src/payapi/core/core.request.php
request.post
public function post($key) { if ($this->has('post') && isset($this->data['post'][$key]) === true) { return $this->data['post'][$key]; } return $key; }
php
public function post($key) { if ($this->has('post') && isset($this->data['post'][$key]) === true) { return $this->data['post'][$key]; } return $key; }
/* public function get($key) { if ($key === false) { return $this->data; } else if ($this->has($key) === true) { return $this->data[$key]; } return $key; }
https://github.com/payapi/payapi-sdk-php/blob/6a675749c88742b261178d7977f2436d540132b4/src/payapi/core/core.request.php#L102-L108
stonedz/pff2
src/modules/auth/Auth.php
Auth.checkAuth
public function checkAuth() { if (isset($_SESSION[$this->_sessionVarName]) && $_SESSION[$this->_sessionVarName] == 1 ) { return true; } else { return false; } }
php
public function checkAuth() { if (isset($_SESSION[$this->_sessionVarName]) && $_SESSION[$this->_sessionVarName] == 1 ) { return true; } else { return false; } }
Checks if a client is logged-in @return bool
https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/modules/auth/Auth.php#L119-L127
stonedz/pff2
src/modules/auth/Auth.php
Auth.login
public function login($username, $password, $entityManager) { $tmp = $entityManager ->getRepository('pff\models\\' . $this->_modelName) ->findOneBy(array($this->_usernameAttribute => $username)); if ($tmp) { if ($this->_encryptionStrategy->checkPass($password, call_user_func(array($tmp, $this->_methodGetPassword)), ($this->_useSalt)?(call_user_func(array($tmp,$this->_methodGetSalt))):'')) { $this->_logUser(); return true; } else { return false; } } else { return false; } }
php
public function login($username, $password, $entityManager) { $tmp = $entityManager ->getRepository('pff\models\\' . $this->_modelName) ->findOneBy(array($this->_usernameAttribute => $username)); if ($tmp) { if ($this->_encryptionStrategy->checkPass($password, call_user_func(array($tmp, $this->_methodGetPassword)), ($this->_useSalt)?(call_user_func(array($tmp,$this->_methodGetSalt))):'')) { $this->_logUser(); return true; } else { return false; } } else { return false; } }
Login @param string $username @param string $password @param \Doctrine\ORM\EntityManager $entityManager @return bool
https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/modules/auth/Auth.php#L137-L151
oliwierptak/Everon1
src/Everon/Helper/Asserts/IsNull.php
IsNull.assertIsNull
public function assertIsNull($value, $message='Unexpected null value: %s', $exception='Asserts') { if (is_null($value)) { $value = 'NULL'; $this->throwException($exception, $message, $value); } }
php
public function assertIsNull($value, $message='Unexpected null value: %s', $exception='Asserts') { if (is_null($value)) { $value = 'NULL'; $this->throwException($exception, $message, $value); } }
Verifies that the specified condition is not null. The assertion fails if the condition is null. @param mixed $value @param string $message @param string $exception @throws \Everon\Exception\Asserts
https://github.com/oliwierptak/Everon1/blob/ac93793d1fa517a8394db5f00062f1925dc218a3/src/Everon/Helper/Asserts/IsNull.php#L23-L29
schpill/thin
src/Html/Row.php
Row.row
public function row(array $attributes = array()) { $row = new self(); if (count($attributes)) { $row->setAttributes($attributes); } return $row; }
php
public function row(array $attributes = array()) { $row = new self(); if (count($attributes)) { $row->setAttributes($attributes); } return $row; }
Generates a new table row @param array $attributes @return Row
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Row.php#L38-L47
schpill/thin
src/Html/Row.php
Row.add
public function add($value, array $attributes = null) { $cell = $value; if (is_string($value)) { $cell = new Cell($value, $attributes); } $this->_cells[] = $cell; return $this; }
php
public function add($value, array $attributes = null) { $cell = $value; if (is_string($value)) { $cell = new Cell($value, $attributes); } $this->_cells[] = $cell; return $this; }
Adds a cell to the row @param string|Cell $cell @param array $attributes
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Row.php#L97-L107
schpill/thin
src/Html/Row.php
Row.isHeader
public function isHeader($isHeader = true) { foreach ($this->_cells as $cell) { $cell->isHeader($isHeader); } return $this; }
php
public function isHeader($isHeader = true) { foreach ($this->_cells as $cell) { $cell->isHeader($isHeader); } return $this; }
Set whether this row should be a table header or not @param bool $isHeader @return Row
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Row.php#L116-L123
schpill/thin
src/Html/Row.php
Row.setState
public function setState($state = null) { if (null === $state) { $this->_state = $state; return $this; } if (in_array($state, array(static::STATE_SUCCESS, static::STATE_ERROR, static::STATE_INFO))) { $this->_state = $state; } return $this; }
php
public function setState($state = null) { if (null === $state) { $this->_state = $state; return $this; } if (in_array($state, array(static::STATE_SUCCESS, static::STATE_ERROR, static::STATE_INFO))) { $this->_state = $state; } return $this; }
Sets the row state @param string $state @return Row
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Row.php#L132-L144
ekyna/AdminBundle
Dashboard/Widget/Registry.php
Registry.hasType
public function hasType($nameOrType) { $name = $nameOrType instanceof WidgetTypeInterface ? $nameOrType->getName() : $nameOrType; return array_key_exists($name, $this->types); }
php
public function hasType($nameOrType) { $name = $nameOrType instanceof WidgetTypeInterface ? $nameOrType->getName() : $nameOrType; return array_key_exists($name, $this->types); }
Returns whether the widget type is registered or not. @param $nameOrType @return bool
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Dashboard/Widget/Registry.php#L36-L41
ekyna/AdminBundle
Dashboard/Widget/Registry.php
Registry.addType
public function addType(WidgetTypeInterface $widget) { if (!$this->hasType($widget)) { $this->types[$widget->getName()] = $widget; } else { throw new \InvalidArgumentException(sprintf('Widget type "%s" is already registered.', $widget->getName())); } }
php
public function addType(WidgetTypeInterface $widget) { if (!$this->hasType($widget)) { $this->types[$widget->getName()] = $widget; } else { throw new \InvalidArgumentException(sprintf('Widget type "%s" is already registered.', $widget->getName())); } }
Adds the widget type. @param WidgetTypeInterface $widget @throws \InvalidArgumentException
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Dashboard/Widget/Registry.php#L49-L56
ekyna/AdminBundle
Dashboard/Widget/Registry.php
Registry.getType
public function getType($name) { if ($this->hasType($name)) { return $this->types[$name]; } else { throw new \InvalidArgumentException(sprintf('Widget type "%s" not found.', $name)); } }
php
public function getType($name) { if ($this->hasType($name)) { return $this->types[$name]; } else { throw new \InvalidArgumentException(sprintf('Widget type "%s" not found.', $name)); } }
Returns the widget type by name. @param string $name @return WidgetTypeInterface @throws \InvalidArgumentException
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Dashboard/Widget/Registry.php#L65-L72
mobtexting/php-http-client
src/Client.php
Client.parseResponse
protected function parseResponse($channel, $content) { $headerSize = curl_getinfo($channel, CURLINFO_HEADER_SIZE); $statusCode = curl_getinfo($channel, CURLINFO_HTTP_CODE); $responseBody = substr($content, $headerSize); $responseHeaders = substr($content, 0, $headerSize); $responseHeaders = explode("\n", $responseHeaders); $responseHeaders = array_map('trim', $responseHeaders); return new Response($statusCode, $responseBody, $responseHeaders); }
php
protected function parseResponse($channel, $content) { $headerSize = curl_getinfo($channel, CURLINFO_HEADER_SIZE); $statusCode = curl_getinfo($channel, CURLINFO_HTTP_CODE); $responseBody = substr($content, $headerSize); $responseHeaders = substr($content, 0, $headerSize); $responseHeaders = explode("\n", $responseHeaders); $responseHeaders = array_map('trim', $responseHeaders); return new Response($statusCode, $responseBody, $responseHeaders); }
Prepare response object @param resource $channel the curl resource @param string $content @return Response object
https://github.com/mobtexting/php-http-client/blob/3925e841cfa0f8fcc35f57a6c0c0935076c7e6e3/src/Client.php#L252-L262
mobtexting/php-http-client
src/Client.php
Client._
public function _($name = null) { if (isset($name)) { $this->path[] = $name; } $client = new static($this->host, $this->headers); $client->setPath($this->path); $client->setCurlOptions($this->curlOptions); $client->setRetryOnLimit($this->retryOnLimit); $this->path = []; return $client; }
php
public function _($name = null) { if (isset($name)) { $this->path[] = $name; } $client = new static($this->host, $this->headers); $client->setPath($this->path); $client->setCurlOptions($this->curlOptions); $client->setRetryOnLimit($this->retryOnLimit); $this->path = []; return $client; }
Add variable values to the url. (e.g. /your/api/{variable_value}/call) Another example: if you have a PHP reserved word, such as and, in your url, you must use this method. @param string $name name of the url segment @return Client object
https://github.com/mobtexting/php-http-client/blob/3925e841cfa0f8fcc35f57a6c0c0935076c7e6e3/src/Client.php#L363-L375
Dhii/output-renderer-abstract
src/ContextAwareTrait.php
ContextAwareTrait._setContext
protected function _setContext($context) { $this->context = ($context !== null) ? $this->_normalizeContainer($context) : null; }
php
protected function _setContext($context) { $this->context = ($context !== null) ? $this->_normalizeContainer($context) : null; }
Sets the context for this instance. @since 0.1 @param array|ArrayAccess|stdClass|ContainerInterface|null $context The context instance, or null.
https://github.com/Dhii/output-renderer-abstract/blob/0f6e5eed940025332dd1986d6c771e10f7197b1a/src/ContextAwareTrait.php#L45-L50
buse974/Dal
src/Dal/Model/AbstractModel.php
AbstractModel.exchangeArray
public function exchangeArray(array &$data) { $hydrator = new ClassMethods(); $formatted = []; if (null !== $this->prefix) { $pr = $this->allParent(); $eq = ($pr === $this->prefix); foreach ($data as $key => $value) { $fkey = null; if (0 === ($tmp = strpos($key, $this->prefix . $this->delimiter))) { $fkey = substr($key, strlen($this->prefix . $this->delimiter)); } elseif ($eq === false && $tmp !== false && 0 === strpos($key, $pr . $this->delimiter)) { $fkey = substr($key, strlen($pr . $this->delimiter)); } elseif (0 === ($tmp = strpos($key, $this->prefix . $this->delimiter_opt))) { $fkey = substr($key, strlen($this->prefix . $this->delimiter_opt)); if($value === null) { $this->keep = false; } } elseif ($eq === false && $tmp !== false && 0 === strpos($key, $pr . $this->delimiter_opt)) { $fkey = substr($key, strlen($pr . $this->delimiter_opt)); if($value === null) { $this->keep = false; } } if (null !== $fkey && $hydrator->canBeHydrated($fkey, $this)) { $formatted[$fkey] = ($value === null) ? new IsNull() : $value; unset($data[$key]); } } } if (null === $this->prefix || empty($formatted)) { foreach ($data as $key => $value) { if ($hydrator->canBeHydrated($key, $this)) { $formatted[$key] = ($value === null) ? new IsNull() : $value; unset($data[$key]); } } } if(!empty($formatted) && $this->keep === true) { $hydrator->hydrate($formatted, $this); } return $this; }
php
public function exchangeArray(array &$data) { $hydrator = new ClassMethods(); $formatted = []; if (null !== $this->prefix) { $pr = $this->allParent(); $eq = ($pr === $this->prefix); foreach ($data as $key => $value) { $fkey = null; if (0 === ($tmp = strpos($key, $this->prefix . $this->delimiter))) { $fkey = substr($key, strlen($this->prefix . $this->delimiter)); } elseif ($eq === false && $tmp !== false && 0 === strpos($key, $pr . $this->delimiter)) { $fkey = substr($key, strlen($pr . $this->delimiter)); } elseif (0 === ($tmp = strpos($key, $this->prefix . $this->delimiter_opt))) { $fkey = substr($key, strlen($this->prefix . $this->delimiter_opt)); if($value === null) { $this->keep = false; } } elseif ($eq === false && $tmp !== false && 0 === strpos($key, $pr . $this->delimiter_opt)) { $fkey = substr($key, strlen($pr . $this->delimiter_opt)); if($value === null) { $this->keep = false; } } if (null !== $fkey && $hydrator->canBeHydrated($fkey, $this)) { $formatted[$fkey] = ($value === null) ? new IsNull() : $value; unset($data[$key]); } } } if (null === $this->prefix || empty($formatted)) { foreach ($data as $key => $value) { if ($hydrator->canBeHydrated($key, $this)) { $formatted[$key] = ($value === null) ? new IsNull() : $value; unset($data[$key]); } } } if(!empty($formatted) && $this->keep === true) { $hydrator->hydrate($formatted, $this); } return $this; }
Populate from an array. @param array $data @return AbstractModel
https://github.com/buse974/Dal/blob/faeac9e260c5e675bc7ed1fcea77c7ba251bf8ab/src/Dal/Model/AbstractModel.php#L58-L101
buse974/Dal
src/Dal/Model/AbstractModel.php
AbstractModel.toArray
public function toArray() { $hydrator = new ClassMethods(); $vars = $hydrator->extract($this); foreach ($vars as $key => &$value) { if ($value === null) { unset($vars[$key]); } elseif (is_object($value) && ! $value instanceof \ArrayObject) { if (method_exists($value, 'toArray')) { $value = $value->toArray(); if (count($value) == 0) { unset($vars[$key]); } } elseif ($value instanceof IsNull) { $vars[$key] = null; } elseif ($value instanceof \stdClass) { $vars[$key] = new \stdClass(); } else { unset($vars[$key]); } } elseif (is_bool($value)) { $vars[$key] = (int) $value; } } return $vars; }
php
public function toArray() { $hydrator = new ClassMethods(); $vars = $hydrator->extract($this); foreach ($vars as $key => &$value) { if ($value === null) { unset($vars[$key]); } elseif (is_object($value) && ! $value instanceof \ArrayObject) { if (method_exists($value, 'toArray')) { $value = $value->toArray(); if (count($value) == 0) { unset($vars[$key]); } } elseif ($value instanceof IsNull) { $vars[$key] = null; } elseif ($value instanceof \stdClass) { $vars[$key] = new \stdClass(); } else { unset($vars[$key]); } } elseif (is_bool($value)) { $vars[$key] = (int) $value; } } return $vars; }
Convert the model to an array. @return array
https://github.com/buse974/Dal/blob/faeac9e260c5e675bc7ed1fcea77c7ba251bf8ab/src/Dal/Model/AbstractModel.php#L108-L135
buse974/Dal
src/Dal/Model/AbstractModel.php
AbstractModel.isRepeatRelational
protected function isRepeatRelational() { $is_repeat = false; if (array_count_values($this->getParentArray())[$this->prefix] > 1) { $is_repeat = true; } return $is_repeat; }
php
protected function isRepeatRelational() { $is_repeat = false; if (array_count_values($this->getParentArray())[$this->prefix] > 1) { $is_repeat = true; } return $is_repeat; }
Return true if relation is boucle infinie. @return bool
https://github.com/buse974/Dal/blob/faeac9e260c5e675bc7ed1fcea77c7ba251bf8ab/src/Dal/Model/AbstractModel.php#L209-L218
buse974/Dal
src/Dal/Model/AbstractModel.php
AbstractModel.requireModel
public function requireModel($model, &$data, $prefix = null) { $class = null; $name = (null !== $prefix) ? $prefix : substr($model, strlen(explode('_', $model)[0]) + 7); foreach ($this->array_prefix as $k => $ap) { if (strrpos($ap, $name) === (strlen($ap) - strlen($name))) { unset($this->array_prefix[$k]); $class = clone $this->container->get($model); $class->setPrefix($prefix); $class->setArrayPrefix($this->array_prefix); $class->setParentModel($this); $class->exchangeArray($data); if (! $class->Keep()) { return new IsNull(); } break; } } return $class; }
php
public function requireModel($model, &$data, $prefix = null) { $class = null; $name = (null !== $prefix) ? $prefix : substr($model, strlen(explode('_', $model)[0]) + 7); foreach ($this->array_prefix as $k => $ap) { if (strrpos($ap, $name) === (strlen($ap) - strlen($name))) { unset($this->array_prefix[$k]); $class = clone $this->container->get($model); $class->setPrefix($prefix); $class->setArrayPrefix($this->array_prefix); $class->setParentModel($this); $class->exchangeArray($data); if (! $class->Keep()) { return new IsNull(); } break; } } return $class; }
return Model if needed. @param string $model @param array $data @param string $prefix @return AbstractModel|null
https://github.com/buse974/Dal/blob/faeac9e260c5e675bc7ed1fcea77c7ba251bf8ab/src/Dal/Model/AbstractModel.php#L270-L291
chilimatic/chilimatic-framework
lib/parser/annotation/AnnotationOdmParser.php
AnnotationOdmParser.parse
public function parse($content) { $map = []; if (preg_match(self::CONFIGURATION_PATTERN, $content, $matches)) { if (preg_match(self::DATABASE_PATTERN, $matches[1], $database)) { $map[self::DATABASE_INDEX] = $database[1]; } if (preg_match(self::COLLECTION_PATTERN, $matches[1], $collection)) { $map[self::COLLECTION_INDEX] = $collection[1]; } } return $map; }
php
public function parse($content) { $map = []; if (preg_match(self::CONFIGURATION_PATTERN, $content, $matches)) { if (preg_match(self::DATABASE_PATTERN, $matches[1], $database)) { $map[self::DATABASE_INDEX] = $database[1]; } if (preg_match(self::COLLECTION_PATTERN, $matches[1], $collection)) { $map[self::COLLECTION_INDEX] = $collection[1]; } } return $map; }
@param string $content @return array
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/parser/annotation/AnnotationOdmParser.php#L46-L60
phpcq/autoload-validation
src/AutoloadValidator/Psr0Validator.php
Psr0Validator.doValidate
protected function doValidate() { foreach ($this->information as $prefix => $paths) { foreach ((array) $paths as $path) { $this->doValidatePath($prefix, $path); } } }
php
protected function doValidate() { foreach ($this->information as $prefix => $paths) { foreach ((array) $paths as $path) { $this->doValidatePath($prefix, $path); } } }
Check that the auto loading information is correct. {@inheritDoc}
https://github.com/phpcq/autoload-validation/blob/c24d331f16034c2096ce0e55492993befbaa687a/src/AutoloadValidator/Psr0Validator.php#L57-L64
phpcq/autoload-validation
src/AutoloadValidator/Psr0Validator.php
Psr0Validator.doValidatePath
private function doValidatePath($prefix, $path) { $subPath = $this->prependPathWithBaseDir($path); if (is_numeric($prefix)) { $this->report->error( new NameSpaceInvalidViolation($this->getName(), $prefix, $path) ); return; } $classMap = $this->classMapFromPath($subPath); // All psr-0 namespace prefixes should end with \ unless they are an exact class name or pear style. if ($prefix && (false !== strpos($prefix, '\\')) && !in_array(substr($prefix, -1), array('\\', '_')) && !isset($classMap[$prefix]) ) { $this->report->warn( new NamespaceShouldEndWithBackslashViolation($this->getName(), $prefix, $path) ); } if (empty($classMap)) { $this->report->error( new NoClassesFoundInPathViolation($this->getName(), $prefix, $subPath) ); return; } $this->validateClassMap($classMap, $subPath, $prefix, $path); }
php
private function doValidatePath($prefix, $path) { $subPath = $this->prependPathWithBaseDir($path); if (is_numeric($prefix)) { $this->report->error( new NameSpaceInvalidViolation($this->getName(), $prefix, $path) ); return; } $classMap = $this->classMapFromPath($subPath); // All psr-0 namespace prefixes should end with \ unless they are an exact class name or pear style. if ($prefix && (false !== strpos($prefix, '\\')) && !in_array(substr($prefix, -1), array('\\', '_')) && !isset($classMap[$prefix]) ) { $this->report->warn( new NamespaceShouldEndWithBackslashViolation($this->getName(), $prefix, $path) ); } if (empty($classMap)) { $this->report->error( new NoClassesFoundInPathViolation($this->getName(), $prefix, $subPath) ); return; } $this->validateClassMap($classMap, $subPath, $prefix, $path); }
Validate a path. @param string $prefix The prefix to use for this path. @param string $path The path. @return void
https://github.com/phpcq/autoload-validation/blob/c24d331f16034c2096ce0e55492993befbaa687a/src/AutoloadValidator/Psr0Validator.php#L75-L108
phpcq/autoload-validation
src/AutoloadValidator/Psr0Validator.php
Psr0Validator.validateClassMap
private function validateClassMap($classMap, $subPath, $prefix, $path) { $cleaned = $prefix; if ('\\' === substr($prefix, -1)) { $cleaned = substr($prefix, 0, -1); } $prefixLength = strlen($cleaned); foreach ($classMap as $class => $file) { if ('\\' === $class[0]) { $class = substr($class, 1); } $classNs = $this->getNameSpaceFromClassName($class); $classNm = $this->getClassFromClassName($class); // PEAR-like class name or namespace does not match. if ($this->checkPearOrNoMatch($classNs, $prefixLength, $cleaned)) { // It is allowed to specify a class name as prefix. if ($class === $prefix) { continue; } $this->classMap->remove($class); $this->report->error( new NamespacePrefixMismatchViolation( $this->getName(), $prefix, $path, $class, $this->getNameSpaceFromClassName($class) ) ); continue; } $classNm = ltrim('\\' . $classNm, '\\'); $fileNameShould = rtrim($subPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; if ($classNs) { $fileNameShould .= str_replace('\\', DIRECTORY_SEPARATOR, $classNs) . DIRECTORY_SEPARATOR; } $fileNameShould .= str_replace('_', DIRECTORY_SEPARATOR, $classNm); if ($fileNameShould !== $this->cutExtensionFromFileName($file)) { $this->classMap->remove($class); $this->report->error( new ClassFoundInWrongFileViolation( $this->getName(), $prefix, $path, $class, $file, $fileNameShould . $this->getExtensionFromFileName($file) ) ); } } }
php
private function validateClassMap($classMap, $subPath, $prefix, $path) { $cleaned = $prefix; if ('\\' === substr($prefix, -1)) { $cleaned = substr($prefix, 0, -1); } $prefixLength = strlen($cleaned); foreach ($classMap as $class => $file) { if ('\\' === $class[0]) { $class = substr($class, 1); } $classNs = $this->getNameSpaceFromClassName($class); $classNm = $this->getClassFromClassName($class); // PEAR-like class name or namespace does not match. if ($this->checkPearOrNoMatch($classNs, $prefixLength, $cleaned)) { // It is allowed to specify a class name as prefix. if ($class === $prefix) { continue; } $this->classMap->remove($class); $this->report->error( new NamespacePrefixMismatchViolation( $this->getName(), $prefix, $path, $class, $this->getNameSpaceFromClassName($class) ) ); continue; } $classNm = ltrim('\\' . $classNm, '\\'); $fileNameShould = rtrim($subPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; if ($classNs) { $fileNameShould .= str_replace('\\', DIRECTORY_SEPARATOR, $classNs) . DIRECTORY_SEPARATOR; } $fileNameShould .= str_replace('_', DIRECTORY_SEPARATOR, $classNm); if ($fileNameShould !== $this->cutExtensionFromFileName($file)) { $this->classMap->remove($class); $this->report->error( new ClassFoundInWrongFileViolation( $this->getName(), $prefix, $path, $class, $file, $fileNameShould . $this->getExtensionFromFileName($file) ) ); } } }
Validate the passed classmap. @param array $classMap The list of classes. @param string $subPath The path where the classes are contained within. @param string $prefix The psr-0 top level namespace. @param string $path The psr-0 top level path. @return void
https://github.com/phpcq/autoload-validation/blob/c24d331f16034c2096ce0e55492993befbaa687a/src/AutoloadValidator/Psr0Validator.php#L123-L180
phpcq/autoload-validation
src/AutoloadValidator/Psr0Validator.php
Psr0Validator.checkPearOrNoMatch
private function checkPearOrNoMatch($classNameSpace, $prefixLength, $prefix) { // No NS, separator in class namespace. if (!$classNameSpace) { return false; } if (substr($classNameSpace, 0, $prefixLength) === $prefix) { return false; } return true; }
php
private function checkPearOrNoMatch($classNameSpace, $prefixLength, $prefix) { // No NS, separator in class namespace. if (!$classNameSpace) { return false; } if (substr($classNameSpace, 0, $prefixLength) === $prefix) { return false; } return true; }
Check if the class is PEAR style or does not match at all. Return true if there is some problem, false otherwise. @param string $classNameSpace The namespace of the class. @param string $prefixLength The length of the namespace that must match. @param string $prefix The required namespace prefix. @return bool
https://github.com/phpcq/autoload-validation/blob/c24d331f16034c2096ce0e55492993befbaa687a/src/AutoloadValidator/Psr0Validator.php#L195-L207
AndyDune/Pipeline
src/Pipeline.php
Pipeline.through
public function through($pipes): self { $this->pipes = is_array($pipes) ? $pipes : func_get_args(); return $this; }
php
public function through($pipes): self { $this->pipes = is_array($pipes) ? $pipes : func_get_args(); return $this; }
Set the array of pipes. @param array|mixed $pipes @return $this
https://github.com/AndyDune/Pipeline/blob/66bcc8ba7a0d74fecdf2f993995c1140c29fd91f/src/Pipeline.php#L109-L114
AndyDune/Pipeline
src/Pipeline.php
Pipeline.pipe
public function pipe($pipe, $methodName = '', ...$params): self { if ($pipe instanceof Closure) { $this->pipes[] = $pipe; return $this; } $pipe = [ $pipe, $methodName, $params, false ]; $this->pipes[] = $pipe; return $this; }
php
public function pipe($pipe, $methodName = '', ...$params): self { if ($pipe instanceof Closure) { $this->pipes[] = $pipe; return $this; } $pipe = [ $pipe, $methodName, $params, false ]; $this->pipes[] = $pipe; return $this; }
Add stage for workflow. @param $pipe class name or service name for stage. @param string $methodName method name for this object @param string $params additional params @return $this
https://github.com/AndyDune/Pipeline/blob/66bcc8ba7a0d74fecdf2f993995c1140c29fd91f/src/Pipeline.php#L137-L152
AndyDune/Pipeline
src/Pipeline.php
Pipeline.pipeForContainer
public function pipeForContainer($pipe, $methodName = '', ...$params): self { if ($pipe instanceof Closure) { $this->pipes[] = $pipe; return $this; } $pipe = [ $pipe, $methodName, $params, true ]; $this->pipes[] = $pipe; return $this; }
php
public function pipeForContainer($pipe, $methodName = '', ...$params): self { if ($pipe instanceof Closure) { $this->pipes[] = $pipe; return $this; } $pipe = [ $pipe, $methodName, $params, true ]; $this->pipes[] = $pipe; return $this; }
Add stage without middleware interface. @param $pipe description for stage @param string $methodName @param array ...$params @return $this
https://github.com/AndyDune/Pipeline/blob/66bcc8ba7a0d74fecdf2f993995c1140c29fd91f/src/Pipeline.php#L163-L178
AndyDune/Pipeline
src/Pipeline.php
Pipeline.execute
public function execute() { $pipeline = array_reduce( array_reverse($this->pipes), $this->carry(), function ($passable) { return $passable; } ); return $pipeline($this->passable); }
php
public function execute() { $pipeline = array_reduce( array_reverse($this->pipes), $this->carry(), function ($passable) { return $passable; } ); return $pipeline($this->passable); }
Run the pipeline without a final destination callback. @return mixed
https://github.com/AndyDune/Pipeline/blob/66bcc8ba7a0d74fecdf2f993995c1140c29fd91f/src/Pipeline.php#L201-L210
AndyDune/Pipeline
src/Pipeline.php
Pipeline.carry
protected function carry() { return function ($stack, $pipe) { return function ($passable) use ($stack, $pipe) { $method = $this->method; if (is_callable($pipe)) { // If the pipe is an instance of a Closure, we will just call it directly but // otherwise we'll resolve the pipes out of the container and call it with // the appropriate method and arguments, returning the results back out. return $pipe($passable, $stack); } elseif (is_object($pipe)) { // If the pipe is already an object we'll just make a callable and pass it to // the pipe as-is. There is no need to do any extra parsing and formatting // since the object we're given was already a fully instantiated object. $parameters = [$passable, $stack]; } else { list($name, $methodFromString, $parameters, $needContainer) = $this->parsePipeData($pipe); if ($methodFromString) { $method = $methodFromString; } if (!$parameters) { $parameters = []; } // If the pipe is a string we will parse the string and resolve the class out // of the dependency injection container. We can then build a callable and // execute the pipe function giving in the parameters that are required. if (is_string($name)) { //$pipe = $this->getContainer()->get($name); $pipe = $this->getPipeStageFromContainer($name); } else { $pipe = $name; } $parameters = array_merge([$passable, $stack], $parameters); // if ($needContainer) { $this->initialize($pipe); $pipeReturn = function ($data, $next) use ($pipe, $method) { if ($method) { $data = $pipe->{$method}($data); } else { $data = $pipe($data); } return $next($data); }; return $pipeReturn(...$parameters); } } $this->initialize($pipe); if ($method) { if (method_exists($pipe, $method)) { return $pipe->{$method}(...$parameters); } throw new Exception('Method ' . $method . ' does not exist in stage with class ' . get_class($pipe)); } else if ($pipe instanceof StageInterface) { return $pipe->execute(...$parameters); } else { return $pipe(...$parameters); } }; }; }
php
protected function carry() { return function ($stack, $pipe) { return function ($passable) use ($stack, $pipe) { $method = $this->method; if (is_callable($pipe)) { // If the pipe is an instance of a Closure, we will just call it directly but // otherwise we'll resolve the pipes out of the container and call it with // the appropriate method and arguments, returning the results back out. return $pipe($passable, $stack); } elseif (is_object($pipe)) { // If the pipe is already an object we'll just make a callable and pass it to // the pipe as-is. There is no need to do any extra parsing and formatting // since the object we're given was already a fully instantiated object. $parameters = [$passable, $stack]; } else { list($name, $methodFromString, $parameters, $needContainer) = $this->parsePipeData($pipe); if ($methodFromString) { $method = $methodFromString; } if (!$parameters) { $parameters = []; } // If the pipe is a string we will parse the string and resolve the class out // of the dependency injection container. We can then build a callable and // execute the pipe function giving in the parameters that are required. if (is_string($name)) { //$pipe = $this->getContainer()->get($name); $pipe = $this->getPipeStageFromContainer($name); } else { $pipe = $name; } $parameters = array_merge([$passable, $stack], $parameters); // if ($needContainer) { $this->initialize($pipe); $pipeReturn = function ($data, $next) use ($pipe, $method) { if ($method) { $data = $pipe->{$method}($data); } else { $data = $pipe($data); } return $next($data); }; return $pipeReturn(...$parameters); } } $this->initialize($pipe); if ($method) { if (method_exists($pipe, $method)) { return $pipe->{$method}(...$parameters); } throw new Exception('Method ' . $method . ' does not exist in stage with class ' . get_class($pipe)); } else if ($pipe instanceof StageInterface) { return $pipe->execute(...$parameters); } else { return $pipe(...$parameters); } }; }; }
Get a Closure that represents a slice of the application onion. @return \Closure
https://github.com/AndyDune/Pipeline/blob/66bcc8ba7a0d74fecdf2f993995c1140c29fd91f/src/Pipeline.php#L230-L295
AndyDune/Pipeline
src/Pipeline.php
Pipeline.parsePipeData
protected function parsePipeData($pipe) { if (is_array($pipe)) { if (!$pipe[0]) { throw new Exception('I need to know name of service (class)'); } $name = $pipe[0]; $method = $pipe[1]; $parameters = $pipe[2]; $needContainer = $pipe[3]; } else { list($name, $method, $parameters) = array_pad(explode(':', $pipe, 3), 3, null); $needContainer = null; } if (is_string($parameters)) { $parameters = explode(',', $parameters); } return [$name, $method, $parameters, $needContainer]; }
php
protected function parsePipeData($pipe) { if (is_array($pipe)) { if (!$pipe[0]) { throw new Exception('I need to know name of service (class)'); } $name = $pipe[0]; $method = $pipe[1]; $parameters = $pipe[2]; $needContainer = $pipe[3]; } else { list($name, $method, $parameters) = array_pad(explode(':', $pipe, 3), 3, null); $needContainer = null; } if (is_string($parameters)) { $parameters = explode(',', $parameters); } return [$name, $method, $parameters, $needContainer]; }
Parse full pipe string to get name and parameters. @param string $pipe @return array
https://github.com/AndyDune/Pipeline/blob/66bcc8ba7a0d74fecdf2f993995c1140c29fd91f/src/Pipeline.php#L303-L323
armazon/armazon
src/Armazon/Mvc/Vista.php
Vista.filtrarValor
public function filtrarValor($filtro, $texto) { if (isset($this->filtros[$filtro])) { $texto = $this->filtros[$filtro]($texto); } return $texto; }
php
public function filtrarValor($filtro, $texto) { if (isset($this->filtros[$filtro])) { $texto = $this->filtros[$filtro]($texto); } return $texto; }
Aplica el filtro solicitado al valor. @param string $filtro @param string $texto @return string
https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Mvc/Vista.php#L125-L132
armazon/armazon
src/Armazon/Mvc/Vista.php
Vista.renderizar
public function renderizar($vista) { $this->contenido = $this->cargarContenido($vista); if (isset($this->plantilla)) { $this->contenido = $this->cargarContenido('plantillas/' . $this->plantilla); } // Procesamos los textos dinámicos en caso de ser detectados if (strpos($this->contenido, '{{') !== false) { preg_match_all('#\{\{([^\{\}]+)\}\}#u', $this->contenido, $ocurrencias); foreach ($ocurrencias[1] as $ocurrencia) { // Extraemos los filtros encontrados en la ocurrencia $filtros = explode('|', $ocurrencia); // Extraemos el valor de los filtros $texto = array_shift($filtros); // Sustituimos si existe una variable en la vista con el nombre del texto if (isset($this->{$texto})) { $texto = $this->{$texto}; } // Aplicamos filtros al valor en caso necesario if (count($filtros)) { foreach ($filtros as $filtro) { $texto = $this->filtrarValor($filtro, $texto); } } // Escapamos el texto por cuestiones de seguridad $texto = htmlspecialchars($texto, ENT_COMPAT | ENT_DISALLOWED | ENT_HTML5); $this->contenido = str_replace('{{' . $ocurrencia . '}}', $texto, $this->contenido); } } $this->renderizado = true; return $this->contenido; }
php
public function renderizar($vista) { $this->contenido = $this->cargarContenido($vista); if (isset($this->plantilla)) { $this->contenido = $this->cargarContenido('plantillas/' . $this->plantilla); } // Procesamos los textos dinámicos en caso de ser detectados if (strpos($this->contenido, '{{') !== false) { preg_match_all('#\{\{([^\{\}]+)\}\}#u', $this->contenido, $ocurrencias); foreach ($ocurrencias[1] as $ocurrencia) { // Extraemos los filtros encontrados en la ocurrencia $filtros = explode('|', $ocurrencia); // Extraemos el valor de los filtros $texto = array_shift($filtros); // Sustituimos si existe una variable en la vista con el nombre del texto if (isset($this->{$texto})) { $texto = $this->{$texto}; } // Aplicamos filtros al valor en caso necesario if (count($filtros)) { foreach ($filtros as $filtro) { $texto = $this->filtrarValor($filtro, $texto); } } // Escapamos el texto por cuestiones de seguridad $texto = htmlspecialchars($texto, ENT_COMPAT | ENT_DISALLOWED | ENT_HTML5); $this->contenido = str_replace('{{' . $ocurrencia . '}}', $texto, $this->contenido); } } $this->renderizado = true; return $this->contenido; }
Convierte una vista con códigos php y etiquetas propias a puro HTML. @param string $vista @return string
https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Mvc/Vista.php#L141-L183
zhengb302/LumengPHP
src/LumengPHP/Kernel/ClassInvoker.php
ClassInvoker.invoke
public function invoke($className) { $classObject = new $className(); $classRefObj = new ReflectionClass($className); //加载类元数据 $classMetadata = $this->classMetadataLoader->load($className); //注入属性 $propertyMetadata = $classMetadata['propertyMetadata']; $this->propertyInjector->inject($classObject, $classRefObj, $propertyMetadata); //如果有init方法,先执行init方法 if ($classRefObj->hasMethod('init')) { $classObject->init(); } //执行类入口方法并返回 $method = self::ENTRY_METHOD; $return = $classObject->$method(); return $return; }
php
public function invoke($className) { $classObject = new $className(); $classRefObj = new ReflectionClass($className); //加载类元数据 $classMetadata = $this->classMetadataLoader->load($className); //注入属性 $propertyMetadata = $classMetadata['propertyMetadata']; $this->propertyInjector->inject($classObject, $classRefObj, $propertyMetadata); //如果有init方法,先执行init方法 if ($classRefObj->hasMethod('init')) { $classObject->init(); } //执行类入口方法并返回 $method = self::ENTRY_METHOD; $return = $classObject->$method(); return $return; }
调用类并返回一个结果对象 @param string $className 要被调用的类的全限定名称 @return type
https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Kernel/ClassInvoker.php#L51-L71
SURFnet/yubikey-api-client
src/Crypto/Signer.php
Signer.sign
public function sign(array $data) { ksort($data); $queryString = $this->buildQueryString($data); $data['h'] = base64_encode(hash_hmac('sha1', $queryString, $this->clientSecret, true)); return $data; }
php
public function sign(array $data) { ksort($data); $queryString = $this->buildQueryString($data); $data['h'] = base64_encode(hash_hmac('sha1', $queryString, $this->clientSecret, true)); return $data; }
Signs an array by calculating a signature and setting it on the 'h' key. @param array $data @return array
https://github.com/SURFnet/yubikey-api-client/blob/bbcb6340c89c5bcecf2f9258390cb9dfe2b87358/src/Crypto/Signer.php#L67-L75
SURFnet/yubikey-api-client
src/Crypto/Signer.php
Signer.verifySignature
public function verifySignature(array $data) { $signedData = array_intersect_key($data, array_flip(self::$validResponseParams)); ksort($signedData); $queryString = $this->buildQueryString($signedData); $signature = base64_encode(hash_hmac('sha1', $queryString, $this->clientSecret, true)); return hash_equals($signature, $data['h']); }
php
public function verifySignature(array $data) { $signedData = array_intersect_key($data, array_flip(self::$validResponseParams)); ksort($signedData); $queryString = $this->buildQueryString($signedData); $signature = base64_encode(hash_hmac('sha1', $queryString, $this->clientSecret, true)); return hash_equals($signature, $data['h']); }
Verifies that the signature in the 'h' key matches the expected signature. @param array $data @return bool
https://github.com/SURFnet/yubikey-api-client/blob/bbcb6340c89c5bcecf2f9258390cb9dfe2b87358/src/Crypto/Signer.php#L83-L92
denostr/stopforumspam
src/Client.php
Client.request
public function request() { $data = $this->prepareData(); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->apiHost . '/api'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); $this->checkResult($result); return $result; }
php
public function request() { $data = $this->prepareData(); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->apiHost . '/api'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); $this->checkResult($result); return $result; }
Run API reauest @return mixed @throws \Exception
https://github.com/denostr/stopforumspam/blob/afbab3bd33ea9b408ad7c3331e0dafa2f87ff3ca/src/Client.php#L147-L161
denostr/stopforumspam
src/Client.php
Client.prepareData
private function prepareData() { $data = []; foreach (get_object_vars($this) as $property => $value) { if (in_array($property, ['apiHost', 'debug'])) { continue; } if ($property == 'format') { $data[$value] = ''; } elseif (is_bool($value) && $value) { $data[$property] = ''; } elseif (!is_null($value) && !is_bool($value)) { if (is_array($value)) { foreach ($value as $key => $val) { $value[$key] = $val; } } else { $value = $value; } $data[$property] = $value; } } if (empty($data) && $this->debug) { throw new \Exception('Query have not data'); } $data = http_build_query($data); return $data; }
php
private function prepareData() { $data = []; foreach (get_object_vars($this) as $property => $value) { if (in_array($property, ['apiHost', 'debug'])) { continue; } if ($property == 'format') { $data[$value] = ''; } elseif (is_bool($value) && $value) { $data[$property] = ''; } elseif (!is_null($value) && !is_bool($value)) { if (is_array($value)) { foreach ($value as $key => $val) { $value[$key] = $val; } } else { $value = $value; } $data[$property] = $value; } } if (empty($data) && $this->debug) { throw new \Exception('Query have not data'); } $data = http_build_query($data); return $data; }
Preparing data before request @return string @throws \Exception
https://github.com/denostr/stopforumspam/blob/afbab3bd33ea9b408ad7c3331e0dafa2f87ff3ca/src/Client.php#L169-L201
denostr/stopforumspam
src/Client.php
Client.checkResult
private function checkResult($result) { if ($this->debug) { if (in_array($this->format, [self::FORMAT_JSON, self::FORMAT_JSONP])) { $result = json_decode($result, true); } elseif ($this->format == self::FORMAT_SERIAL) { $result = unserialize($result); } if (is_array($result)) { if (isset($result['success']) && $result['success'] == 0 && isset($result['error'])) { throw new \Exception($result['error']); } } } }
php
private function checkResult($result) { if ($this->debug) { if (in_array($this->format, [self::FORMAT_JSON, self::FORMAT_JSONP])) { $result = json_decode($result, true); } elseif ($this->format == self::FORMAT_SERIAL) { $result = unserialize($result); } if (is_array($result)) { if (isset($result['success']) && $result['success'] == 0 && isset($result['error'])) { throw new \Exception($result['error']); } } } }
Check response data @param $result @throws \Exception
https://github.com/denostr/stopforumspam/blob/afbab3bd33ea9b408ad7c3331e0dafa2f87ff3ca/src/Client.php#L209-L224
YiMAproject/yimaAdminor
src/yimaAdminor/Service/AuthServiceFactory.php
AuthServiceFactory.createService
public function createService(ServiceLocatorInterface $serviceLocator) { $serviceLocator = $serviceLocator->getServiceLocator(); $config = $serviceLocator->get('Config'); $config = (isset($config['yima_adminor']) && is_array($config['yima_adminor'])) ? $config['yima_adminor'] : []; $opts = []; if (isset($config['auth_service']) && is_array($config['auth_service']) ) $opts = $config['auth_service']; if (isset($opts['auth_adapter']) && $srvAdapter = $opts['auth_adapter']) { if (is_string($srvAdapter)) { if (!class_exists($srvAdapter)) // it's a registered service $opts['auth_adapter'] = $serviceLocator->get($srvAdapter); else $opts['auth_adapter'] = $serviceLocator->get($srvAdapter); } } $authService = new AuthService($opts); return $authService; }
php
public function createService(ServiceLocatorInterface $serviceLocator) { $serviceLocator = $serviceLocator->getServiceLocator(); $config = $serviceLocator->get('Config'); $config = (isset($config['yima_adminor']) && is_array($config['yima_adminor'])) ? $config['yima_adminor'] : []; $opts = []; if (isset($config['auth_service']) && is_array($config['auth_service']) ) $opts = $config['auth_service']; if (isset($opts['auth_adapter']) && $srvAdapter = $opts['auth_adapter']) { if (is_string($srvAdapter)) { if (!class_exists($srvAdapter)) // it's a registered service $opts['auth_adapter'] = $serviceLocator->get($srvAdapter); else $opts['auth_adapter'] = $serviceLocator->get($srvAdapter); } } $authService = new AuthService($opts); return $authService; }
Create the Authentication Service @param ServiceLocatorInterface $serviceLocator @return iAuthenticateAdapter
https://github.com/YiMAproject/yimaAdminor/blob/7a6c66e05aedaef8061c8998dfa44ac1ce9cc319/src/yimaAdminor/Service/AuthServiceFactory.php#L18-L45
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Session.php
Radial_Core_Model_Session._extractQuoteSkuData
protected function _extractQuoteSkuData(Mage_Sales_Model_Quote $quote) { $skuData = []; // use getAllVisibleItems to prevent dupes due to parent config + child used both being included foreach ($quote->getAllVisibleItems() as $item) { // before item's have been saved, getAllVisible items won't properly // filter child items...this extra check fixes it if ($item->getParentItem()) { continue; } $skuData[$item->getSku()] = [ 'item_id' => $item->getId(), 'managed' => Mage::helper('radial_core/quote_item')->isItemInventoried($item), 'virtual' => $item->getIsVirtual(), 'qty' => $item->getQty(), ]; } return $skuData; }
php
protected function _extractQuoteSkuData(Mage_Sales_Model_Quote $quote) { $skuData = []; // use getAllVisibleItems to prevent dupes due to parent config + child used both being included foreach ($quote->getAllVisibleItems() as $item) { // before item's have been saved, getAllVisible items won't properly // filter child items...this extra check fixes it if ($item->getParentItem()) { continue; } $skuData[$item->getSku()] = [ 'item_id' => $item->getId(), 'managed' => Mage::helper('radial_core/quote_item')->isItemInventoried($item), 'virtual' => $item->getIsVirtual(), 'qty' => $item->getQty(), ]; } return $skuData; }
Get sku and qty data for a given quote @param Mage_Sales_Model_Quote $quote Quote object to extract data from @return array Array of 'sku' => qty
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Session.php#L57-L75
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Session.php
Radial_Core_Model_Session._extractAddressData
protected function _extractAddressData(Mage_Customer_Model_Address_Abstract $address) { return array( 'street' => $address->getStreet(), 'city' => $address->getCity(), 'region_code' => $address->getRegionCode(), 'country_id' => $address->getCountryId(), 'postcode' => $address->getPostcode(), ); }
php
protected function _extractAddressData(Mage_Customer_Model_Address_Abstract $address) { return array( 'street' => $address->getStreet(), 'city' => $address->getCity(), 'region_code' => $address->getRegionCode(), 'country_id' => $address->getCountryId(), 'postcode' => $address->getPostcode(), ); }
Extract array of address data - street, city, region code, etc. from an address object @param Mage_Customer_Model_Address_Abstract $address Address object to pull data from @return array Extracted data
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Session.php#L81-L90
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Session.php
Radial_Core_Model_Session._extractQuoteShippingData
protected function _extractQuoteShippingData(Mage_Sales_Model_Quote $quote) { $shippingData = array(); foreach ($quote->getAllShippingAddresses() as $address) { $shippingData[] = array( 'method' => $address->getShippingMethod(), 'address' => $this->_extractAddressData($address), ); } return $shippingData; }
php
protected function _extractQuoteShippingData(Mage_Sales_Model_Quote $quote) { $shippingData = array(); foreach ($quote->getAllShippingAddresses() as $address) { $shippingData[] = array( 'method' => $address->getShippingMethod(), 'address' => $this->_extractAddressData($address), ); } return $shippingData; }
Extract shipping data from a quote - the shipping method and address for each shipping address in the quote. @param Mage_Sales_Model_Quote $quote The quote to extract the data from @return array Map of shipping method and address for each shipping address in the quote
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Session.php#L97-L107
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Session.php
Radial_Core_Model_Session._extractQuoteBillingData
protected function _extractQuoteBillingData(Mage_Sales_Model_Quote $quote) { $address = $quote->getBillingAddress(); return $address ? $this->_extractAddressData($address) : array(); }
php
protected function _extractQuoteBillingData(Mage_Sales_Model_Quote $quote) { $address = $quote->getBillingAddress(); return $address ? $this->_extractAddressData($address) : array(); }
Return array of billing address data if available, otherwise, an empty array @param Mage_Sales_Model_Quote $quote Quote object to extract data from @return array Array of billing address data
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Session.php#L122-L128
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Session.php
Radial_Core_Model_Session._extractQuoteAmounts
protected function _extractQuoteAmounts(Mage_Sales_Model_Quote $quote) { return array_map( function ($address) { return array( 'subtotal' => round($address->getSubtotal(), 4) ?: 0.0000, 'discount' => round($address->getDiscountAmount(), 4) ?: 0.0000, 'ship_amount' => round($address->getShippingAmount(), 4) ?: 0.0000, 'ship_discount' => round($address->getShippingDiscountAmount(), 4) ?: 0.0000, 'giftwrap_amount' => round($address->getGwPrice() + $address->getGwItemsPrice(), 4) ?: 0.0000, ); }, $quote->getAllShippingAddresses() ); }
php
protected function _extractQuoteAmounts(Mage_Sales_Model_Quote $quote) { return array_map( function ($address) { return array( 'subtotal' => round($address->getSubtotal(), 4) ?: 0.0000, 'discount' => round($address->getDiscountAmount(), 4) ?: 0.0000, 'ship_amount' => round($address->getShippingAmount(), 4) ?: 0.0000, 'ship_discount' => round($address->getShippingDiscountAmount(), 4) ?: 0.0000, 'giftwrap_amount' => round($address->getGwPrice() + $address->getGwItemsPrice(), 4) ?: 0.0000, ); }, $quote->getAllShippingAddresses() ); }
Extract quote amounts from each address. @param Mage_Sales_Model_Quote $quote @return array
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Session.php#L134-L148
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Session.php
Radial_Core_Model_Session._extractQuoteData
protected function _extractQuoteData(Mage_Sales_Model_Quote $quote) { return array( 'billing' => $this->_extractQuoteBillingData($quote), 'coupon' => $this->_extractQuoteCouponData($quote), 'shipping' => $this->_extractQuoteShippingData($quote), 'skus' => $this->_extractQuoteSkuData($quote), 'amounts' => $this->_extractQuoteAmounts($quote), ); }
php
protected function _extractQuoteData(Mage_Sales_Model_Quote $quote) { return array( 'billing' => $this->_extractQuoteBillingData($quote), 'coupon' => $this->_extractQuoteCouponData($quote), 'shipping' => $this->_extractQuoteShippingData($quote), 'skus' => $this->_extractQuoteSkuData($quote), 'amounts' => $this->_extractQuoteAmounts($quote), ); }
Extract coupon, shipping and sku/quantity data from a quote. Should return an array (map) keys: 'coupon' containing the current coupon code in use, 'shipping' containing all shipping addresses and methods, 'billing' containing the current billing address, and 'skus' containing all item skus and quantites @param Mage_Sales_Model_Quote $quote object to extract data from @return array extracted quote data
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Session.php#L157-L166
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Session.php
Radial_Core_Model_Session._diffSkus
protected function _diffSkus($oldItems, $newItems) { $skuDiff = []; foreach ($newItems as $sku => $details) { // only care if item qty changes or the item was previously removed from the quote and was added back, hence making its item id change. // None of the other item details, managed & virtual, should change between requests. if (!isset($oldItems[$sku]) || $oldItems[$sku]['qty'] !== $details['qty'] || $oldItems[$sku]['item_id'] !== $details['item_id']) { $skuDiff[$sku] = $details; } } foreach ($oldItems as $sku => $details) { if (!isset($newItems[$sku])) { $skuDiff[$sku] = ['managed' => $details['managed'], 'virtual' => $details['virtual'], 'qty' => 0, 'item_id' => $details['item_id']]; } } return $skuDiff ? ['skus' => $skuDiff] : $skuDiff; }
php
protected function _diffSkus($oldItems, $newItems) { $skuDiff = []; foreach ($newItems as $sku => $details) { // only care if item qty changes or the item was previously removed from the quote and was added back, hence making its item id change. // None of the other item details, managed & virtual, should change between requests. if (!isset($oldItems[$sku]) || $oldItems[$sku]['qty'] !== $details['qty'] || $oldItems[$sku]['item_id'] !== $details['item_id']) { $skuDiff[$sku] = $details; } } foreach ($oldItems as $sku => $details) { if (!isset($newItems[$sku])) { $skuDiff[$sku] = ['managed' => $details['managed'], 'virtual' => $details['virtual'], 'qty' => 0, 'item_id' => $details['item_id']]; } } return $skuDiff ? ['skus' => $skuDiff] : $skuDiff; }
Diff quote item quantities between the old items and new items. Diff should only check for changes to item quantities as no other data in the item data (managed and virtual) should ever change between requests. @param array $oldItems Item data extracted from a quote @param array $newItems Item data extracted from a quote @return array Array of item data if any items have changed, empty array otherwise
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Session.php#L217-L233
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Session.php
Radial_Core_Model_Session._diffQuoteData
protected function _diffQuoteData($oldQuote, $newQuote) { if (empty($oldQuote)) { return $newQuote; } return $this->_diffBilling($oldQuote['billing'], $newQuote['billing']) + $this->_diffCoupon($oldQuote['coupon'], $newQuote['coupon']) + $this->_diffShipping($oldQuote['shipping'], $newQuote['shipping']) + $this->_diffSkus($oldQuote['skus'], $newQuote['skus']) + $this->_diffAmounts($oldQuote['amounts'], $newQuote['amounts']); }
php
protected function _diffQuoteData($oldQuote, $newQuote) { if (empty($oldQuote)) { return $newQuote; } return $this->_diffBilling($oldQuote['billing'], $newQuote['billing']) + $this->_diffCoupon($oldQuote['coupon'], $newQuote['coupon']) + $this->_diffShipping($oldQuote['shipping'], $newQuote['shipping']) + $this->_diffSkus($oldQuote['skus'], $newQuote['skus']) + $this->_diffAmounts($oldQuote['amounts'], $newQuote['amounts']); }
Diff the new quote to the old quote. May contain keys for 'billing', 'coupon', 'shipping' and 'skus'. For more details on the type of changes detected for each key, see the responsible methods for diffing those sets of data. @param array $oldQuote Array of data extracted from a quote @param array $newQuote Array of data extracted from a quote @return array Array of changes made between the two sets of quote data
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Session.php#L252-L262
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Session.php
Radial_Core_Model_Session._anyItem
protected function _anyItem($items, $key) { foreach ($items as $item) { if (isset($item[$key]) && $item[$key]) { return true; } } return false; }
php
protected function _anyItem($items, $key) { foreach ($items as $item) { if (isset($item[$key]) && $item[$key]) { return true; } } return false; }
Check the set of items to have an item with the given key set to a truthy value. @param array $items array of item data @param string $key array key to check @return bool true if any item has a truthy value at the given key
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Session.php#L270-L278
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Session.php
Radial_Core_Model_Session._changeRequiresTaxUpdate
protected function _changeRequiresTaxUpdate($quoteData, $quoteDiff) { return (isset($quoteData['skus'])) && ( (isset($quoteDiff['skus'])) || (isset($quoteDiff['shipping'])) || (isset($quoteDiff['coupon'])) || (isset($quoteDiff['billing']) && $this->_itemsIncludeVirtualItem($quoteData['skus'])) || (isset($quoteDiff['amounts'])) ); }
php
protected function _changeRequiresTaxUpdate($quoteData, $quoteDiff) { return (isset($quoteData['skus'])) && ( (isset($quoteDiff['skus'])) || (isset($quoteDiff['shipping'])) || (isset($quoteDiff['coupon'])) || (isset($quoteDiff['billing']) && $this->_itemsIncludeVirtualItem($quoteData['skus'])) || (isset($quoteDiff['amounts'])) ); }
Check if changes to the quote require tax data to be updated. Current conditions which required tax to be updated: - coupon code changes - billing address changes for a quote with virtual items - shipping address changes - item quantities change - quote amounts change @param array $quoteData Array of data extracted from the newest quote object @param array $quoteDiff Array of changes made to the quote @return bool true iff a tax request should be made
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Session.php#L310-L319
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Session.php
Radial_Core_Model_Session._changeRequiresDetailsUpdate
protected function _changeRequiresDetailsUpdate($quoteData, $quoteDiff) { return isset($quoteData['skus']) && ( (isset($quoteDiff['skus']) && $this->_itemsIncludeManagedItem($quoteDiff['skus'])) || (isset($quoteDiff['shipping']) && $this->_itemsIncludeManagedItem($quoteData['skus'])) ); }
php
protected function _changeRequiresDetailsUpdate($quoteData, $quoteDiff) { return isset($quoteData['skus']) && ( (isset($quoteDiff['skus']) && $this->_itemsIncludeManagedItem($quoteDiff['skus'])) || (isset($quoteDiff['shipping']) && $this->_itemsIncludeManagedItem($quoteData['skus'])) ); }
Check if changes to the quote require inventory details to be updated. Current conditions which require inventory details to be updated: - shipping data changes for quote with managed stock items - items with managed stock change @param array $quoteData Array of data extracted from the newest quote object @param array $quoteDiff Array of changes made to the quote @return bool true iff an inventory details request should be made
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Session.php#L329-L335
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Session.php
Radial_Core_Model_Session.updateWithQuote
public function updateWithQuote(Mage_Sales_Model_Quote $quote) { $oldData = $this->getCurrentQuoteData(); $newData = $this->_extractQuoteData($quote); // Copy over the last_updated timestamp from the old quote data. This will // persist the timestamp from one set of data to the next preventing // the new data from auto expiring. $newData['last_updated'] = $oldData['last_updated']; $this->_logger->debug( 'Comparing quote data', $this->_context->getMetaData(__CLASS__, [ 'old' => json_encode($oldData), 'new' => json_encode($newData), ]) ); $quoteDiff = $this->_diffQuoteData($oldData, $newData); // if nothing has changed in the quote, no need to update flags, or // quote data as none of them will change if (!empty($quoteDiff)) { $changes = implode(', ', array_keys($quoteDiff)); $logData = ['changes' => $changes, 'diff' => json_encode($quoteDiff)]; $logMessage = 'Changes found in quote for: {changes}'; $this->_logger->debug($logMessage, $this->_context->getMetaData(__CLASS__, $logData)); $this // set the update required flags - any flags that are already true should remain true // flags should only be unset explicitly by the reset methods ->setTaxUpdateRequiredFlag($this->_changeRequiresTaxUpdate($newData, $quoteDiff)) ->setDetailsUpdateRequiredFlag($this->_changeRequiresDetailsUpdate($newData, $quoteDiff)) ->setCurrentQuoteData($newData); } else { $this->_logger->debug('No changes in quote.', $this->_context->getMetaData(__CLASS__)); } // always update the changes - could go from having changes to no changes $this->setQuoteChanges($quoteDiff); return $this; }
php
public function updateWithQuote(Mage_Sales_Model_Quote $quote) { $oldData = $this->getCurrentQuoteData(); $newData = $this->_extractQuoteData($quote); // Copy over the last_updated timestamp from the old quote data. This will // persist the timestamp from one set of data to the next preventing // the new data from auto expiring. $newData['last_updated'] = $oldData['last_updated']; $this->_logger->debug( 'Comparing quote data', $this->_context->getMetaData(__CLASS__, [ 'old' => json_encode($oldData), 'new' => json_encode($newData), ]) ); $quoteDiff = $this->_diffQuoteData($oldData, $newData); // if nothing has changed in the quote, no need to update flags, or // quote data as none of them will change if (!empty($quoteDiff)) { $changes = implode(', ', array_keys($quoteDiff)); $logData = ['changes' => $changes, 'diff' => json_encode($quoteDiff)]; $logMessage = 'Changes found in quote for: {changes}'; $this->_logger->debug($logMessage, $this->_context->getMetaData(__CLASS__, $logData)); $this // set the update required flags - any flags that are already true should remain true // flags should only be unset explicitly by the reset methods ->setTaxUpdateRequiredFlag($this->_changeRequiresTaxUpdate($newData, $quoteDiff)) ->setDetailsUpdateRequiredFlag($this->_changeRequiresDetailsUpdate($newData, $quoteDiff)) ->setCurrentQuoteData($newData); } else { $this->_logger->debug('No changes in quote.', $this->_context->getMetaData(__CLASS__)); } // always update the changes - could go from having changes to no changes $this->setQuoteChanges($quoteDiff); return $this; }
Update session data with a new quote object. Method should get a diff of the current/old quote data and diff it with the new quote data. This data should then be used to update flags as needed. Finally, the new data should replace existing data. @param Mage_Sales_Model_Quote $quote New quote object @return self
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Session.php#L418-L454
RadialCorp/magento-core
src/app/code/community/Radial/Core/Model/Session.php
Radial_Core_Model_Session.updateQuoteInventory
public function updateQuoteInventory(Mage_Sales_Model_Quote $quote) { $quoteData = $this->getCurrentQuoteData(); $quoteData['skus'] = $this->_extractQuoteSkuData($quote); $quoteData['last_updated'] = gmdate('c'); $this->setCurrentQuoteData($quoteData); return $this; }
php
public function updateQuoteInventory(Mage_Sales_Model_Quote $quote) { $quoteData = $this->getCurrentQuoteData(); $quoteData['skus'] = $this->_extractQuoteSkuData($quote); $quoteData['last_updated'] = gmdate('c'); $this->setCurrentQuoteData($quoteData); return $this; }
Update just the inventory data with the given quote. This should not set/reset any flags, just update the current data set with any changes made to the quote while checking inventory. This method should also update the timestamp on the current quote data. @param Mage_Sales_Model_Quote $quote The quote to update inventory data with @return self
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Model/Session.php#L463-L470
OpenClassrooms/DoctrineCacheExtensionBundle
Services/DataCollector/DebugCacheProviderDecorator.php
DebugCacheProviderDecorator.fetch
public function fetch($id) { $start = $this->startQuery(); $data = $this->cacheProviderDecorator->fetch($id); $stop = $this->stopQuery(); self::$collectedData[self::$callId++] = $this->create(CacheCollectedData::FETCH) ->withData($data) ->withId($id) ->withStart($start) ->withStop($stop) ->build(); return $data; }
php
public function fetch($id) { $start = $this->startQuery(); $data = $this->cacheProviderDecorator->fetch($id); $stop = $this->stopQuery(); self::$collectedData[self::$callId++] = $this->create(CacheCollectedData::FETCH) ->withData($data) ->withId($id) ->withStart($start) ->withStop($stop) ->build(); return $data; }
{@inheritdoc}
https://github.com/OpenClassrooms/DoctrineCacheExtensionBundle/blob/c6d1ded7e5a22b20643486cb3fa84cddd86135a5/Services/DataCollector/DebugCacheProviderDecorator.php#L72-L86
OpenClassrooms/DoctrineCacheExtensionBundle
Services/DataCollector/DebugCacheProviderDecorator.php
DebugCacheProviderDecorator.fetchWithNamespace
public function fetchWithNamespace($id, $namespaceId = null) { $start = $this->startQuery(); $data = $this->cacheProviderDecorator->fetchWithNamespace($id, $namespaceId); $stop = $this->stopQuery(); self::$collectedData[self::$callId++] = $this->create(CacheCollectedData::FETCH_WITH_NAMESPACE) ->withData($data) ->withId($id) ->withNamespaceId($namespaceId) ->withStart($start) ->withStop($stop) ->build(); return $data; }
php
public function fetchWithNamespace($id, $namespaceId = null) { $start = $this->startQuery(); $data = $this->cacheProviderDecorator->fetchWithNamespace($id, $namespaceId); $stop = $this->stopQuery(); self::$collectedData[self::$callId++] = $this->create(CacheCollectedData::FETCH_WITH_NAMESPACE) ->withData($data) ->withId($id) ->withNamespaceId($namespaceId) ->withStart($start) ->withStop($stop) ->build(); return $data; }
{@inheritdoc}
https://github.com/OpenClassrooms/DoctrineCacheExtensionBundle/blob/c6d1ded7e5a22b20643486cb3fa84cddd86135a5/Services/DataCollector/DebugCacheProviderDecorator.php#L121-L136
OpenClassrooms/DoctrineCacheExtensionBundle
Services/DataCollector/DebugCacheProviderDecorator.php
DebugCacheProviderDecorator.invalidate
public function invalidate($namespaceId) { $start = $this->startQuery(); $invalidated = $this->cacheProviderDecorator->invalidate($namespaceId); $stop = $this->stopQuery(); self::$collectedData[self::$callId++] = $this->create(CacheCollectedData::INVALIDATE) ->withNamespaceId($namespaceId) ->withStart($start) ->withStop($stop) ->build(); return $invalidated; }
php
public function invalidate($namespaceId) { $start = $this->startQuery(); $invalidated = $this->cacheProviderDecorator->invalidate($namespaceId); $stop = $this->stopQuery(); self::$collectedData[self::$callId++] = $this->create(CacheCollectedData::INVALIDATE) ->withNamespaceId($namespaceId) ->withStart($start) ->withStop($stop) ->build(); return $invalidated; }
{@inheritdoc}
https://github.com/OpenClassrooms/DoctrineCacheExtensionBundle/blob/c6d1ded7e5a22b20643486cb3fa84cddd86135a5/Services/DataCollector/DebugCacheProviderDecorator.php#L141-L154
OpenClassrooms/DoctrineCacheExtensionBundle
Services/DataCollector/DebugCacheProviderDecorator.php
DebugCacheProviderDecorator.save
public function save($id, $data, $lifeTime = null) { $start = $this->startQuery(); $saved = $this->cacheProviderDecorator->save($id, $data, $lifeTime); $stop = $this->stopQuery(); self::$collectedData[self::$callId++] = $this->create(CacheCollectedData::SAVE) ->withData($data) ->withId($id) ->withStart($start) ->withStop($stop) ->build(); return $saved; }
php
public function save($id, $data, $lifeTime = null) { $start = $this->startQuery(); $saved = $this->cacheProviderDecorator->save($id, $data, $lifeTime); $stop = $this->stopQuery(); self::$collectedData[self::$callId++] = $this->create(CacheCollectedData::SAVE) ->withData($data) ->withId($id) ->withStart($start) ->withStop($stop) ->build(); return $saved; }
{@inheritdoc}
https://github.com/OpenClassrooms/DoctrineCacheExtensionBundle/blob/c6d1ded7e5a22b20643486cb3fa84cddd86135a5/Services/DataCollector/DebugCacheProviderDecorator.php#L159-L173
OpenClassrooms/DoctrineCacheExtensionBundle
Services/DataCollector/DebugCacheProviderDecorator.php
DebugCacheProviderDecorator.saveWithNamespace
public function saveWithNamespace($id, $data, $namespaceId = null, $lifeTime = null) { $start = $this->startQuery(); $saved = $this->cacheProviderDecorator->saveWithNamespace($id, $data, $namespaceId, $lifeTime); $stop = $this->stopQuery(); self::$collectedData[self::$callId++] = $this->create(CacheCollectedData::SAVE_WITH_NAMESPACE) ->withData($data) ->withId($id) ->withNamespaceId($namespaceId) ->withStart($start) ->withStop($stop) ->build(); return $saved; }
php
public function saveWithNamespace($id, $data, $namespaceId = null, $lifeTime = null) { $start = $this->startQuery(); $saved = $this->cacheProviderDecorator->saveWithNamespace($id, $data, $namespaceId, $lifeTime); $stop = $this->stopQuery(); self::$collectedData[self::$callId++] = $this->create(CacheCollectedData::SAVE_WITH_NAMESPACE) ->withData($data) ->withId($id) ->withNamespaceId($namespaceId) ->withStart($start) ->withStop($stop) ->build(); return $saved; }
{@inheritdoc}
https://github.com/OpenClassrooms/DoctrineCacheExtensionBundle/blob/c6d1ded7e5a22b20643486cb3fa84cddd86135a5/Services/DataCollector/DebugCacheProviderDecorator.php#L178-L193
Clevis/Se34
Se34/BrowserSession.php
BrowserSession.keepOpen
public function keepOpen() { $stoppedProperty = new \ReflectionProperty(get_parent_class($this), 'stopped'); $stoppedProperty->setAccessible(TRUE); $stoppedProperty->setValue($this, TRUE); }
php
public function keepOpen() { $stoppedProperty = new \ReflectionProperty(get_parent_class($this), 'stopped'); $stoppedProperty->setAccessible(TRUE); $stoppedProperty->setValue($this, TRUE); }
Calling this method avoids destructor to send DELETE session request. The browser window will close either way, but after some quite long timeout (at least with ChromeDriver).
https://github.com/Clevis/Se34/blob/c52d579a831ba5642dae464882da012b0409ae46/Se34/BrowserSession.php#L109-L114
Clevis/Se34
Se34/BrowserSession.php
BrowserSession.getLink
public function getLink($presenterName, $parameters = array()) { $url = new \Nette\Http\UrlScript($this->context->parameters['selenium']['baseUrl']); $url->scriptPath = $url->path; $appRequest = new \Nette\Application\Request($presenterName, 'GET', Utils::strToArray($parameters)); return $this->context->router->constructUrl($appRequest, $url); }
php
public function getLink($presenterName, $parameters = array()) { $url = new \Nette\Http\UrlScript($this->context->parameters['selenium']['baseUrl']); $url->scriptPath = $url->path; $appRequest = new \Nette\Application\Request($presenterName, 'GET', Utils::strToArray($parameters)); return $this->context->router->constructUrl($appRequest, $url); }
Creates an URL. Parameters can be either a PHP array, or a Neon array without brackets. Ie. Instead of `array('a' => 'b', 'c' => 'd')` you can pass `'a=b,c=d'`. @param string $presenterName @param array|string $parameters
https://github.com/Clevis/Se34/blob/c52d579a831ba5642dae464882da012b0409ae46/Se34/BrowserSession.php#L146-L152
Clevis/Se34
Se34/BrowserSession.php
BrowserSession.getAppRequest
public function getAppRequest($url = NULL) { $httpRequest = new \Nette\Http\Request($this->getUrlScriptForUrl($url ? : $this->url())); return $this->context->router->match($httpRequest); }
php
public function getAppRequest($url = NULL) { $httpRequest = new \Nette\Http\Request($this->getUrlScriptForUrl($url ? : $this->url())); return $this->context->router->match($httpRequest); }
URL back-routed into application request object. @param string|NULL $url URL or NULL for current URL. @return \Nette\Application\Request
https://github.com/Clevis/Se34/blob/c52d579a831ba5642dae464882da012b0409ae46/Se34/BrowserSession.php#L160-L164
Clevis/Se34
Se34/BrowserSession.php
BrowserSession.waitForAlert
public function waitForAlert($timeout = 60) { $result = FALSE; $i = 0; do { sleep(1); try { $result = $this->alertText(); } catch (\RuntimeException $e) { ; } } while (++$i < $timeout && $result === FALSE); return $result; }
php
public function waitForAlert($timeout = 60) { $result = FALSE; $i = 0; do { sleep(1); try { $result = $this->alertText(); } catch (\RuntimeException $e) { ; } } while (++$i < $timeout && $result === FALSE); return $result; }
Wait for javascript alert, prompt or confirm dialog. @param int $timeout Patience in seconds. @return string|bool Alert text, or FALSE if waiting times out.
https://github.com/Clevis/Se34/blob/c52d579a831ba5642dae464882da012b0409ae46/Se34/BrowserSession.php#L172-L189
Clevis/Se34
Se34/BrowserSession.php
BrowserSession.waitForCondition
public function waitForCondition($jsCondition, $timeout = 60) { $i = 0; do { sleep(1); } while ( !($result = $this->execute(array('script' => 'return ' . $jsCondition, 'args' => array()))) && $i++ < $timeout ); return $result; }
php
public function waitForCondition($jsCondition, $timeout = 60) { $i = 0; do { sleep(1); } while ( !($result = $this->execute(array('script' => 'return ' . $jsCondition, 'args' => array()))) && $i++ < $timeout ); return $result; }
Wait for fulfilment of some javascript condition. @param string $jsCondition Javascript code. @param int $timeout Amount of patience in seconds. @return bool Whether the condition was fulfilled.
https://github.com/Clevis/Se34/blob/c52d579a831ba5642dae464882da012b0409ae46/Se34/BrowserSession.php#L220-L231
Clevis/Se34
Se34/BrowserSession.php
BrowserSession.getActiveElement
public function getActiveElement() { $response = $this->driver->curl('POST', $this->url->addCommand('element/active')); return Element::fromResponseValue($response->getValue(), $this->url->descend('element'), $this->driver); }
php
public function getActiveElement() { $response = $this->driver->curl('POST', $this->url->addCommand('element/active')); return Element::fromResponseValue($response->getValue(), $this->url->descend('element'), $this->driver); }
Get the element on the page that currently has focus. @return Element
https://github.com/Clevis/Se34/blob/c52d579a831ba5642dae464882da012b0409ae46/Se34/BrowserSession.php#L249-L253
Clevis/Se34
Se34/BrowserSession.php
BrowserSession.element
public function element(\PHPUnit_Extensions_Selenium2TestCase_ElementCriteria $criteria) { $value = $this->postCommand('element', $criteria); return Element::fromResponseValue($value, $this->url->descend('element'), $this->driver); }
php
public function element(\PHPUnit_Extensions_Selenium2TestCase_ElementCriteria $criteria) { $value = $this->postCommand('element', $criteria); return Element::fromResponseValue($value, $this->url->descend('element'), $this->driver); }
Finds an element using the criteria. Criteria are set by this WTF way: <code> $session->element($session->using('xpath')->value('//input[type="text"]')); </code> @param \PHPUnit_Extensions_Selenium2TestCase_ElementCriteria $criteria @return Element
https://github.com/Clevis/Se34/blob/c52d579a831ba5642dae464882da012b0409ae46/Se34/BrowserSession.php#L266-L270
Clevis/Se34
Se34/BrowserSession.php
BrowserSession.elements
public function elements(\PHPUnit_Extensions_Selenium2TestCase_ElementCriteria $criteria) { $values = $this->postCommand('elements', $criteria); $elements = array(); foreach ($values as $value) { $elements[] = Element::fromResponseValue($value, $this->url->descend('element'), $this->driver); } return $elements; }
php
public function elements(\PHPUnit_Extensions_Selenium2TestCase_ElementCriteria $criteria) { $values = $this->postCommand('elements', $criteria); $elements = array(); foreach ($values as $value) { $elements[] = Element::fromResponseValue($value, $this->url->descend('element'), $this->driver); } return $elements; }
Finds elements using given criteria. Similar to {@see BrowserSession::element()}, only this returns all matched elements as an array. Also, this doesn't throw an exception if no element was found. @param \PHPUnit_Extensions_Selenium2TestCase_ElementCriteria $criteria @return Element[] array of instances of Se34\Element
https://github.com/Clevis/Se34/blob/c52d579a831ba5642dae464882da012b0409ae46/Se34/BrowserSession.php#L282-L291
Clevis/Se34
Se34/BrowserSession.php
BrowserSession.findElement
public function findElement($strategy, $selector) { return $this->element($this->using($strategy)->value($selector)); }
php
public function findElement($strategy, $selector) { return $this->element($this->using($strategy)->value($selector)); }
Find the first element that matches the criteria and return it. Or throw an exception. @param string $strategy @param string $selector @return Element
https://github.com/Clevis/Se34/blob/c52d579a831ba5642dae464882da012b0409ae46/Se34/BrowserSession.php#L367-L370
Clevis/Se34
Se34/BrowserSession.php
BrowserSession.findElements
public function findElements($strategy, $selector) { return $this->elements($this->using($strategy)->value($selector)); }
php
public function findElements($strategy, $selector) { return $this->elements($this->using($strategy)->value($selector)); }
Find all elements that match given criteria. If none found, than return an empty array. @param string $strategy @param string $selector @return Element[]
https://github.com/Clevis/Se34/blob/c52d579a831ba5642dae464882da012b0409ae46/Se34/BrowserSession.php#L380-L383
LoggerEssentials/LoggerEssentials
src/Formatters/NobrFormatter.php
NobrFormatter.log
public function log($level, $message, array $context = array()) { $message = preg_replace("/[\r\n]+/", $this->replacement, $message); $this->logger()->log($level, $message, $context); }
php
public function log($level, $message, array $context = array()) { $message = preg_replace("/[\r\n]+/", $this->replacement, $message); $this->logger()->log($level, $message, $context); }
Logs with an arbitrary level. @param mixed $level @param string $message @param array $context @return null
https://github.com/LoggerEssentials/LoggerEssentials/blob/f32f9b865eacfccced90697f3eb69dc4ad80dc96/src/Formatters/NobrFormatter.php#L27-L30
stonedz/pff2
src/Abs/AModule.php
AModule.getRequiredModules
public function getRequiredModules($moduleName) { $moduleName = strtolower($moduleName); if (isset($this->_requiredModules[$moduleName])) { return $this->_requiredModules[$moduleName]; } else { return null; } }
php
public function getRequiredModules($moduleName) { $moduleName = strtolower($moduleName); if (isset($this->_requiredModules[$moduleName])) { return $this->_requiredModules[$moduleName]; } else { return null; } }
Gets a module @param string $moduleName @return AModule|null
https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/Abs/AModule.php#L122-L130
stonedz/pff2
src/Abs/AModule.php
AModule.readConfig
public function readConfig($configFile) { $yamlParser = new \Symfony\Component\Yaml\Parser(); $userConfPath = ROOT . DS . 'app' . DS . 'config' . DS . 'modules' . DS . $configFile; $userCustomPath = ROOT. DS . 'app'. DS.'modules'.DS.$configFile; $composerConfPath = ROOT . DS . 'modules' . DS . $configFile; $libConfPath = ROOT_LIB . DS . 'src' . DS . 'modules' . DS . $configFile; if (file_exists($userConfPath)) { $confPath = $userConfPath; } elseif (file_exists($userCustomPath)) { $confPath = $userCustomPath; } elseif (file_exists($composerConfPath)) { $confPath = $composerConfPath; } elseif (file_exists($libConfPath)) { $confPath = $libConfPath; } else { throw new ModuleException ("Module configuration file not found!"); } try { $conf = $yamlParser->parse(file_get_contents($confPath)); } catch (\Symfony\Component\Yaml\Exception\ParseException $e) { throw new ModuleException("Unable to parse module configuration file for AutomaticHeaderFooter module: " . $e->getMessage()); } return $conf; }
php
public function readConfig($configFile) { $yamlParser = new \Symfony\Component\Yaml\Parser(); $userConfPath = ROOT . DS . 'app' . DS . 'config' . DS . 'modules' . DS . $configFile; $userCustomPath = ROOT. DS . 'app'. DS.'modules'.DS.$configFile; $composerConfPath = ROOT . DS . 'modules' . DS . $configFile; $libConfPath = ROOT_LIB . DS . 'src' . DS . 'modules' . DS . $configFile; if (file_exists($userConfPath)) { $confPath = $userConfPath; } elseif (file_exists($userCustomPath)) { $confPath = $userCustomPath; } elseif (file_exists($composerConfPath)) { $confPath = $composerConfPath; } elseif (file_exists($libConfPath)) { $confPath = $libConfPath; } else { throw new ModuleException ("Module configuration file not found!"); } try { $conf = $yamlParser->parse(file_get_contents($confPath)); } catch (\Symfony\Component\Yaml\Exception\ParseException $e) { throw new ModuleException("Unable to parse module configuration file for AutomaticHeaderFooter module: " . $e->getMessage()); } return $conf; }
Reads the configuration file ad returns a configuration array @param string $configFile The module filename @throws ModuleException @return array
https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/Abs/AModule.php#L195-L220
yii2lab/yii2-rbac
src/domain/repositories/base/BaseItemRepository.php
BaseItemRepository.getRolesByUser
public function getRolesByUser($userId) { $roles = $this->getDefaultRoleInstances(); foreach ($this->domain->assignment->getAssignments($userId) as $name => $assignment) { $role = $this->items[$assignment->roleName]; if ($role->type === Item::TYPE_ROLE) { $roles[$name] = $role; } } return $roles; }
php
public function getRolesByUser($userId) { $roles = $this->getDefaultRoleInstances(); foreach ($this->domain->assignment->getAssignments($userId) as $name => $assignment) { $role = $this->items[$assignment->roleName]; if ($role->type === Item::TYPE_ROLE) { $roles[$name] = $role; } } return $roles; }
{@inheritdoc} The roles returned by this method include the roles assigned via [[$defaultRoles]].
https://github.com/yii2lab/yii2-rbac/blob/e72ac0359af660690c161451f864208b2d20919d/src/domain/repositories/base/BaseItemRepository.php#L192-L203
yii2lab/yii2-rbac
src/domain/repositories/base/BaseItemRepository.php
BaseItemRepository.updateItem
public function updateItem($name, $item) { $this->items = ItemHelper::updateItems($name, $item, $this->items); $this->children = ItemHelper::updateChildren($name, $item, $this->children); $this->saveItems(); return true; }
php
public function updateItem($name, $item) { $this->items = ItemHelper::updateItems($name, $item, $this->items); $this->children = ItemHelper::updateChildren($name, $item, $this->children); $this->saveItems(); return true; }
{@inheritdoc}
https://github.com/yii2lab/yii2-rbac/blob/e72ac0359af660690c161451f864208b2d20919d/src/domain/repositories/base/BaseItemRepository.php#L370-L377
yii2lab/yii2-rbac
src/domain/repositories/base/BaseItemRepository.php
BaseItemRepository.getDirectPermissionsByUser
protected function getDirectPermissionsByUser($userId) { $assignments = $this->domain->assignment->getAssignments($userId); return ItemHelper::allPermissionsByAssignments($this->items, $assignments); }
php
protected function getDirectPermissionsByUser($userId) { $assignments = $this->domain->assignment->getAssignments($userId); return ItemHelper::allPermissionsByAssignments($this->items, $assignments); }
Returns all permissions that are directly assigned to user. @param string|int $userId the user ID (see [[\yii\web\User::id]]) @return Permission[] all direct permissions that the user has. The array is indexed by the permission names. @since 2.0.7
https://github.com/yii2lab/yii2-rbac/blob/e72ac0359af660690c161451f864208b2d20919d/src/domain/repositories/base/BaseItemRepository.php#L396-L400
yii2lab/yii2-rbac
src/domain/repositories/base/BaseItemRepository.php
BaseItemRepository.removeAllItems
protected function removeAllItems($type) { $names = ItemHelper::getItemsNameByType($this->items, $type); if (empty($names)) { return; } foreach ($names as $n => $hardTrue) { $this->domain->assignment->revokeAllByItemName($n); } /*foreach ($this->domain->assignment->all() as $i => $assignments) { foreach ($assignments as $n => $assignment) { if (isset($names[$assignment->roleName])) { unset($this->assignments[$i][$n]); } } }*/ $this->children = ItemHelper::removeByNames($this->children, $names); $this->saveItems(); }
php
protected function removeAllItems($type) { $names = ItemHelper::getItemsNameByType($this->items, $type); if (empty($names)) { return; } foreach ($names as $n => $hardTrue) { $this->domain->assignment->revokeAllByItemName($n); } /*foreach ($this->domain->assignment->all() as $i => $assignments) { foreach ($assignments as $n => $assignment) { if (isset($names[$assignment->roleName])) { unset($this->assignments[$i][$n]); } } }*/ $this->children = ItemHelper::removeByNames($this->children, $names); $this->saveItems(); }
Removes all auth items of the specified type. @param int $type the auth item type (either Item::TYPE_PERMISSION or Item::TYPE_ROLE)
https://github.com/yii2lab/yii2-rbac/blob/e72ac0359af660690c161451f864208b2d20919d/src/domain/repositories/base/BaseItemRepository.php#L454-L476
OpenClassrooms/FrontDesk
src/Services/Impl/VisitServiceImpl.php
VisitServiceImpl.getVisits
public function getVisits($personId, $from = null, $to = null) { return $this->visitGateway->findAllByPersonId($personId, $from, $to); }
php
public function getVisits($personId, $from = null, $to = null) { return $this->visitGateway->findAllByPersonId($personId, $from, $to); }
{@inheritdoc}
https://github.com/OpenClassrooms/FrontDesk/blob/1d221ff96fa0a3948b8bd210dec77542074ed988/src/Services/Impl/VisitServiceImpl.php#L21-L24
schpill/thin
src/Injection/Manager.php
InstanceManager.addSharedInstance
public function addSharedInstance($instance, $classOrAlias) { if (!is_object($instance)) { throw new Exception('This method requires an object to be shared. Class or Alias given: ' . $classOrAlias); } $this->sharedInstances[$classOrAlias] = $instance; }
php
public function addSharedInstance($instance, $classOrAlias) { if (!is_object($instance)) { throw new Exception('This method requires an object to be shared. Class or Alias given: ' . $classOrAlias); } $this->sharedInstances[$classOrAlias] = $instance; }
Add shared instance @param object $instance @param string $classOrAlias @throws Exception
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Injection/Manager.php#L88-L95
schpill/thin
src/Injection/Manager.php
InstanceManager.hasSharedInstanceWithParameters
public function hasSharedInstanceWithParameters($classOrAlias, array $params, $returnFastHashLookupKey = false) { ksort($params); $hashKey = $this->createHashForKeys($classOrAlias, array_keys($params)); if (isset($this->sharedInstancesWithParams['hashShort'][$hashKey])) { $hashValue = $this->createHashForValues($classOrAlias, $params); if (isset($this->sharedInstancesWithParams['hashLong'][$hashKey . '/' . $hashValue])) { return ($returnFastHashLookupKey) ? $hashKey . '/' . $hashValue : true; } } return false; }
php
public function hasSharedInstanceWithParameters($classOrAlias, array $params, $returnFastHashLookupKey = false) { ksort($params); $hashKey = $this->createHashForKeys($classOrAlias, array_keys($params)); if (isset($this->sharedInstancesWithParams['hashShort'][$hashKey])) { $hashValue = $this->createHashForValues($classOrAlias, $params); if (isset($this->sharedInstancesWithParams['hashLong'][$hashKey . '/' . $hashValue])) { return ($returnFastHashLookupKey) ? $hashKey . '/' . $hashValue : true; } } return false; }
hasSharedInstanceWithParameters() @param string $classOrAlias @param array $params @param bool $returnFastHashLookupKey @return bool|string
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Injection/Manager.php#L105-L117
schpill/thin
src/Injection/Manager.php
InstanceManager.addSharedInstanceWithParameters
public function addSharedInstanceWithParameters($instance, $classOrAlias, array $params) { ksort($params); $hashKey = $this->createHashForKeys($classOrAlias, array_keys($params)); $hashValue = $this->createHashForValues($classOrAlias, $params); if (!isset($this->sharedInstancesWithParams[$hashKey]) || !is_array($this->sharedInstancesWithParams[$hashKey])) { $this->sharedInstancesWithParams[$hashKey] = []; } $this->sharedInstancesWithParams['hashShort'][$hashKey] = true; $this->sharedInstancesWithParams['hashLong'][$hashKey . '/' . $hashValue] = $instance; }
php
public function addSharedInstanceWithParameters($instance, $classOrAlias, array $params) { ksort($params); $hashKey = $this->createHashForKeys($classOrAlias, array_keys($params)); $hashValue = $this->createHashForValues($classOrAlias, $params); if (!isset($this->sharedInstancesWithParams[$hashKey]) || !is_array($this->sharedInstancesWithParams[$hashKey])) { $this->sharedInstancesWithParams[$hashKey] = []; } $this->sharedInstancesWithParams['hashShort'][$hashKey] = true; $this->sharedInstancesWithParams['hashLong'][$hashKey . '/' . $hashValue] = $instance; }
addSharedInstanceWithParameters() @param object $instance @param string $classOrAlias @param array $params @return void
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Injection/Manager.php#L127-L140
schpill/thin
src/Injection/Manager.php
InstanceManager.getSharedInstanceWithParameters
public function getSharedInstanceWithParameters($classOrAlias, array $params, $fastHashFromHasLookup = null) { if ($fastHashFromHasLookup) { return $this->sharedInstancesWithParams['hashLong'][$fastHashFromHasLookup]; } ksort($params); $hashKey = $this->createHashForKeys($classOrAlias, array_keys($params)); if (isset($this->sharedInstancesWithParams['hashShort'][$hashKey])) { $hashValue = $this->createHashForValues($classOrAlias, $params); if (isset($this->sharedInstancesWithParams['hashLong'][$hashKey . '/' . $hashValue])) { return $this->sharedInstancesWithParams['hashLong'][$hashKey . '/' . $hashValue]; } } return false; }
php
public function getSharedInstanceWithParameters($classOrAlias, array $params, $fastHashFromHasLookup = null) { if ($fastHashFromHasLookup) { return $this->sharedInstancesWithParams['hashLong'][$fastHashFromHasLookup]; } ksort($params); $hashKey = $this->createHashForKeys($classOrAlias, array_keys($params)); if (isset($this->sharedInstancesWithParams['hashShort'][$hashKey])) { $hashValue = $this->createHashForValues($classOrAlias, $params); if (isset($this->sharedInstancesWithParams['hashLong'][$hashKey . '/' . $hashValue])) { return $this->sharedInstancesWithParams['hashLong'][$hashKey . '/' . $hashValue]; } } return false; }
Retrieves an instance by its name and the parameters stored at its instantiation @param string $classOrAlias @param array $params @param bool|null $fastHashFromHasLookup @return object|bool false if no instance was found
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Injection/Manager.php#L150-L168
schpill/thin
src/Injection/Manager.php
InstanceManager.getClassFromAlias
public function getClassFromAlias($alias) { if (!isset($this->aliases[$alias])) { return false; } $r = 0; while (isset($this->aliases[$alias])) { $alias = $this->aliases[$alias]; $r++; if ($r > 100) { throw new Exception( sprintf('Possible infinite recursion in DI alias! Max recursion of 100 levels reached at alias "%s".', $alias) ); } } return $alias; }
php
public function getClassFromAlias($alias) { if (!isset($this->aliases[$alias])) { return false; } $r = 0; while (isset($this->aliases[$alias])) { $alias = $this->aliases[$alias]; $r++; if ($r > 100) { throw new Exception( sprintf('Possible infinite recursion in DI alias! Max recursion of 100 levels reached at alias "%s".', $alias) ); } } return $alias; }
getClassFromAlias() @param string @return string|bool @throws Exception
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Injection/Manager.php#L198-L218
schpill/thin
src/Injection/Manager.php
InstanceManager.addAlias
public function addAlias($alias, $class, array $parameters = []) { if (!preg_match('#^[a-zA-Z0-9-_]+$#', $alias)) { throw new Exception( 'Aliases must be alphanumeric and can contain dashes and underscores only.' ); } $this->aliases[$alias] = $class; if ($parameters) { $this->setParameters($alias, $parameters); } }
php
public function addAlias($alias, $class, array $parameters = []) { if (!preg_match('#^[a-zA-Z0-9-_]+$#', $alias)) { throw new Exception( 'Aliases must be alphanumeric and can contain dashes and underscores only.' ); } $this->aliases[$alias] = $class; if ($parameters) { $this->setParameters($alias, $parameters); } }
Add alias @throws Exception @param string $alias @param string $class @param array $parameters @return void
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Injection/Manager.php#L258-L271
schpill/thin
src/Injection/Manager.php
InstanceManager.hasConfig
public function hasConfig($aliasOrClass) { $key = ($this->hasAlias($aliasOrClass)) ? 'alias:' . $this->getBaseAlias($aliasOrClass) : $aliasOrClass; if (!isset($this->configurations[$key])) { return false; } if ($this->configurations[$key] === $this->configurationTemplate) { return false; } return true; }
php
public function hasConfig($aliasOrClass) { $key = ($this->hasAlias($aliasOrClass)) ? 'alias:' . $this->getBaseAlias($aliasOrClass) : $aliasOrClass; if (!isset($this->configurations[$key])) { return false; } if ($this->configurations[$key] === $this->configurationTemplate) { return false; } return true; }
Check for configuration @param string $aliasOrClass @return bool
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Injection/Manager.php#L279-L292