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
chippyash/Currency
src/Chippyash/Currency/Factory.php
Factory.create
public static function create($code, $value = 0) { $cd = strtoupper($code); list($symbol, $precision, $name) = self::getDefinition($cd); $crcy = new Currency($value, $cd, $symbol, $precision, $name); $crcy->setLocale(self::getLocale()); return $crcy; }
php
public static function create($code, $value = 0) { $cd = strtoupper($code); list($symbol, $precision, $name) = self::getDefinition($cd); $crcy = new Currency($value, $cd, $symbol, $precision, $name); $crcy->setLocale(self::getLocale()); return $crcy; }
Create a currency @param string $code Currency 3 letter ISO4217 code @param int $value initial value for currency @return Currency @throws \ErrorException
https://github.com/chippyash/Currency/blob/d2c6a3da2d1443818b98206ec2cb8f34c2a3be84/src/Chippyash/Currency/Factory.php#L41-L49
chippyash/Currency
src/Chippyash/Currency/Factory.php
Factory.getLocale
public static function getLocale() { if (empty(self::$locale)) { self::$locale = new StringType(\locale_get_default()); } return self::$locale; }
php
public static function getLocale() { if (empty(self::$locale)) { self::$locale = new StringType(\locale_get_default()); } return self::$locale; }
Get locale to be used for currency creation Will default to locale_get_default() if not set @return StringType
https://github.com/chippyash/Currency/blob/d2c6a3da2d1443818b98206ec2cb8f34c2a3be84/src/Chippyash/Currency/Factory.php#L67-L74
chippyash/Currency
src/Chippyash/Currency/Factory.php
Factory.getDefinition
protected static function getDefinition($code) { $currencies = self::getDefinitions(); $nodes = $currencies->xpath("//currency[@code='{$code}']"); if (empty($nodes)) { throw new \InvalidArgumentException("Unknown currency: {$code}"); } $cNode = $nodes[0]; $def = array( self::createSymbol($cNode->symbol, $code), intval($cNode->exponent), self::createName($cNode), ); return $def; }
php
protected static function getDefinition($code) { $currencies = self::getDefinitions(); $nodes = $currencies->xpath("//currency[@code='{$code}']"); if (empty($nodes)) { throw new \InvalidArgumentException("Unknown currency: {$code}"); } $cNode = $nodes[0]; $def = array( self::createSymbol($cNode->symbol, $code), intval($cNode->exponent), self::createName($cNode), ); return $def; }
Get a currency definition @param string $code ISO4217 currency code @return array ['symbol','precision', 'name'] @throws \ErrorException
https://github.com/chippyash/Currency/blob/d2c6a3da2d1443818b98206ec2cb8f34c2a3be84/src/Chippyash/Currency/Factory.php#L84-L101
chippyash/Currency
src/Chippyash/Currency/Factory.php
Factory.getDefinitions
protected static function getDefinitions() { if (empty(self::$definitions)) { self::$definitions = \simplexml_load_file(__DIR__ . '/currencies.xml'); } return self::$definitions; }
php
protected static function getDefinitions() { if (empty(self::$definitions)) { self::$definitions = \simplexml_load_file(__DIR__ . '/currencies.xml'); } return self::$definitions; }
Load currency definitions @return \SimpleXMLElement
https://github.com/chippyash/Currency/blob/d2c6a3da2d1443818b98206ec2cb8f34c2a3be84/src/Chippyash/Currency/Factory.php#L108-L115
chippyash/Currency
src/Chippyash/Currency/Factory.php
Factory.createSymbol
protected static function createSymbol(\SimpleXMLElement $sNode, $code) { switch((string) $sNode['type']) { case 'UCS': $symbol = (string) $sNode['UTF-8']; break; case null: //no symbol - use code default: $symbol = $code; break; } return $symbol; }
php
protected static function createSymbol(\SimpleXMLElement $sNode, $code) { switch((string) $sNode['type']) { case 'UCS': $symbol = (string) $sNode['UTF-8']; break; case null: //no symbol - use code default: $symbol = $code; break; } return $symbol; }
Create currency symbol from the symbol node @param \SimpleXMLElement $sNode @param string $code currency code @return string
https://github.com/chippyash/Currency/blob/d2c6a3da2d1443818b98206ec2cb8f34c2a3be84/src/Chippyash/Currency/Factory.php#L125-L138
chippyash/Currency
src/Chippyash/Currency/Factory.php
Factory.createName
protected static function createName(\SimpleXMLElement $currency) { $locale = self::getLocale(); //first - see if we have an exact locale match $nodes = $currency->xpath("name[@lang='{$locale}']"); if (count($nodes) > 0) { return (string) $nodes[0]; } //next, see if we have a name for the language part of the locale $lang = \locale_get_primary_language($locale()); $nodes = $currency->xpath("name[@lang='{$lang}']"); if (count($nodes) > 0) { return (string) $nodes[0]; } //else default to using 'en' $nodes = $currency->xpath("name[@lang='en']"); return (string) $nodes[0]; }
php
protected static function createName(\SimpleXMLElement $currency) { $locale = self::getLocale(); //first - see if we have an exact locale match $nodes = $currency->xpath("name[@lang='{$locale}']"); if (count($nodes) > 0) { return (string) $nodes[0]; } //next, see if we have a name for the language part of the locale $lang = \locale_get_primary_language($locale()); $nodes = $currency->xpath("name[@lang='{$lang}']"); if (count($nodes) > 0) { return (string) $nodes[0]; } //else default to using 'en' $nodes = $currency->xpath("name[@lang='en']"); return (string) $nodes[0]; }
Find closest matching name for a currency based on currently set locale. Default to 'en' entry if none more suitable found @param \SimpleXMLElement $currency @return string
https://github.com/chippyash/Currency/blob/d2c6a3da2d1443818b98206ec2cb8f34c2a3be84/src/Chippyash/Currency/Factory.php#L148-L167
gplcart/file_manager
handlers/commands/Command.php
Command.getTotal
protected function getTotal($directory, array $options = array()) { $options['count'] = true; return (int) $this->scanner->scan($directory, $options); }
php
protected function getTotal($directory, array $options = array()) { $options['count'] = true; return (int) $this->scanner->scan($directory, $options); }
Returns a total number of scanned files @param string $directory @param array $options @return integer
https://github.com/gplcart/file_manager/blob/45424e93eafea75d31af6410ac9cf110f08e500a/handlers/commands/Command.php#L59-L63
gplcart/file_manager
handlers/commands/Command.php
Command.getRelativePath
protected function getRelativePath($path = null) { if (!isset($path)) { $path = $this->scanner->getInitialPath(true); } return gplcart_path_normalize(gplcart_path_relative($path)); }
php
protected function getRelativePath($path = null) { if (!isset($path)) { $path = $this->scanner->getInitialPath(true); } return gplcart_path_normalize(gplcart_path_relative($path)); }
Returns a relative file path or initial directory @param null|string $path @return string
https://github.com/gplcart/file_manager/blob/45424e93eafea75d31af6410ac9cf110f08e500a/handlers/commands/Command.php#L91-L98
gplcart/file_manager
handlers/commands/Command.php
Command.move
protected function move($src, $dest, &$errors = 0, &$success = 0) { $this->copy($src, $dest, $errors, $success); if (empty($errors)) { gplcart_file_delete_recursive($src, $errors); } return empty($errors); }
php
protected function move($src, $dest, &$errors = 0, &$success = 0) { $this->copy($src, $dest, $errors, $success); if (empty($errors)) { gplcart_file_delete_recursive($src, $errors); } return empty($errors); }
Moves a file to a new destination @param string $src @param string $dest @param int $errors @param int $success @return bool
https://github.com/gplcart/file_manager/blob/45424e93eafea75d31af6410ac9cf110f08e500a/handlers/commands/Command.php#L118-L127
gplcart/file_manager
handlers/commands/Command.php
Command.copy
protected function copy($src, $dest, &$errors = 0, &$success = 0) { if (is_file($src)) { if (copy($src, $dest)) { $success++; return true; } $errors++; return false; } if (!is_dir($dest) && !mkdir($dest)) { $errors++; return false; } foreach (new DirectoryIterator($src) as $file) { $result = null; $copyto = "$dest/" . $file->getBasename(); if ($file->isFile() || (!$file->isDot() && $file->isDir())) { $result = $this->copy($file->getRealPath(), $copyto, $errors, $success); } if (!isset($result)) { continue; } if ($result) { $success++; } else { $errors++; } } $success++; return true; }
php
protected function copy($src, $dest, &$errors = 0, &$success = 0) { if (is_file($src)) { if (copy($src, $dest)) { $success++; return true; } $errors++; return false; } if (!is_dir($dest) && !mkdir($dest)) { $errors++; return false; } foreach (new DirectoryIterator($src) as $file) { $result = null; $copyto = "$dest/" . $file->getBasename(); if ($file->isFile() || (!$file->isDot() && $file->isDir())) { $result = $this->copy($file->getRealPath(), $copyto, $errors, $success); } if (!isset($result)) { continue; } if ($result) { $success++; } else { $errors++; } } $success++; return true; }
Copy a file / directory @param string $src @param string $dest @param int $errors @param int $success @return boolean
https://github.com/gplcart/file_manager/blob/45424e93eafea75d31af6410ac9cf110f08e500a/handlers/commands/Command.php#L137-L177
gplcart/file_manager
handlers/commands/Command.php
Command.isInitialPath
protected function isInitialPath($file) { $current_path = gplcart_path_normalize($file->getRealPath()); $initial_path = gplcart_path_normalize($this->scanner->getInitialPath(true)); return $current_path === $initial_path; }
php
protected function isInitialPath($file) { $current_path = gplcart_path_normalize($file->getRealPath()); $initial_path = gplcart_path_normalize($this->scanner->getInitialPath(true)); return $current_path === $initial_path; }
Whether the current file is the initial file manager path @param \SplFileInfo $file @return bool
https://github.com/gplcart/file_manager/blob/45424e93eafea75d31af6410ac9cf110f08e500a/handlers/commands/Command.php#L184-L190
brainexe/core
src/Middleware/Authentication.php
Authentication.processRequest
public function processRequest(Request $request, Route $route) { if ($request->attributes->has('user')) { $user = $request->attributes->get('user'); } else { $session = $request->getSession(); $userId = (int)$session->get('user_id'); $user = $this->loadUser($userId); } $request->attributes->set('user', $user); $request->attributes->set('user_id', $user->getId()); $this->checkForRole($route, $user); if ($route->hasDefault('_guest')) { return null; } if (empty($user->getId())) { return $this->handleNotAuthenticatedRequest($request); } return null; }
php
public function processRequest(Request $request, Route $route) { if ($request->attributes->has('user')) { $user = $request->attributes->get('user'); } else { $session = $request->getSession(); $userId = (int)$session->get('user_id'); $user = $this->loadUser($userId); } $request->attributes->set('user', $user); $request->attributes->set('user_id', $user->getId()); $this->checkForRole($route, $user); if ($route->hasDefault('_guest')) { return null; } if (empty($user->getId())) { return $this->handleNotAuthenticatedRequest($request); } return null; }
{@inheritdoc}
https://github.com/brainexe/core/blob/9ef69c6f045306abd20e271572386970db9b3e54/src/Middleware/Authentication.php#L42-L67
heliopsis/ezforms-bundle
Heliopsis/eZFormsBundle/FormHandler/MultiplexerHandler.php
MultiplexerHandler.setLocation
public function setLocation( Location $location ) { foreach ( $this->handlers as $handler ) { if ( $handler instanceof LocationAwareHandlerInterface ) { $handler->setLocation( $location ); } } }
php
public function setLocation( Location $location ) { foreach ( $this->handlers as $handler ) { if ( $handler instanceof LocationAwareHandlerInterface ) { $handler->setLocation( $location ); } } }
Passes location to location aware handlers @param \eZ\Publish\API\Repository\Values\Content\Location $location
https://github.com/heliopsis/ezforms-bundle/blob/ed87feeb76fcdcd4a4e355d4bc60b83077ba90b4/Heliopsis/eZFormsBundle/FormHandler/MultiplexerHandler.php#L62-L71
heliopsis/ezforms-bundle
Heliopsis/eZFormsBundle/FormHandler/MultiplexerHandler.php
MultiplexerHandler.setContent
public function setContent( Content $content ) { foreach ( $this->handlers as $handler ) { if ( $handler instanceof ContentAwareHandlerInterface ) { $handler->setContent( $content ); } } }
php
public function setContent( Content $content ) { foreach ( $this->handlers as $handler ) { if ( $handler instanceof ContentAwareHandlerInterface ) { $handler->setContent( $content ); } } }
Passes content to content aware handlers @param \eZ\Publish\API\Repository\Values\Content\Content $content
https://github.com/heliopsis/ezforms-bundle/blob/ed87feeb76fcdcd4a4e355d4bc60b83077ba90b4/Heliopsis/eZFormsBundle/FormHandler/MultiplexerHandler.php#L77-L86
valu-digital/valuso
src/ValuSo/Controller/ServiceController.php
ServiceController.httpAction
public function httpAction() { $status = self::STATUS_SUCCESS; $responses = array(); $exception = null; $data = null; $debug = $this->getRouteParam('debug', false); try { $service = $this->fetchService(); $operation = $service ? $this->fetchOperation() : false; if(!$service){ throw new ServiceNotFoundException("Route doesn't contain service information"); } elseif (!$operation) { throw new OperationNotFoundException("Route doesn't contain operation information"); } try { $params = $this->fetchParams(); } catch(\Exception $e) { $status = self::STATUS_MALFORMED_REQUEST; $exception = $e; } if ($status === self::STATUS_SUCCESS) { if (isset($params[self::HEADER_FORCE_CONTENT_HTML])) { if ($params[self::HEADER_FORCE_CONTENT_HTML]) { $this->getRequest()->getHeaders()->addHeaders([ self::HEADER_FORCE_CONTENT_HTML => true ]); } unset($params[self::HEADER_FORCE_CONTENT_HTML]); } $data = $this->exec( $service, $operation, $params, Command::CONTEXT_HTTP); } } catch (PermissionDeniedException $exception) { $status = self::STATUS_PERMISSION_DENIED; } catch (NotFoundException $exception) { $status = self::STATUS_NOT_FOUND; } catch (ServiceException $exception) { $status = self::STATUS_UNKNOWN_EXCEPTION; } catch (\Exception $exception) { $status = self::STATUS_UNKNOWN_EXCEPTION; } // Log error if ($exception) { error_log($exception->getMessage() . ' (' . $exception->getFile().':'.$exception->getLine().')'); if ($debug) { throw $exception; } } return $this->prepareHttpResponse( $data, $status, $exception); }
php
public function httpAction() { $status = self::STATUS_SUCCESS; $responses = array(); $exception = null; $data = null; $debug = $this->getRouteParam('debug', false); try { $service = $this->fetchService(); $operation = $service ? $this->fetchOperation() : false; if(!$service){ throw new ServiceNotFoundException("Route doesn't contain service information"); } elseif (!$operation) { throw new OperationNotFoundException("Route doesn't contain operation information"); } try { $params = $this->fetchParams(); } catch(\Exception $e) { $status = self::STATUS_MALFORMED_REQUEST; $exception = $e; } if ($status === self::STATUS_SUCCESS) { if (isset($params[self::HEADER_FORCE_CONTENT_HTML])) { if ($params[self::HEADER_FORCE_CONTENT_HTML]) { $this->getRequest()->getHeaders()->addHeaders([ self::HEADER_FORCE_CONTENT_HTML => true ]); } unset($params[self::HEADER_FORCE_CONTENT_HTML]); } $data = $this->exec( $service, $operation, $params, Command::CONTEXT_HTTP); } } catch (PermissionDeniedException $exception) { $status = self::STATUS_PERMISSION_DENIED; } catch (NotFoundException $exception) { $status = self::STATUS_NOT_FOUND; } catch (ServiceException $exception) { $status = self::STATUS_UNKNOWN_EXCEPTION; } catch (\Exception $exception) { $status = self::STATUS_UNKNOWN_EXCEPTION; } // Log error if ($exception) { error_log($exception->getMessage() . ' (' . $exception->getFile().':'.$exception->getLine().')'); if ($debug) { throw $exception; } } return $this->prepareHttpResponse( $data, $status, $exception); }
Performs service operation matched by HTTP router @throws \Exception @return Response
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Controller/ServiceController.php#L184-L250
valu-digital/valuso
src/ValuSo/Controller/ServiceController.php
ServiceController.consoleAction
public function consoleAction() { $request = $this->getRequest(); $service = $this->fetchService(); $operation = $this->fetchOperation(); $query = $this->fetchConsoleQuery(); if (!$request instanceof ConsoleRequest) { throw new \RuntimeException('You can only use this action from a console!'); } // Check flags $verbose = $request->getParam('verbose') || $request->getParam('v'); $silent = $request->getParam('silent') || $request->getParam('s'); $params = Json::decode( $query, Json::TYPE_ARRAY ); try { $data = $this->exec($service, $operation, $params, Command::CONTEXT_CLI); return $this->prepareConsoleResponse($data, null, $verbose, $silent); } catch (\Exception $exception) { error_log($exception->getMessage() . ' (' . $exception->getFile().':'.$exception->getLine().')'); return $this->prepareConsoleResponse(null, $exception, $verbose, $silent); } }
php
public function consoleAction() { $request = $this->getRequest(); $service = $this->fetchService(); $operation = $this->fetchOperation(); $query = $this->fetchConsoleQuery(); if (!$request instanceof ConsoleRequest) { throw new \RuntimeException('You can only use this action from a console!'); } // Check flags $verbose = $request->getParam('verbose') || $request->getParam('v'); $silent = $request->getParam('silent') || $request->getParam('s'); $params = Json::decode( $query, Json::TYPE_ARRAY ); try { $data = $this->exec($service, $operation, $params, Command::CONTEXT_CLI); return $this->prepareConsoleResponse($data, null, $verbose, $silent); } catch (\Exception $exception) { error_log($exception->getMessage() . ' (' . $exception->getFile().':'.$exception->getLine().')'); return $this->prepareConsoleResponse(null, $exception, $verbose, $silent); } }
Performs service operation routed by console router
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Controller/ServiceController.php#L255-L283
valu-digital/valuso
src/ValuSo/Controller/ServiceController.php
ServiceController.exec
protected function exec($service, $operation, $params, $context) { // Perform operation and fetch first result return $this->serviceBroker() ->service($service) ->context($context) ->until(array($this, '_break')) ->exec($operation, $params) ->first(); }
php
protected function exec($service, $operation, $params, $context) { // Perform operation and fetch first result return $this->serviceBroker() ->service($service) ->context($context) ->until(array($this, '_break')) ->exec($operation, $params) ->first(); }
Execute operation @param string $service @param string $operation @param array|null $params @param string $context
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Controller/ServiceController.php#L293-L302
valu-digital/valuso
src/ValuSo/Controller/ServiceController.php
ServiceController.prepareHttpResponse
protected function prepareHttpResponse($data, $status, $exception = null) { $error = $this->getRequest()->getHeader( self::HEADER_ERRORS, self::HEADER_ERRORS_DEFAULT); $forceHtmlContentType = $this->getRequest()->getHeader( self::HEADER_FORCE_CONTENT_HTML, false); if ($error instanceof HeaderInterface) { $error = $error->getFieldValue(); } $response = $this->getResponse(); $headers = array( 'Cache-Control' => 'no-cache, must-revalidate', 'Pragma' => 'no-cache', 'Expires' => '2000-01-01 00:00:00', 'Content-Type' => 'application/json', ); if ($forceHtmlContentType) { $headers['Content-Type'] = 'text/html'; } $response->getHeaders()->addHeaders($headers); // update response status code $response->setStatusCode( $status ); // update reason phrase if($exception){ if ($exception instanceof ServiceException) { $message = $exception->getMessage(); } else { $message = 'Unknown exception'; } $response->setReasonPhrase( $message ); } if ($data instanceof \Zend\Http\Response) { // Attach custom stream response sender listener // to send the stream to output buffer in chunks if ($data instanceof Stream) { $sendReponseListener = $this->getServiceLocator()->get('SendResponseListener'); $sendReponseListener->getEventManager()->attach( SendResponseEvent::EVENT_SEND_RESPONSE, new StreamResponseSender(), 10000); } return $data; } else { $responseModel = array( 'd' => $data ); // Append exception data if ($exception) { if ($error == self::HEADER_ERRORS_VERBOSE && $exception instanceof ServiceException) { $responseModel['e'] = array( 'm' => $exception->getRawMessage(), 'c' => $exception->getCode(), 'a' => $exception->getVars() ); } else { $responseModel['e'] = array( 'm' => $response->getReasonPhrase(), 'c' => $exception->getCode(), ); } } try { $response->setContent(JsonEncoder::encode($responseModel, true)); } catch (Exception $e) { if ($e instanceof RecursionException) { $message = self::CYCLIC_DATA_ERROR; } else { $message = $e->getMessage(); } $response->setReasonPhrase( $message ); $response->setStatusCode( self::STATUS_UNKNOWN_EXCEPTION ); $response->setContent(JsonEncoder::encode([ 'd' => null, 'e' => [ 'm' => $message, 'c' => $e->getCode() ] ], true)); } return $response; } }
php
protected function prepareHttpResponse($data, $status, $exception = null) { $error = $this->getRequest()->getHeader( self::HEADER_ERRORS, self::HEADER_ERRORS_DEFAULT); $forceHtmlContentType = $this->getRequest()->getHeader( self::HEADER_FORCE_CONTENT_HTML, false); if ($error instanceof HeaderInterface) { $error = $error->getFieldValue(); } $response = $this->getResponse(); $headers = array( 'Cache-Control' => 'no-cache, must-revalidate', 'Pragma' => 'no-cache', 'Expires' => '2000-01-01 00:00:00', 'Content-Type' => 'application/json', ); if ($forceHtmlContentType) { $headers['Content-Type'] = 'text/html'; } $response->getHeaders()->addHeaders($headers); // update response status code $response->setStatusCode( $status ); // update reason phrase if($exception){ if ($exception instanceof ServiceException) { $message = $exception->getMessage(); } else { $message = 'Unknown exception'; } $response->setReasonPhrase( $message ); } if ($data instanceof \Zend\Http\Response) { // Attach custom stream response sender listener // to send the stream to output buffer in chunks if ($data instanceof Stream) { $sendReponseListener = $this->getServiceLocator()->get('SendResponseListener'); $sendReponseListener->getEventManager()->attach( SendResponseEvent::EVENT_SEND_RESPONSE, new StreamResponseSender(), 10000); } return $data; } else { $responseModel = array( 'd' => $data ); // Append exception data if ($exception) { if ($error == self::HEADER_ERRORS_VERBOSE && $exception instanceof ServiceException) { $responseModel['e'] = array( 'm' => $exception->getRawMessage(), 'c' => $exception->getCode(), 'a' => $exception->getVars() ); } else { $responseModel['e'] = array( 'm' => $response->getReasonPhrase(), 'c' => $exception->getCode(), ); } } try { $response->setContent(JsonEncoder::encode($responseModel, true)); } catch (Exception $e) { if ($e instanceof RecursionException) { $message = self::CYCLIC_DATA_ERROR; } else { $message = $e->getMessage(); } $response->setReasonPhrase( $message ); $response->setStatusCode( self::STATUS_UNKNOWN_EXCEPTION ); $response->setContent(JsonEncoder::encode([ 'd' => null, 'e' => [ 'm' => $message, 'c' => $e->getCode() ] ], true)); } return $response; } }
Prepares HTTP response @param mixed $data @param int $status @param \Exception|null $exception @return Response
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Controller/ServiceController.php#L312-L427
valu-digital/valuso
src/ValuSo/Controller/ServiceController.php
ServiceController.prepareConsoleResponse
protected function prepareConsoleResponse($data, \Exception $exception = null, $verbose = false, $silent = false) { $response = new ConsoleResponse(); try { if (is_array($data) || is_object($data)) { $json = JsonEncoder::encode($data, true); $data = Json::prettyPrint($json) . "\n"; } else if (is_scalar($data)) { $data = (string)$data."\n"; } } catch (Exception $e) { $exception = $e; $data = null; } if ($exception) { if ($verbose) { $msg = $exception->getMessage() . ' (' . $exception->getFile().':'.$exception->getLine() . ')'; } else { $msg = $exception->getMessage(); } if (!$silent) { $response->setContent("Error: " . $msg . "\n"); } $response->setErrorLevel($exception->getCode()); } if (!$silent) { $response->setContent($data); } return $response; }
php
protected function prepareConsoleResponse($data, \Exception $exception = null, $verbose = false, $silent = false) { $response = new ConsoleResponse(); try { if (is_array($data) || is_object($data)) { $json = JsonEncoder::encode($data, true); $data = Json::prettyPrint($json) . "\n"; } else if (is_scalar($data)) { $data = (string)$data."\n"; } } catch (Exception $e) { $exception = $e; $data = null; } if ($exception) { if ($verbose) { $msg = $exception->getMessage() . ' (' . $exception->getFile().':'.$exception->getLine() . ')'; } else { $msg = $exception->getMessage(); } if (!$silent) { $response->setContent("Error: " . $msg . "\n"); } $response->setErrorLevel($exception->getCode()); } if (!$silent) { $response->setContent($data); } return $response; }
Prepares console response @param mixed $data @param \Exception|null $exception @param boolean $verbose @param boolean $silent @return ConsoleResponse
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Controller/ServiceController.php#L438-L474
valu-digital/valuso
src/ValuSo/Controller/ServiceController.php
ServiceController.fetchService
protected function fetchService() { $service = $this->getRouteParam('service'); $service = $this->parseCanonicalName($service, true); if (preg_match($this->servicePattern, $service)) { return $service; } else { return false; } }
php
protected function fetchService() { $service = $this->getRouteParam('service'); $service = $this->parseCanonicalName($service, true); if (preg_match($this->servicePattern, $service)) { return $service; } else { return false; } }
Parse service name from request @return string|boolean
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Controller/ServiceController.php#L481-L491
valu-digital/valuso
src/ValuSo/Controller/ServiceController.php
ServiceController.fetchOperation
protected function fetchOperation() { $operation = $this->getRouteParam('operation'); if ($operation !== null) { $operation = $this->parseCanonicalName($operation); if (preg_match($this->operationPattern, $operation)) { return $operation; } else { return false; } } else { $operation = $this->getRequest()->getHeader(self::HEADER_OPERATION); if (!$operation) { $operation = 'http-'.$this->getRequest()->getMethod(); } else { $operation = $operation->getFieldValue(); } return $this->parseCanonicalName($operation); } }
php
protected function fetchOperation() { $operation = $this->getRouteParam('operation'); if ($operation !== null) { $operation = $this->parseCanonicalName($operation); if (preg_match($this->operationPattern, $operation)) { return $operation; } else { return false; } } else { $operation = $this->getRequest()->getHeader(self::HEADER_OPERATION); if (!$operation) { $operation = 'http-'.$this->getRequest()->getMethod(); } else { $operation = $operation->getFieldValue(); } return $this->parseCanonicalName($operation); } }
Parse operation name from request @return string|boolean
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Controller/ServiceController.php#L498-L521
valu-digital/valuso
src/ValuSo/Controller/ServiceController.php
ServiceController.fetchParams
protected function fetchParams() { $contentType = $this->getRequest()->getHeaders()->get('Content-Type'); if ($contentType) { $contentTypeParts = explode(';', $contentType->getFieldValue()); $contentType = strtolower(trim($contentTypeParts[0])); } if ($contentType === 'application/json') { $json = $this->getRequest()->getContent(); $params = JsonDecoder::decode($json, JSON::TYPE_ARRAY); } else { // Parse parameters if ($this->getRequest()->isPost()) { $params = $this->getRequest() ->getPost() ->toArray(); $params = array_merge( $params, $this->getRequest() ->getFiles() ->toArray() ); } else { $params = $this->getRequest() ->getQuery() ->toArray(); } } // Use special 'q' parameters instead, if specified if (isset($params['q'])) { $params = Json::decode($params['q'], Json::TYPE_ARRAY); // Files are an exception, as they cannot be passed as part of // the special q parameter foreach ($this->getRequest()->getFiles() as $name => $value) { if (!isset($params[$name])) { $params[$name] = $value; } } } else { // Use route param 'path' and parse its parameters $paramsInRoute = $this->getRouteParam('path'); if ($paramsInRoute && $paramsInRoute !== '/') { $paramsInRoute = explode('/', $paramsInRoute); array_shift($paramsInRoute); $params = array_merge( $params, $paramsInRoute); } } return $params; }
php
protected function fetchParams() { $contentType = $this->getRequest()->getHeaders()->get('Content-Type'); if ($contentType) { $contentTypeParts = explode(';', $contentType->getFieldValue()); $contentType = strtolower(trim($contentTypeParts[0])); } if ($contentType === 'application/json') { $json = $this->getRequest()->getContent(); $params = JsonDecoder::decode($json, JSON::TYPE_ARRAY); } else { // Parse parameters if ($this->getRequest()->isPost()) { $params = $this->getRequest() ->getPost() ->toArray(); $params = array_merge( $params, $this->getRequest() ->getFiles() ->toArray() ); } else { $params = $this->getRequest() ->getQuery() ->toArray(); } } // Use special 'q' parameters instead, if specified if (isset($params['q'])) { $params = Json::decode($params['q'], Json::TYPE_ARRAY); // Files are an exception, as they cannot be passed as part of // the special q parameter foreach ($this->getRequest()->getFiles() as $name => $value) { if (!isset($params[$name])) { $params[$name] = $value; } } } else { // Use route param 'path' and parse its parameters $paramsInRoute = $this->getRouteParam('path'); if ($paramsInRoute && $paramsInRoute !== '/') { $paramsInRoute = explode('/', $paramsInRoute); array_shift($paramsInRoute); $params = array_merge( $params, $paramsInRoute); } } return $params; }
Parse parameters from request @return array
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Controller/ServiceController.php#L528-L585
valu-digital/valuso
src/ValuSo/Controller/ServiceController.php
ServiceController.parseCanonicalName
protected function parseCanonicalName($name, $toUcc = false) { $array = explode('-', $name); if (sizeof($array) > 1) { $array = array_map('strtolower', $array); } $array = array_map('ucfirst', $array); $canonical = implode('', $array); return ! $toUcc ? lcfirst($canonical) : $canonical; }
php
protected function parseCanonicalName($name, $toUcc = false) { $array = explode('-', $name); if (sizeof($array) > 1) { $array = array_map('strtolower', $array); } $array = array_map('ucfirst', $array); $canonical = implode('', $array); return ! $toUcc ? lcfirst($canonical) : $canonical; }
Parse canonical service/operation name @param string $name @param boolean $toUcc @return string
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Controller/ServiceController.php#L612-L625
ghousseyn/phiber
library/tools.php
tools.wtf
public static function wtf($var, $arrayOfObjectsToHide = array(), $fontSize = 12) { $text = print_r($var, true); $text = str_replace('<', '&lt;', $text); $text = str_replace('>', '&gt;', $text); if ($var instanceof \ErrorException || $var instanceof \Exception) { $text = $var->getMessage() . PHP_EOL; $text .= PHP_EOL . 'Code: ' . $var->getCode() . ' File: ' . $var->getFile() . ':' . $var->getLine() . PHP_EOL; $trace = $var->getTrace(); $first = array_shift($trace); $text .= PHP_EOL . 'Vars:' . PHP_EOL . PHP_EOL; if (isset($first['args'][4])) { foreach ($first['args'][4] as $var => $value) { if (is_object($value)) { $value = 'Instance of ' . get_class($value); } else { $value = print_r($value, true); } $text .= " $$var = $value" . PHP_EOL; } } $text .= PHP_EOL . 'Trace:' . PHP_EOL; foreach ($trace as $step => $data) { $class = ''; if (isset($data["class"])) { $class = $data["class"] . '->'; } $line = (isset($data["line"])) ? $data["line"] : ''; $file = (isset($data["file"])) ? $data["file"] . ':' : ''; $fn = (isset($data["function"])) ? $data["function"] . '() ' : ''; $text .= PHP_EOL . $step . '. ' . $class . $fn . $file . $line . PHP_EOL; if (isset($data['args']) && count($data['args'])) { $text .= PHP_EOL . ' Vars:' . PHP_EOL; foreach ($data['args'] as $arg => $val) { $text .= print_r($val, true) . PHP_EOL; } } unset($class); } $text = preg_replace('#(Code|File|Trace|Vars):\s#', '<span style="color: #079700;font-weight:bold;">$1:</span>', $text); $text = preg_replace('#(Debug|Info|Notice):\s#', '<span style="color: #079700;">$1:</span>', $text); $text = preg_replace('#(Warning|Error|Critical|Alert|Emergency):\s#', '<span style="color: red;">$1:</span>', $text); // color code object properties $pattern = '#\$(\w+)\s=\s(\w+)#'; $replace = '<span style="color: #000099;">$$1</span> = '; $replace .= '<span style="color: #009999;">$2</span>'; $text = preg_replace($pattern, $replace, $text); } else { foreach ($arrayOfObjectsToHide as $objectName) { $searchPattern = '#(\W' . $objectName . ' Object\n(\s+)\().*?\n\2\)\n#s'; $replace = "$1<span style=\"color: #FF9900;\">"; $replace .= "--&gt; HIDDEN - courtesy of wtf() &lt;--</span>)"; $text = preg_replace($searchPattern, $replace, $text); } // color code objects $text = preg_replace('#(\w+)(\s+Object\s+\()#s', '<span style="color: #079700;">$1</span>$2', $text); // color code object properties $pattern = '#\[(\w+)\:(public|private|protected)\]#'; $replace = '[<span style="color: #000099;">$1</span>:'; $replace .= '<span style="color: #009999;">$2</span>]'; $text = preg_replace($pattern, $replace, $text); } echo '<pre style="font-size: ' . $fontSize . 'px; line-height: ' . $fontSize . 'px;background-color: #fff; padding: 10px;">' . $text . '</pre>'; }
php
public static function wtf($var, $arrayOfObjectsToHide = array(), $fontSize = 12) { $text = print_r($var, true); $text = str_replace('<', '&lt;', $text); $text = str_replace('>', '&gt;', $text); if ($var instanceof \ErrorException || $var instanceof \Exception) { $text = $var->getMessage() . PHP_EOL; $text .= PHP_EOL . 'Code: ' . $var->getCode() . ' File: ' . $var->getFile() . ':' . $var->getLine() . PHP_EOL; $trace = $var->getTrace(); $first = array_shift($trace); $text .= PHP_EOL . 'Vars:' . PHP_EOL . PHP_EOL; if (isset($first['args'][4])) { foreach ($first['args'][4] as $var => $value) { if (is_object($value)) { $value = 'Instance of ' . get_class($value); } else { $value = print_r($value, true); } $text .= " $$var = $value" . PHP_EOL; } } $text .= PHP_EOL . 'Trace:' . PHP_EOL; foreach ($trace as $step => $data) { $class = ''; if (isset($data["class"])) { $class = $data["class"] . '->'; } $line = (isset($data["line"])) ? $data["line"] : ''; $file = (isset($data["file"])) ? $data["file"] . ':' : ''; $fn = (isset($data["function"])) ? $data["function"] . '() ' : ''; $text .= PHP_EOL . $step . '. ' . $class . $fn . $file . $line . PHP_EOL; if (isset($data['args']) && count($data['args'])) { $text .= PHP_EOL . ' Vars:' . PHP_EOL; foreach ($data['args'] as $arg => $val) { $text .= print_r($val, true) . PHP_EOL; } } unset($class); } $text = preg_replace('#(Code|File|Trace|Vars):\s#', '<span style="color: #079700;font-weight:bold;">$1:</span>', $text); $text = preg_replace('#(Debug|Info|Notice):\s#', '<span style="color: #079700;">$1:</span>', $text); $text = preg_replace('#(Warning|Error|Critical|Alert|Emergency):\s#', '<span style="color: red;">$1:</span>', $text); // color code object properties $pattern = '#\$(\w+)\s=\s(\w+)#'; $replace = '<span style="color: #000099;">$$1</span> = '; $replace .= '<span style="color: #009999;">$2</span>'; $text = preg_replace($pattern, $replace, $text); } else { foreach ($arrayOfObjectsToHide as $objectName) { $searchPattern = '#(\W' . $objectName . ' Object\n(\s+)\().*?\n\2\)\n#s'; $replace = "$1<span style=\"color: #FF9900;\">"; $replace .= "--&gt; HIDDEN - courtesy of wtf() &lt;--</span>)"; $text = preg_replace($searchPattern, $replace, $text); } // color code objects $text = preg_replace('#(\w+)(\s+Object\s+\()#s', '<span style="color: #079700;">$1</span>$2', $text); // color code object properties $pattern = '#\[(\w+)\:(public|private|protected)\]#'; $replace = '[<span style="color: #000099;">$1</span>:'; $replace .= '<span style="color: #009999;">$2</span>]'; $text = preg_replace($pattern, $replace, $text); } echo '<pre style="font-size: ' . $fontSize . 'px; line-height: ' . $fontSize . 'px;background-color: #fff; padding: 10px;">' . $text . '</pre>'; }
/* Thanks to Aaron Fisher http://www.aaron-fisher.com/articles/web/php/wtf/
https://github.com/ghousseyn/phiber/blob/2574249d49b6930a0123a310a32073a105cdd486/library/tools.php#L63-L133
krakphp/cargo
src/Container/AutoWireContainer.php
AutoWireContainer.get
public function get($id, Cargo\Container $container = null) { if ($this->container->has($id) || !class_exists($id)) { return $this->container->get($id, $container ?: $this); } $this->add($id, null); return $this->get($id, $container); }
php
public function get($id, Cargo\Container $container = null) { if ($this->container->has($id) || !class_exists($id)) { return $this->container->get($id, $container ?: $this); } $this->add($id, null); return $this->get($id, $container); }
fetch from container, or if the service is a class name, we'll try to resolve it automatically
https://github.com/krakphp/cargo/blob/ed5ee24dfe4112b33f0fdcf7131d82a2bf96d191/src/Container/AutoWireContainer.php#L19-L26
phpalchemy/phpalchemy
Alchemy/Component/WebAssets/Bundle.php
Bundle.register
public function register() { $numArgs = func_get_args(); if ($numArgs === 0) { throw new \RuntimeException("Assets Bundle Error: Register error, missing params."); } $args = func_get_args(); $params = array(); if (count($args) === 1) { if (strpos($args[0], ':') === false) { $args[0] = 'file:' . $args[0]; } } foreach ($args as $i => $arg) { if (strpos($args[0], ':') === false) { throw new \RuntimeException(sprintf( "Assets Bundle Error: Invalid param, multiple params must be " . "prefixed for a valid key (file|filter|import). %s", print_r($args, true) )); } list($key, $value) = explode(':', $arg); $params[trim($key)] = trim($value); if (! in_array($key, array('file', 'filter', 'import'))) { throw new \RuntimeException(sprintf( "Assets Bundle Error: Invalid key '%s', valid keys are: (%s).", $key, 'file|filter|import' )); } } if (! array_key_exists('file', $params)) { throw new \RuntimeException("Assets Bundle Error: asset file name param is missing."); } if (array_key_exists('filter', $params) && ! ($params['filter'] instanceof FilterInterface)) { throw new \RuntimeException("Assets Bundle Error: Invalid Filter, it must implement FilterInterface."); } else { $params['filter'] = null; } if (array_key_exists('import', $params)) { // do import if (strpos($params['import'], '->') !== false) { list($source, $target) = explode('->', $params['import']); $source = trim($source); $target = trim($target); } else { $source = $params['import']; $target = ''; } $this->import($source, $target); } // add asset $this->add($params['file'], $params['filter']); }
php
public function register() { $numArgs = func_get_args(); if ($numArgs === 0) { throw new \RuntimeException("Assets Bundle Error: Register error, missing params."); } $args = func_get_args(); $params = array(); if (count($args) === 1) { if (strpos($args[0], ':') === false) { $args[0] = 'file:' . $args[0]; } } foreach ($args as $i => $arg) { if (strpos($args[0], ':') === false) { throw new \RuntimeException(sprintf( "Assets Bundle Error: Invalid param, multiple params must be " . "prefixed for a valid key (file|filter|import). %s", print_r($args, true) )); } list($key, $value) = explode(':', $arg); $params[trim($key)] = trim($value); if (! in_array($key, array('file', 'filter', 'import'))) { throw new \RuntimeException(sprintf( "Assets Bundle Error: Invalid key '%s', valid keys are: (%s).", $key, 'file|filter|import' )); } } if (! array_key_exists('file', $params)) { throw new \RuntimeException("Assets Bundle Error: asset file name param is missing."); } if (array_key_exists('filter', $params) && ! ($params['filter'] instanceof FilterInterface)) { throw new \RuntimeException("Assets Bundle Error: Invalid Filter, it must implement FilterInterface."); } else { $params['filter'] = null; } if (array_key_exists('import', $params)) { // do import if (strpos($params['import'], '->') !== false) { list($source, $target) = explode('->', $params['import']); $source = trim($source); $target = trim($target); } else { $source = $params['import']; $target = ''; } $this->import($source, $target); } // add asset $this->add($params['file'], $params['filter']); }
This method adds a asset and import a asset library is was requested @param mutable some params can be passed with some valid prefixes like file:some_file, filter:some_filter_name and import:some_import_dir_or_pattern, the order of params doesn't matter example: $this->register('file:css/bootstrap.css', 'import:twitter/bootstrap/*') $this->register('import:twitter/jquery/*.js', 'file:css/bootstrap.css')
https://github.com/phpalchemy/phpalchemy/blob/5b7e9b13acfda38c61b2da2639e8a56f298dc32e/Alchemy/Component/WebAssets/Bundle.php#L144-L205
4devs/serializer
Normalizer/ObjectNormalizer.php
ObjectNormalizer.setSerializer
public function setSerializer(SerializerInterface $serializer) { if ($serializer instanceof DenormalizerInterface) { $this->denormalizer = $serializer; } if ($serializer instanceof NormalizerInterface) { $this->normalizer = $serializer; } return $this; }
php
public function setSerializer(SerializerInterface $serializer) { if ($serializer instanceof DenormalizerInterface) { $this->denormalizer = $serializer; } if ($serializer instanceof NormalizerInterface) { $this->normalizer = $serializer; } return $this; }
{@inheritdoc}
https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Normalizer/ObjectNormalizer.php#L71-L81
4devs/serializer
Normalizer/ObjectNormalizer.php
ObjectNormalizer.denormalize
public function denormalize($data, $class, $format = null, array $context = []) { $classMetadata = $this->metadataFactory->getMetadataFor($class); $normalizedData = []; $object = $this->instantiateObject($normalizedData, $class, $context); foreach ($classMetadata as $propertyMetadata) { try { $property = $this->propertyFactory->createDenormalizeProperty($propertyMetadata, $context, $this->denormalizer ?: $this); if (isset($data[$property->getName()])) { $value = $property->denormalize($data[$property->getName()]); $property->setValue($object, $value); } } catch (\Exception $e) { $this->log(LogLevel::ERROR, $e->getMessage(), ['property' => $propertyMetadata, 'context' => $context, 'object' => $object, 'format' => $format]); if ($this->strict) { throw $e; } } } return $object; }
php
public function denormalize($data, $class, $format = null, array $context = []) { $classMetadata = $this->metadataFactory->getMetadataFor($class); $normalizedData = []; $object = $this->instantiateObject($normalizedData, $class, $context); foreach ($classMetadata as $propertyMetadata) { try { $property = $this->propertyFactory->createDenormalizeProperty($propertyMetadata, $context, $this->denormalizer ?: $this); if (isset($data[$property->getName()])) { $value = $property->denormalize($data[$property->getName()]); $property->setValue($object, $value); } } catch (\Exception $e) { $this->log(LogLevel::ERROR, $e->getMessage(), ['property' => $propertyMetadata, 'context' => $context, 'object' => $object, 'format' => $format]); if ($this->strict) { throw $e; } } } return $object; }
{@inheritdoc}
https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Normalizer/ObjectNormalizer.php#L86-L107
4devs/serializer
Normalizer/ObjectNormalizer.php
ObjectNormalizer.supportsDenormalization
public function supportsDenormalization($data, $type, $format = null) { return class_exists($type) && $this->metadataFactory->hasMetadataFor($type); }
php
public function supportsDenormalization($data, $type, $format = null) { return class_exists($type) && $this->metadataFactory->hasMetadataFor($type); }
{@inheritdoc}
https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Normalizer/ObjectNormalizer.php#L112-L115
4devs/serializer
Normalizer/ObjectNormalizer.php
ObjectNormalizer.normalize
public function normalize($object, $format = null, array $context = []) { $classMetadata = $this->metadataFactory->getMetadataFor($object); $data = []; foreach ($classMetadata as $propertyMetadata) { try { $property = $this->propertyFactory->createNormalizeProperty($propertyMetadata, $context, $this->normalizer ?: $this); if ($property->isVisible()) { $value = $property->getValue($object); if ($property->isVisibleValue($value)) { $data[$property->getName()] = $property->normalize($value); } } } catch (\Exception $e) { $this->log(LogLevel::ERROR, $e->getMessage(), ['property' => $propertyMetadata, 'context' => $context, 'object' => $object, 'format' => $format]); if ($this->strict) { throw $e; } } } return $data; }
php
public function normalize($object, $format = null, array $context = []) { $classMetadata = $this->metadataFactory->getMetadataFor($object); $data = []; foreach ($classMetadata as $propertyMetadata) { try { $property = $this->propertyFactory->createNormalizeProperty($propertyMetadata, $context, $this->normalizer ?: $this); if ($property->isVisible()) { $value = $property->getValue($object); if ($property->isVisibleValue($value)) { $data[$property->getName()] = $property->normalize($value); } } } catch (\Exception $e) { $this->log(LogLevel::ERROR, $e->getMessage(), ['property' => $propertyMetadata, 'context' => $context, 'object' => $object, 'format' => $format]); if ($this->strict) { throw $e; } } } return $data; }
{@inheritdoc}
https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Normalizer/ObjectNormalizer.php#L120-L142
4devs/serializer
Normalizer/ObjectNormalizer.php
ObjectNormalizer.supportsNormalization
public function supportsNormalization($data, $format = null) { return is_object($data) && $this->metadataFactory->hasMetadataFor($data); }
php
public function supportsNormalization($data, $format = null) { return is_object($data) && $this->metadataFactory->hasMetadataFor($data); }
{@inheritdoc}
https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Normalizer/ObjectNormalizer.php#L147-L150
4devs/serializer
Normalizer/ObjectNormalizer.php
ObjectNormalizer.instantiateObject
private function instantiateObject(array &$data, $class, array &$context) { if ( isset($context[AbstractNormalizer::OBJECT_TO_POPULATE]) && is_object($context[AbstractNormalizer::OBJECT_TO_POPULATE]) && $context[AbstractNormalizer::OBJECT_TO_POPULATE] instanceof $class ) { $object = $context[AbstractNormalizer::OBJECT_TO_POPULATE]; unset($context[AbstractNormalizer::OBJECT_TO_POPULATE]); return $object; } $reflectionClass = new \ReflectionClass($class); $constructor = $reflectionClass->getConstructor(); if ($constructor) { $constructorParameters = $constructor->getParameters(); $params = []; foreach ($constructorParameters as $constructorParameter) { $paramName = $constructorParameter->name; if (method_exists($constructorParameter, 'isVariadic') && $constructorParameter->isVariadic()) { if (isset($data[$paramName]) || array_key_exists($paramName, $data)) { if (!is_array($data[$paramName])) { throw new RuntimeException(sprintf('Cannot create an instance of %s from serialized data because the variadic parameter %s can only accept an array.', $class, $constructorParameter->name)); } $params = array_merge($params, $data[$paramName]); } } elseif (isset($data[$paramName]) || array_key_exists($paramName, $data)) { $params[] = $data[$paramName]; unset($data[$paramName]); } elseif ($constructorParameter->isDefaultValueAvailable()) { $params[] = $constructorParameter->getDefaultValue(); } else { throw new RuntimeException( sprintf( 'Cannot create an instance of %s from serialized data because its constructor requires parameter "%s" to be present.', $class, $constructorParameter->name ) ); } } return $reflectionClass->newInstanceArgs($params); } return new $class(); }
php
private function instantiateObject(array &$data, $class, array &$context) { if ( isset($context[AbstractNormalizer::OBJECT_TO_POPULATE]) && is_object($context[AbstractNormalizer::OBJECT_TO_POPULATE]) && $context[AbstractNormalizer::OBJECT_TO_POPULATE] instanceof $class ) { $object = $context[AbstractNormalizer::OBJECT_TO_POPULATE]; unset($context[AbstractNormalizer::OBJECT_TO_POPULATE]); return $object; } $reflectionClass = new \ReflectionClass($class); $constructor = $reflectionClass->getConstructor(); if ($constructor) { $constructorParameters = $constructor->getParameters(); $params = []; foreach ($constructorParameters as $constructorParameter) { $paramName = $constructorParameter->name; if (method_exists($constructorParameter, 'isVariadic') && $constructorParameter->isVariadic()) { if (isset($data[$paramName]) || array_key_exists($paramName, $data)) { if (!is_array($data[$paramName])) { throw new RuntimeException(sprintf('Cannot create an instance of %s from serialized data because the variadic parameter %s can only accept an array.', $class, $constructorParameter->name)); } $params = array_merge($params, $data[$paramName]); } } elseif (isset($data[$paramName]) || array_key_exists($paramName, $data)) { $params[] = $data[$paramName]; unset($data[$paramName]); } elseif ($constructorParameter->isDefaultValueAvailable()) { $params[] = $constructorParameter->getDefaultValue(); } else { throw new RuntimeException( sprintf( 'Cannot create an instance of %s from serialized data because its constructor requires parameter "%s" to be present.', $class, $constructorParameter->name ) ); } } return $reflectionClass->newInstanceArgs($params); } return new $class(); }
Instantiates an object using constructor parameters when needed. This method also allows to denormalize data into an existing object if it is present in the context with the object_to_populate. This object is removed from the context before being returned to avoid side effects when recursively normalizing an object graph. @param array $data @param string $class @param array $context @throws RuntimeException @return object
https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Normalizer/ObjectNormalizer.php#L180-L229
Rndwiga/laravel-notifications
src/Notifications/ConfirmEmailNotification.php
ConfirmEmailNotification.toMail
public function toMail($notifiable) { $link = route('user.activate', $this->token); return (new MailMessage) ->subject('Activate your Account') ->line('Welcome to ' . config('app.name')) //->action('Notification Action', 'https://laravel.com') ->action('Activation Link', $link) ->line('We hope you will have a good experience'); }
php
public function toMail($notifiable) { $link = route('user.activate', $this->token); return (new MailMessage) ->subject('Activate your Account') ->line('Welcome to ' . config('app.name')) //->action('Notification Action', 'https://laravel.com') ->action('Activation Link', $link) ->line('We hope you will have a good experience'); }
Get the mail representation of the notification. @param mixed $notifiable @return \Illuminate\Notifications\Messages\MailMessage
https://github.com/Rndwiga/laravel-notifications/blob/39f911a2bf651f9e773cc67fb44dc34c12ea60fd/src/Notifications/ConfirmEmailNotification.php#L42-L51
Ekstazi/yii2-crud-actions
src/Bootstrap.php
Bootstrap.bootstrap
public function bootstrap($app) { $i18n = \Yii::$app->i18n; if ( !isset($i18n->translations[Constants::MSG_CATEGORY_NAME]) && !isset($i18n->translations['ekstazi.*']) ) { $i18n->translations[Constants::MSG_CATEGORY_NAME] = [ 'class' => 'yii\i18n\PhpMessageSource', 'sourceLanguage' => 'en-US', 'basePath' => '@ekstazi/crud/messages', 'fileMap' => [ 'ekstazi/crud' => 'crud.php' ] ]; } $di = \Yii::$container; $di->set('ekstazi\crud\actions\CreateAction', [ 'redirectTo' => RedirectTo::byPk(['view']), ]); $di->set('ekstazi\crud\actions\UpdateAction', [ 'redirectTo' => RedirectTo::byPk(['view']), ]); }
php
public function bootstrap($app) { $i18n = \Yii::$app->i18n; if ( !isset($i18n->translations[Constants::MSG_CATEGORY_NAME]) && !isset($i18n->translations['ekstazi.*']) ) { $i18n->translations[Constants::MSG_CATEGORY_NAME] = [ 'class' => 'yii\i18n\PhpMessageSource', 'sourceLanguage' => 'en-US', 'basePath' => '@ekstazi/crud/messages', 'fileMap' => [ 'ekstazi/crud' => 'crud.php' ] ]; } $di = \Yii::$container; $di->set('ekstazi\crud\actions\CreateAction', [ 'redirectTo' => RedirectTo::byPk(['view']), ]); $di->set('ekstazi\crud\actions\UpdateAction', [ 'redirectTo' => RedirectTo::byPk(['view']), ]); }
Bootstrap method to be called during application bootstrap stage. @param Application $app the application currently running
https://github.com/Ekstazi/yii2-crud-actions/blob/38029fcfc1fac662604b3cabc08ec6ccacb94c57/src/Bootstrap.php#L25-L48
valu-digital/valuso
src/ValuSo/Broker/ServiceLoader.php
ServiceLoader.setOptions
public function setOptions($options) { if (!is_array($options) && !$options instanceof Traversable) { throw new \InvalidArgumentException(sprintf( 'Expected an array or Traversable; received "%s"', (is_object($options) ? get_class($options) : gettype($options)) )); } foreach ($options as $key => $value){ $key = strtolower($key); switch ($key) { case 'services': $this->registerServices($value); break; case 'locator': case 'service_locator': $this->setServiceLocator($value); break; case 'service_manager': $this->configureServiceManager($value); break; } } return $this; }
php
public function setOptions($options) { if (!is_array($options) && !$options instanceof Traversable) { throw new \InvalidArgumentException(sprintf( 'Expected an array or Traversable; received "%s"', (is_object($options) ? get_class($options) : gettype($options)) )); } foreach ($options as $key => $value){ $key = strtolower($key); switch ($key) { case 'services': $this->registerServices($value); break; case 'locator': case 'service_locator': $this->setServiceLocator($value); break; case 'service_manager': $this->configureServiceManager($value); break; } } return $this; }
Configure service loader @param array|\Traversable $options @throws \InvalidArgumentException @return \ValuSo\Broker\ServiceLoader
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Broker/ServiceLoader.php#L66-L94
valu-digital/valuso
src/ValuSo/Broker/ServiceLoader.php
ServiceLoader.getCommandManager
public function getCommandManager() { if ($this->commandManager === null) { $this->commandManager = new CommandManager(); $this->commandManager->setServiceLoader($this); } return $this->commandManager; }
php
public function getCommandManager() { if ($this->commandManager === null) { $this->commandManager = new CommandManager(); $this->commandManager->setServiceLoader($this); } return $this->commandManager; }
Retrieve command manager @return \ValuSo\Command\CommandManager
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Broker/ServiceLoader.php#L158-L166
valu-digital/valuso
src/ValuSo/Broker/ServiceLoader.php
ServiceLoader.registerServices
public function registerServices($services) { if (!is_array($services) && !($services instanceof Traversable)) { throw new Exception\InvalidArgumentException(sprintf( 'Expected an array or Traversable; received "%s"', (is_object($services) ? get_class($services) : gettype($services)) )); } foreach($services as $key => $impl){ if (is_string($impl)) { $impl = ['name' => $impl]; } $id = isset($impl['id']) ? $impl['id'] : $key; $name = isset($impl['name']) ? $impl['name'] : null; $service = isset($impl['service']) ? $impl['service'] : null; $factory = isset($impl['factory']) ? $impl['factory'] : null; $options = isset($impl['options']) ? $impl['options'] : null; $priority = isset($impl['priority']) ? $impl['priority'] : 1; if (!$service && isset($impl['class'])) { $service = $impl['class']; } if(is_null($options) && isset($impl['config'])){ $options = $impl['config']; } if(!$name){ throw new Exception\InvalidArgumentException('Service name is not defined for service: '.$id); } $this->registerService($id, $name, $service, $options, $priority); if (array_key_exists('enabled', $impl) && !$impl['enabled']) { $this->disableService($id); } if($factory){ $this->getServicePluginManager()->setFactory( $id, $factory); } } return $this; }
php
public function registerServices($services) { if (!is_array($services) && !($services instanceof Traversable)) { throw new Exception\InvalidArgumentException(sprintf( 'Expected an array or Traversable; received "%s"', (is_object($services) ? get_class($services) : gettype($services)) )); } foreach($services as $key => $impl){ if (is_string($impl)) { $impl = ['name' => $impl]; } $id = isset($impl['id']) ? $impl['id'] : $key; $name = isset($impl['name']) ? $impl['name'] : null; $service = isset($impl['service']) ? $impl['service'] : null; $factory = isset($impl['factory']) ? $impl['factory'] : null; $options = isset($impl['options']) ? $impl['options'] : null; $priority = isset($impl['priority']) ? $impl['priority'] : 1; if (!$service && isset($impl['class'])) { $service = $impl['class']; } if(is_null($options) && isset($impl['config'])){ $options = $impl['config']; } if(!$name){ throw new Exception\InvalidArgumentException('Service name is not defined for service: '.$id); } $this->registerService($id, $name, $service, $options, $priority); if (array_key_exists('enabled', $impl) && !$impl['enabled']) { $this->disableService($id); } if($factory){ $this->getServicePluginManager()->setFactory( $id, $factory); } } return $this; }
Batch register services @param array|\Traversable $services @throws \InvalidArgumentException @return \ValuSo\Broker\ServiceLoader
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Broker/ServiceLoader.php#L175-L223
valu-digital/valuso
src/ValuSo/Broker/ServiceLoader.php
ServiceLoader.registerService
public function registerService($id, $name, $service = null, $options = array(), $priority = 1) { $name = $this->normalizeServiceName($name); $id = $this->normalizeServiceId($id); if (!preg_match($this->validIdPattern, $id)) { throw new Exception\InvalidServiceException(sprintf( "Service ID '%s' is not valid (ID must begin with lower/uppercase letter a-z, followed by one or more letters or digits)", $id)); } if (!preg_match($this->validNamePattern, $name)) { throw new Exception\InvalidServiceException(sprintf( "Service name '%s' is not valid", $name)); } $this->services[$id] = array( 'name' => $name, 'options' => $options, 'priority' => $priority ); // Register as invokable if(is_string($service)){ $this->getServicePluginManager()->setInvokableClass( $id, $service ); } elseif (is_object($service)) { $this->getServicePluginManager()->setService($id, $service); } // Attach to command manager $this->services[$id]['listener'] = $this->getCommandManager()->attach($name, $id, $priority); return $this; }
php
public function registerService($id, $name, $service = null, $options = array(), $priority = 1) { $name = $this->normalizeServiceName($name); $id = $this->normalizeServiceId($id); if (!preg_match($this->validIdPattern, $id)) { throw new Exception\InvalidServiceException(sprintf( "Service ID '%s' is not valid (ID must begin with lower/uppercase letter a-z, followed by one or more letters or digits)", $id)); } if (!preg_match($this->validNamePattern, $name)) { throw new Exception\InvalidServiceException(sprintf( "Service name '%s' is not valid", $name)); } $this->services[$id] = array( 'name' => $name, 'options' => $options, 'priority' => $priority ); // Register as invokable if(is_string($service)){ $this->getServicePluginManager()->setInvokableClass( $id, $service ); } elseif (is_object($service)) { $this->getServicePluginManager()->setService($id, $service); } // Attach to command manager $this->services[$id]['listener'] = $this->getCommandManager()->attach($name, $id, $priority); return $this; }
Register service @param string $id Unique service ID @param string $name Service name @param string|object|null $service Service object or invokable service class name @param array $options @param int $priority @return \ValuSo\Broker\ServiceLoader
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Broker/ServiceLoader.php#L235-L270
valu-digital/valuso
src/ValuSo/Broker/ServiceLoader.php
ServiceLoader.enableService
public function enableService($id) { if(!isset($this->services[$id])){ throw new Exception\ServiceNotFoundException( sprintf('Service ID "%s" does not exist', $id) ); } if (!isset($this->services[$id]['listener'])) { $this->services[$id]['listener'] = $this->getCommandManager()->attach( $this->services[$id]['name'], $id, $this->services[$id]['priority']); return true; } else { return false; } }
php
public function enableService($id) { if(!isset($this->services[$id])){ throw new Exception\ServiceNotFoundException( sprintf('Service ID "%s" does not exist', $id) ); } if (!isset($this->services[$id]['listener'])) { $this->services[$id]['listener'] = $this->getCommandManager()->attach( $this->services[$id]['name'], $id, $this->services[$id]['priority']); return true; } else { return false; } }
Enable service @param string $id @return boolean
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Broker/ServiceLoader.php#L278-L294
valu-digital/valuso
src/ValuSo/Broker/ServiceLoader.php
ServiceLoader.disableService
public function disableService($id) { $id = $this->normalizeServiceId($id); if(!isset($this->services[$id])){ throw new Exception\ServiceNotFoundException( sprintf('Service ID "%s" does not exist', $id) ); } if (isset($this->services[$id]['listener'])) { $return = $this->getCommandManager()->detach($this->services[$id]['listener']); $this->services[$id]['listener'] = null; return $return; } else { return false; } }
php
public function disableService($id) { $id = $this->normalizeServiceId($id); if(!isset($this->services[$id])){ throw new Exception\ServiceNotFoundException( sprintf('Service ID "%s" does not exist', $id) ); } if (isset($this->services[$id]['listener'])) { $return = $this->getCommandManager()->detach($this->services[$id]['listener']); $this->services[$id]['listener'] = null; return $return; } else { return false; } }
Disable service @param string $id @return boolean
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Broker/ServiceLoader.php#L302-L320
valu-digital/valuso
src/ValuSo/Broker/ServiceLoader.php
ServiceLoader.load
public function load($id, $options = null) { $id = $this->normalizeServiceId($id); if(!isset($this->services[$id])){ throw new Exception\ServiceNotFoundException( sprintf('Service ID "%s" does not exist', $id) ); } if($options == null){ $options = $this->services[$id]['options']; } return $this->getServicePluginManager()->get($id, $options, true, true); }
php
public function load($id, $options = null) { $id = $this->normalizeServiceId($id); if(!isset($this->services[$id])){ throw new Exception\ServiceNotFoundException( sprintf('Service ID "%s" does not exist', $id) ); } if($options == null){ $options = $this->services[$id]['options']; } return $this->getServicePluginManager()->get($id, $options, true, true); }
Loads specific service by ID @param string $name Service name @param array $options Options to apply when first initialized @return ServiceInterface
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Broker/ServiceLoader.php#L329-L344
valu-digital/valuso
src/ValuSo/Broker/ServiceLoader.php
ServiceLoader.getServiceOptions
public function getServiceOptions($id) { $id = $this->normalizeServiceId($id); if(!isset($this->services[$id])){ throw new Exception\ServiceNotFoundException( sprintf('Service ID "%s" does not exist', $id) ); } return $this->services[$id]['options']; }
php
public function getServiceOptions($id) { $id = $this->normalizeServiceId($id); if(!isset($this->services[$id])){ throw new Exception\ServiceNotFoundException( sprintf('Service ID "%s" does not exist', $id) ); } return $this->services[$id]['options']; }
Retrieve options for service @param string $id @return array|null @throws Exception\ServiceNotFoundException
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Broker/ServiceLoader.php#L363-L374
valu-digital/valuso
src/ValuSo/Broker/ServiceLoader.php
ServiceLoader.exists
public function exists($name) { $name = $this->normalizeServiceName($name); return $this->getCommandManager()->hasListeners($name); }
php
public function exists($name) { $name = $this->normalizeServiceName($name); return $this->getCommandManager()->hasListeners($name); }
Test if a service exists Any services that are currently disabled, are not taken into account. @param string $name
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Broker/ServiceLoader.php#L404-L408
valu-digital/valuso
src/ValuSo/Broker/ServiceLoader.php
ServiceLoader.getServicePluginManager
public function getServicePluginManager() { if($this->servicePluginManager === null){ $this->servicePluginManager = new ServicePluginManager(); $that = $this; $this->servicePluginManager->addInitializer(function ($instance, $serviceManager) use ($that) { $name = $serviceManager->getCreationInstanceName(); $options = $serviceManager->getCreationInstanceOptions(); /** * Configure service */ if($options !== null && sizeof($options) && $instance instanceof Feature\ConfigurableInterface){ $instance->setConfig($options); } }); } return $this->servicePluginManager; }
php
public function getServicePluginManager() { if($this->servicePluginManager === null){ $this->servicePluginManager = new ServicePluginManager(); $that = $this; $this->servicePluginManager->addInitializer(function ($instance, $serviceManager) use ($that) { $name = $serviceManager->getCreationInstanceName(); $options = $serviceManager->getCreationInstanceOptions(); /** * Configure service */ if($options !== null && sizeof($options) && $instance instanceof Feature\ConfigurableInterface){ $instance->setConfig($options); } }); } return $this->servicePluginManager; }
Retrieve service manager @return \ValuSo\Broker\ServicePluginManager
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Broker/ServiceLoader.php#L415-L438
raideer/tweech-framework
src/Tweech/Command/CommandRegistry.php
CommandRegistry.register
public function register(CommandInterface $command) { /* * Gets the name of the command * @var string */ $name = $command->getCommand(); /* * Check if the command isn't already registered * otherwise throw an exception */ if (array_key_exists($name, $this->commands)) { throw new CommandException("Command with name '$name' already registered"); } /* * Adds the command to the array */ $this->commands[$name] = $command; }
php
public function register(CommandInterface $command) { /* * Gets the name of the command * @var string */ $name = $command->getCommand(); /* * Check if the command isn't already registered * otherwise throw an exception */ if (array_key_exists($name, $this->commands)) { throw new CommandException("Command with name '$name' already registered"); } /* * Adds the command to the array */ $this->commands[$name] = $command; }
Registers a command. @param CommandInterface $command @return void
https://github.com/raideer/tweech-framework/blob/4aeb5fbf78f96baa67cb62ff676867c4fce1f16c/src/Tweech/Command/CommandRegistry.php#L28-L48
raideer/tweech-framework
src/Tweech/Command/CommandRegistry.php
CommandRegistry.getCommandIfExists
public function getCommandIfExists($string) { if (starts_with($string, $this->id)) { foreach ($this->commands as $commandName => $command) { if (starts_with($string, $this->id.$commandName)) { return $command; } } } }
php
public function getCommandIfExists($string) { if (starts_with($string, $this->id)) { foreach ($this->commands as $commandName => $command) { if (starts_with($string, $this->id.$commandName)) { return $command; } } } }
Check if the given string contains a command if so, return the registered command. @param string $string Received Message @return Command Returns the command or null
https://github.com/raideer/tweech-framework/blob/4aeb5fbf78f96baa67cb62ff676867c4fce1f16c/src/Tweech/Command/CommandRegistry.php#L68-L77
jtallant/skimpy-engine
src/Database/Populator.php
Populator.rebuildDatabase
protected function rebuildDatabase() { # 2. Drop the existing database schema $this->schemaTool->dropDatabase(); # 3. Create the new database schema based on (1) $entityMeta = $this->em->getMetadataFactory()->getAllMetadata(); $this->schemaTool->updateSchema($entityMeta); }
php
protected function rebuildDatabase() { # 2. Drop the existing database schema $this->schemaTool->dropDatabase(); # 3. Create the new database schema based on (1) $entityMeta = $this->em->getMetadataFactory()->getAllMetadata(); $this->schemaTool->updateSchema($entityMeta); }
Builds the DB Schema @return void
https://github.com/jtallant/skimpy-engine/blob/2fce5bc16f8745e54fd66a1c291fcea47fc1b4b2/src/Database/Populator.php#L62-L70
internetofvoice/libvoice
src/Alexa/Response/Directives/AudioPlayer/Play.php
Play.setPlayBehavior
public function setPlayBehavior($playBehavior) { if(!in_array($playBehavior, self::PLAY_BEHAVIORS)) { throw new InvalidArgumentException('PlayBehavior must be one of ' . implode(', ', self::PLAY_BEHAVIORS)); } $this->playBehavior = $playBehavior; return $this; }
php
public function setPlayBehavior($playBehavior) { if(!in_array($playBehavior, self::PLAY_BEHAVIORS)) { throw new InvalidArgumentException('PlayBehavior must be one of ' . implode(', ', self::PLAY_BEHAVIORS)); } $this->playBehavior = $playBehavior; return $this; }
@param string $playBehavior @return Play @throws InvalidArgumentException
https://github.com/internetofvoice/libvoice/blob/15dc4420ddd52234c53902752dc0da16b9d4acdf/src/Alexa/Response/Directives/AudioPlayer/Play.php#L52-L60
Tuna-CMS/tuna-bundle
Twig/PathExtension.php
PathExtension.getPath
public function getPath($name) { if (array_key_exists($name, $this->paths)) { return '/' . $this->paths[$name]; } else { throw new \InvalidArgumentException(sprintf('Path "%s" is not defined. Maybe you forgot to add it to tuna_cms_admin.paths config?', $name)); } }
php
public function getPath($name) { if (array_key_exists($name, $this->paths)) { return '/' . $this->paths[$name]; } else { throw new \InvalidArgumentException(sprintf('Path "%s" is not defined. Maybe you forgot to add it to tuna_cms_admin.paths config?', $name)); } }
@param $name @return string
https://github.com/Tuna-CMS/tuna-bundle/blob/1f999de44e14cbe9f992d46f2e5e74ddc117b04c/Twig/PathExtension.php#L37-L44
widoz/template-loader
src/Loader.php
Loader.locateFile
private function locateFile() { // Try to retrieve the theme file path from child or parent for first. // Fallback to Plugin templates path. $filePath = locate_template($this->templatesPath, false, false); // Looking for the file within the plugin if allowed. if (! $filePath) { $filePath = $this->defaultPath; } return $filePath; }
php
private function locateFile() { // Try to retrieve the theme file path from child or parent for first. // Fallback to Plugin templates path. $filePath = locate_template($this->templatesPath, false, false); // Looking for the file within the plugin if allowed. if (! $filePath) { $filePath = $this->defaultPath; } return $filePath; }
Locate template file Locate the file path for the view, hierarchy try to find the file within the child, parent and last within the plugin. @uses locate_template() To locate the view file within the theme (child or parent). @since 2.1.0 @return string The found file path. Empty string if not found.
https://github.com/widoz/template-loader/blob/6fa0f74047505fe7f2f37c76b61f4e2058e22868/src/Loader.php#L222-L234
tokenly/counterparty-sender
src/Tokenly/CounterpartySender/Provider/CounterpartySenderServiceProvider.php
CounterpartySenderServiceProvider.register
public function register() { $this->bindConfig(); $this->app->bind('Nbobtc\Bitcoind\Bitcoind', function($app) { $url_pieces = parse_url(Config::get('counterparty-sender.connection_string')); $rpc_user = Config::get('counterparty-sender.rpc_user'); $rpc_password = Config::get('counterparty-sender.rpc_password'); $connection_string = "{$url_pieces['scheme']}://{$rpc_user}:{$rpc_password}@{$url_pieces['host']}:{$url_pieces['port']}"; $bitcoin_client = new Client($connection_string); $bitcoind = new Bitcoind($bitcoin_client); return $bitcoind; }); $this->app->bind('Tokenly\CounterpartySender\CounterpartySender', function($app) { $xcpd_client = $app->make('Tokenly\XCPDClient\Client'); $bitcoind = $app->make('Nbobtc\Bitcoind\Bitcoind'); $sender = new CounterpartySender($xcpd_client, $bitcoind); return $sender; }); }
php
public function register() { $this->bindConfig(); $this->app->bind('Nbobtc\Bitcoind\Bitcoind', function($app) { $url_pieces = parse_url(Config::get('counterparty-sender.connection_string')); $rpc_user = Config::get('counterparty-sender.rpc_user'); $rpc_password = Config::get('counterparty-sender.rpc_password'); $connection_string = "{$url_pieces['scheme']}://{$rpc_user}:{$rpc_password}@{$url_pieces['host']}:{$url_pieces['port']}"; $bitcoin_client = new Client($connection_string); $bitcoind = new Bitcoind($bitcoin_client); return $bitcoind; }); $this->app->bind('Tokenly\CounterpartySender\CounterpartySender', function($app) { $xcpd_client = $app->make('Tokenly\XCPDClient\Client'); $bitcoind = $app->make('Nbobtc\Bitcoind\Bitcoind'); $sender = new CounterpartySender($xcpd_client, $bitcoind); return $sender; }); }
Register the service provider. @return void
https://github.com/tokenly/counterparty-sender/blob/aad0570f7d23e496cce1b7ea7efe9db071794737/src/Tokenly/CounterpartySender/Provider/CounterpartySenderServiceProvider.php#L27-L50
fxpio/fxp-gluon
Block/Type/PanelCellPrefType.php
PanelCellPrefType.buildView
public function buildView(BlockView $view, BlockInterface $block, array $options) { if (null !== $options['src'] && !$options['disabled']) { BlockUtil::addAttribute($view, 'href', $options['src'], 'control_attr'); } if ($options['disabled'] && isset($view->vars['control_attr']['tabindex'])) { unset($view->vars['control_attr']['tabindex']); } $view->vars = array_replace($view->vars, [ 'disabled' => $options['disabled'], ]); }
php
public function buildView(BlockView $view, BlockInterface $block, array $options) { if (null !== $options['src'] && !$options['disabled']) { BlockUtil::addAttribute($view, 'href', $options['src'], 'control_attr'); } if ($options['disabled'] && isset($view->vars['control_attr']['tabindex'])) { unset($view->vars['control_attr']['tabindex']); } $view->vars = array_replace($view->vars, [ 'disabled' => $options['disabled'], ]); }
{@inheritdoc}
https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Type/PanelCellPrefType.php#L28-L41
mojopollo/laravel-helpers
src/Mojopollo/Helpers/DateTimeHelper.php
DateTimeHelper.daysOfWeek
public function daysOfWeek($daysOfWeek) { // Check for empty, string or no value if (empty($daysOfWeek) || is_string($daysOfWeek) === false || strlen($daysOfWeek) < 3) { // Return with a null parse return null; } // Separate days of the week by comma $daysOfWeek = explode(',', $daysOfWeek); // Allowed values $allowedValues = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']; // Make sure each day of week foreach ($daysOfWeek as $dayOfWeek) { // Is an allowed value if (in_array($dayOfWeek, $allowedValues) === false) { // Otherwise return with a null parse return null; } } // Return days of the week return $daysOfWeek; }
php
public function daysOfWeek($daysOfWeek) { // Check for empty, string or no value if (empty($daysOfWeek) || is_string($daysOfWeek) === false || strlen($daysOfWeek) < 3) { // Return with a null parse return null; } // Separate days of the week by comma $daysOfWeek = explode(',', $daysOfWeek); // Allowed values $allowedValues = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']; // Make sure each day of week foreach ($daysOfWeek as $dayOfWeek) { // Is an allowed value if (in_array($dayOfWeek, $allowedValues) === false) { // Otherwise return with a null parse return null; } } // Return days of the week return $daysOfWeek; }
Parses a string like "mon,tue,wed,thu,fri,sat,sun" into a array @param string $daysOfWeek example: mon,tue,wed,thu,fri,sat,sun mon,wed,fri @return null|array null if there was a parsing error or a array with parsed days of the week
https://github.com/mojopollo/laravel-helpers/blob/0becb5e0f4202a0f489fb5e384c01dacb8f29dc5/src/Mojopollo/Helpers/DateTimeHelper.php#L23-L51
mojopollo/laravel-helpers
src/Mojopollo/Helpers/DateTimeHelper.php
DateTimeHelper.range
public function range($startDate, $endDate, $periodDate, $step = '+1 day', $daysOfWeek = null, $dateFormat = 'Y-m-d H:i:s') { // Date array $dates = []; // Set current and period date $currentDate = strtotime($startDate); $periodDate = strtotime($periodDate); // Set days of week $daysOfWeek = self::daysOfWeek($daysOfWeek); // Get difference between current date and end date $endDateDifference = strtotime($endDate) - $currentDate; // Generate dates while ($currentDate <= $periodDate) { // If this is a days of the week thing if ($daysOfWeek !== null) { // For every day of the week specified foreach ($daysOfWeek as $dayOfWeek) { // Set day of week start time $dayOfWeekStartTime = strtotime("{$dayOfWeek} this week " . date('Y-m-d H:i:s', $currentDate)); // Set day of week end time $dayOfWeekEndTime = strtotime(date('Y-m-d H:i:s', $dayOfWeekStartTime + $endDateDifference)); // Add to our dates array $dates[] = [ 'start' => date($dateFormat, $dayOfWeekStartTime), 'end' => date($dateFormat, $dayOfWeekEndTime), ]; } // Its a daily, monthly thing... } else { // Add to our dates array $dates[] = [ 'start' => date($dateFormat, $currentDate), 'end' => date($dateFormat, $currentDate + $endDateDifference), ]; } // Set current date $currentDate = strtotime($step, $currentDate); } // Return all dates generated return $dates; }
php
public function range($startDate, $endDate, $periodDate, $step = '+1 day', $daysOfWeek = null, $dateFormat = 'Y-m-d H:i:s') { // Date array $dates = []; // Set current and period date $currentDate = strtotime($startDate); $periodDate = strtotime($periodDate); // Set days of week $daysOfWeek = self::daysOfWeek($daysOfWeek); // Get difference between current date and end date $endDateDifference = strtotime($endDate) - $currentDate; // Generate dates while ($currentDate <= $periodDate) { // If this is a days of the week thing if ($daysOfWeek !== null) { // For every day of the week specified foreach ($daysOfWeek as $dayOfWeek) { // Set day of week start time $dayOfWeekStartTime = strtotime("{$dayOfWeek} this week " . date('Y-m-d H:i:s', $currentDate)); // Set day of week end time $dayOfWeekEndTime = strtotime(date('Y-m-d H:i:s', $dayOfWeekStartTime + $endDateDifference)); // Add to our dates array $dates[] = [ 'start' => date($dateFormat, $dayOfWeekStartTime), 'end' => date($dateFormat, $dayOfWeekEndTime), ]; } // Its a daily, monthly thing... } else { // Add to our dates array $dates[] = [ 'start' => date($dateFormat, $currentDate), 'end' => date($dateFormat, $currentDate + $endDateDifference), ]; } // Set current date $currentDate = strtotime($step, $currentDate); } // Return all dates generated return $dates; }
Generates an array of start and endates for a specified period of time (UTC) based on: date_range by [email protected] on SO @see http://stackoverflow.com/questions/4312439/php-return-all-dates-between-two-dates-in-an-array/9225875#9225875 @param string $startDate example: 2015-06-04 08:00:00 @param string $endDate example: ends at 2015-06-04 12:00:00 @param string $periodDate example: keep generating these dates until 2015-08-01 12:00:00 @param string $step example: +2 days in the period, +1 week, +2 week @param string $daysOfWeek example: mon,tues,wed,thu,fri,sat,sun mon,wed,fri @param string $dateFormat example: Y-m-d @return array Final array with collection of start and end dates
https://github.com/mojopollo/laravel-helpers/blob/0becb5e0f4202a0f489fb5e384c01dacb8f29dc5/src/Mojopollo/Helpers/DateTimeHelper.php#L66-L119
webignition/url-resolver
src/Resolver.php
Resolver.resolve
public function resolve(UriInterface $uri): UriInterface { $request = new Request('GET', $uri); $lastRequestUri = $request->getUri(); $requestUri = new Uri(''); try { $response = $this->httpClient->send($request, [ 'on_stats' => function (TransferStats $stats) use (&$requestUri) { if ($stats->hasResponse()) { $requestUri = $stats->getEffectiveUri(); } }, ]); } catch (TooManyRedirectsException $tooManyRedirectsException) { return $requestUri; } catch (BadResponseException $badResponseException) { $response = $badResponseException->getResponse(); } if ($this->followMetaRedirects) { $metaRedirectUri = $this->getMetaRedirectUriFromResponse($response, $lastRequestUri); if (!empty($metaRedirectUri) && !$this->isLastResponseUrl($metaRedirectUri, $lastRequestUri)) { return $this->resolve($metaRedirectUri); } } return $requestUri; }
php
public function resolve(UriInterface $uri): UriInterface { $request = new Request('GET', $uri); $lastRequestUri = $request->getUri(); $requestUri = new Uri(''); try { $response = $this->httpClient->send($request, [ 'on_stats' => function (TransferStats $stats) use (&$requestUri) { if ($stats->hasResponse()) { $requestUri = $stats->getEffectiveUri(); } }, ]); } catch (TooManyRedirectsException $tooManyRedirectsException) { return $requestUri; } catch (BadResponseException $badResponseException) { $response = $badResponseException->getResponse(); } if ($this->followMetaRedirects) { $metaRedirectUri = $this->getMetaRedirectUriFromResponse($response, $lastRequestUri); if (!empty($metaRedirectUri) && !$this->isLastResponseUrl($metaRedirectUri, $lastRequestUri)) { return $this->resolve($metaRedirectUri); } } return $requestUri; }
@param UriInterface $uri @return UriInterface @throws GuzzleException
https://github.com/webignition/url-resolver/blob/f4dea57b645be3a1debf70b9836015449d6a685e/src/Resolver.php#L44-L73
webignition/url-resolver
src/Resolver.php
Resolver.getMetaRedirectUriFromResponse
private function getMetaRedirectUriFromResponse( ResponseInterface $response, UriInterface $lastRequestUri ): ?UriInterface { /* @var WebPage $webPage */ try { $webPage = Webpage::createFromResponse($lastRequestUri, $response); } catch (\Exception $exception) { return null; } $redirectUrl = null; $selector = 'meta[http-equiv=refresh]'; /** @noinspection PhpUnhandledExceptionInspection */ $inspector = new WebPageInspector($webPage); /* @var \DOMElement[] $metaRefreshElements */ $metaRefreshElements = $inspector->querySelectorAll($selector); foreach ($metaRefreshElements as $metaRefreshElement) { if ($metaRefreshElement->hasAttribute('content')) { $contentAttribute = $metaRefreshElement->getAttribute('content'); $urlMarkerPosition = stripos($contentAttribute, 'url='); if ($urlMarkerPosition !== false) { $redirectUrl = substr($contentAttribute, $urlMarkerPosition + strlen('url=')); } } } if (empty($redirectUrl)) { return null; } return AbsoluteUrlDeriver::derive($lastRequestUri, new Uri($redirectUrl)); }
php
private function getMetaRedirectUriFromResponse( ResponseInterface $response, UriInterface $lastRequestUri ): ?UriInterface { /* @var WebPage $webPage */ try { $webPage = Webpage::createFromResponse($lastRequestUri, $response); } catch (\Exception $exception) { return null; } $redirectUrl = null; $selector = 'meta[http-equiv=refresh]'; /** @noinspection PhpUnhandledExceptionInspection */ $inspector = new WebPageInspector($webPage); /* @var \DOMElement[] $metaRefreshElements */ $metaRefreshElements = $inspector->querySelectorAll($selector); foreach ($metaRefreshElements as $metaRefreshElement) { if ($metaRefreshElement->hasAttribute('content')) { $contentAttribute = $metaRefreshElement->getAttribute('content'); $urlMarkerPosition = stripos($contentAttribute, 'url='); if ($urlMarkerPosition !== false) { $redirectUrl = substr($contentAttribute, $urlMarkerPosition + strlen('url=')); } } } if (empty($redirectUrl)) { return null; } return AbsoluteUrlDeriver::derive($lastRequestUri, new Uri($redirectUrl)); }
@param ResponseInterface $response @param UriInterface $lastRequestUri @return UriInterface|null
https://github.com/webignition/url-resolver/blob/f4dea57b645be3a1debf70b9836015449d6a685e/src/Resolver.php#L89-L125
phavour/phavour
Phavour/Runnable/View.php
View.setPackage
public function setPackage($package) { if ($package != $this->package) { $this->layoutLocation = null; } $this->package = $this->treatPackageName($package); }
php
public function setPackage($package) { if ($package != $this->package) { $this->layoutLocation = null; } $this->package = $this->treatPackageName($package); }
Set the package name @param string $package
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Runnable/View.php#L190-L196
phavour/phavour
Phavour/Runnable/View.php
View.get
public function get($name) { if (array_key_exists($name, $this->runnableVariables)) { return $this->runnableVariables[$name]; } return null; }
php
public function get($name) { if (array_key_exists($name, $this->runnableVariables)) { return $this->runnableVariables[$name]; } return null; }
Get a value from the view. (returns null if not set) @param string $name @return string|null
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Runnable/View.php#L319-L325
phavour/phavour
Phavour/Runnable/View.php
View.setLayout
public function setLayout($file) { if (strstr($file, '::')) { $file = explode('::', $file); $package = $file[0]; $file = $file[1]; } else { $package = $this->package; } $this->assignDeclaredLayout($package, $file); }
php
public function setLayout($file) { if (strstr($file, '::')) { $file = explode('::', $file); $package = $file[0]; $file = $file[1]; } else { $package = $this->package; } $this->assignDeclaredLayout($package, $file); }
Set the layout location @param string $file
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Runnable/View.php#L365-L376
phavour/phavour
Phavour/Runnable/View.php
View.render
public function render($methodName = null, $class = null, $package = null) { if (!$this->isEnabled()) { return true; } if (null != $package) { $this->package = $this->treatPackageName($package); } if (null != $class) { $this->class = $class; } if (null != $methodName) { $this->method = $methodName; } $this->currentView = $this->getPathForView(); @ob_start(); @include $this->currentView; $this->viewBody = @ob_get_clean(); if (!empty($this->layoutLocation)) { @ob_start(); @include $this->layoutLocation; $this->viewBody = @ob_get_clean(); } $this->response->setBody($this->viewBody); $this->response->sendResponse(); }
php
public function render($methodName = null, $class = null, $package = null) { if (!$this->isEnabled()) { return true; } if (null != $package) { $this->package = $this->treatPackageName($package); } if (null != $class) { $this->class = $class; } if (null != $methodName) { $this->method = $methodName; } $this->currentView = $this->getPathForView(); @ob_start(); @include $this->currentView; $this->viewBody = @ob_get_clean(); if (!empty($this->layoutLocation)) { @ob_start(); @include $this->layoutLocation; $this->viewBody = @ob_get_clean(); } $this->response->setBody($this->viewBody); $this->response->sendResponse(); }
Render the view @param string $methodName @param string $class @param string $package @return boolean if no view, otherwise sends the response
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Runnable/View.php#L385-L414
phavour/phavour
Phavour/Runnable/View.php
View.assignDeclaredLayout
private function assignDeclaredLayout($package, $file) { $file = lcfirst($file); if (substr(strtolower($file), -6) == '.phtml') { $file = substr($file, 0, -6); } $package = $this->app->getPackage($package); $pathPieces = array($package['package_path'], 'res', 'layout', $file); $path = implode(self::DS, $pathPieces) . '.phtml'; if (file_exists($path)) { $this->layoutLocation = $path; return true; } $e = new LayoutFileNotFoundException('Invalid layout file path, expected: "' . $path . '"'); $e->setAdditionalData('Layout Path Checked: ', $path); throw $e; }
php
private function assignDeclaredLayout($package, $file) { $file = lcfirst($file); if (substr(strtolower($file), -6) == '.phtml') { $file = substr($file, 0, -6); } $package = $this->app->getPackage($package); $pathPieces = array($package['package_path'], 'res', 'layout', $file); $path = implode(self::DS, $pathPieces) . '.phtml'; if (file_exists($path)) { $this->layoutLocation = $path; return true; } $e = new LayoutFileNotFoundException('Invalid layout file path, expected: "' . $path . '"'); $e->setAdditionalData('Layout Path Checked: ', $path); throw $e; }
Assign the path to the layout file @param string $package @param string $file @throws LayoutFileNotFoundException @throws \Phavour\Application\Exception\PackageNotFoundException @return boolean
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Runnable/View.php#L433-L450
phavour/phavour
Phavour/Runnable/View.php
View.getPathForView
private function getPathForView() { $methodName = lcfirst($this->method); $className = lcfirst($this->class); $package = $this->app->getPackage($this->package); $pathPieces = array($package['package_path'], 'res', 'view', $className, $methodName); $path = implode(self::DS, $pathPieces) . '.phtml'; if (file_exists($path)) { return $path; } $e = new ViewFileNotFoundException('Invalid view file path, expected: "' . $path . '"'); $e->setAdditionalData('View Path Checked: ', $path); throw $e; }
php
private function getPathForView() { $methodName = lcfirst($this->method); $className = lcfirst($this->class); $package = $this->app->getPackage($this->package); $pathPieces = array($package['package_path'], 'res', 'view', $className, $methodName); $path = implode(self::DS, $pathPieces) . '.phtml'; if (file_exists($path)) { return $path; } $e = new ViewFileNotFoundException('Invalid view file path, expected: "' . $path . '"'); $e->setAdditionalData('View Path Checked: ', $path); throw $e; }
Get the path for a view file. @throws \Phavour\Application\Exception\PackageNotFoundException @throws ViewFileNotFoundException @return string
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Runnable/View.php#L458-L472
phavour/phavour
Phavour/Runnable/View.php
View.inflate
private function inflate($filePath) { $currentDirectory = rtrim(dirname($this->currentView), self::DS); $currentDirectory .= self::DS; if (substr($filePath, -6, 6) != '.phtml') { $filePath .= '.phtml'; } $searchPath = realpath($currentDirectory . $filePath); if ($searchPath != false && file_exists($searchPath)) { $content = @include $searchPath; if (!$content) { // @codeCoverageIgnoreStart $e = new ViewFileNotFoundException('Unable to inflate file "' . $searchPath . '"'); $e->setAdditionalData('View Path: ', $searchPath); throw $e; // @codeCoverageIgnoreEnd } return; } // @codeCoverageIgnoreStart $e = new ViewFileNotFoundException('Invalid view file path, expected: "' . $currentDirectory . $filePath . '"'); $e->setAdditionalData('View Path Checked: ', $currentDirectory . $filePath); throw $e; // @codeCoverageIgnoreEnd }
php
private function inflate($filePath) { $currentDirectory = rtrim(dirname($this->currentView), self::DS); $currentDirectory .= self::DS; if (substr($filePath, -6, 6) != '.phtml') { $filePath .= '.phtml'; } $searchPath = realpath($currentDirectory . $filePath); if ($searchPath != false && file_exists($searchPath)) { $content = @include $searchPath; if (!$content) { // @codeCoverageIgnoreStart $e = new ViewFileNotFoundException('Unable to inflate file "' . $searchPath . '"'); $e->setAdditionalData('View Path: ', $searchPath); throw $e; // @codeCoverageIgnoreEnd } return; } // @codeCoverageIgnoreStart $e = new ViewFileNotFoundException('Invalid view file path, expected: "' . $currentDirectory . $filePath . '"'); $e->setAdditionalData('View Path Checked: ', $currentDirectory . $filePath); throw $e; // @codeCoverageIgnoreEnd }
Inflate a given @param string $filePath @throws \Phavour\Runnable\View\Exception\ViewFileNotFoundException
https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Runnable/View.php#L479-L505
zbox/UnifiedPush
src/Zbox/UnifiedPush/NotificationService/ServiceCredentialsFactory.php
ServiceCredentialsFactory.getCredentialsByService
public function getCredentialsByService($serviceName) { if (!in_array($serviceName, $this->getInitializedServices())) { throw new DomainException( sprintf("Credentials for service '%s' was not initialized", $serviceName) ); } return $this->serviceCredentials[$serviceName]; }
php
public function getCredentialsByService($serviceName) { if (!in_array($serviceName, $this->getInitializedServices())) { throw new DomainException( sprintf("Credentials for service '%s' was not initialized", $serviceName) ); } return $this->serviceCredentials[$serviceName]; }
Returns credentials for notification service @param string $serviceName @throws DomainException @return CredentialsInterface
https://github.com/zbox/UnifiedPush/blob/47da2d0577b18ac709cd947c68541014001e1866/src/Zbox/UnifiedPush/NotificationService/ServiceCredentialsFactory.php#L76-L85
romaricdrigon/OrchestraBundle
Core/Pool/Factory/RepositoryPoolFactory.php
RepositoryPoolFactory.addRepository
public function addRepository($repositoryClass, $serviceId, $entityClass) { $repositoryDefinition = $this->definitionFactory->build($repositoryClass, $serviceId, $entityClass); // this array is not ordered by slug $this->definitions[] = $repositoryDefinition; }
php
public function addRepository($repositoryClass, $serviceId, $entityClass) { $repositoryDefinition = $this->definitionFactory->build($repositoryClass, $serviceId, $entityClass); // this array is not ordered by slug $this->definitions[] = $repositoryDefinition; }
Add a repository, service from Symfony DIC, to the pool @param string $repositoryClass @param string $serviceId @param string $entityClass
https://github.com/romaricdrigon/OrchestraBundle/blob/4abb9736fcb6b23ed08ebd14ab169867339a4785/Core/Pool/Factory/RepositoryPoolFactory.php#L48-L54
romaricdrigon/OrchestraBundle
Core/Pool/Factory/RepositoryPoolFactory.php
RepositoryPoolFactory.createPool
public function createPool() { $pool = new RepositoryPool(); foreach ($this->definitions as $definition) { $pool->addRepositoryDefinition($definition); } return $pool; }
php
public function createPool() { $pool = new RepositoryPool(); foreach ($this->definitions as $definition) { $pool->addRepositoryDefinition($definition); } return $pool; }
Factory method for the EntityPool @return RepositoryPoolInterface
https://github.com/romaricdrigon/OrchestraBundle/blob/4abb9736fcb6b23ed08ebd14ab169867339a4785/Core/Pool/Factory/RepositoryPoolFactory.php#L61-L70
schpill/thin
src/Prototype.php
Prototype.from
static public function from($class) { if (is_object($class)) { $class = get_class($class); } if (empty(self::$prototypes[$class])) { self::$prototypes[$class] = new static($class); } return self::$prototypes[$class]; }
php
static public function from($class) { if (is_object($class)) { $class = get_class($class); } if (empty(self::$prototypes[$class])) { self::$prototypes[$class] = new static($class); } return self::$prototypes[$class]; }
Returns the prototype associated with the specified class or object. @param string|object $class Class name or instance. @return Prototype
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Prototype.php#L27-L38
schpill/thin
src/Prototype.php
Prototype.getConsolidatedMethods
protected function getConsolidatedMethods() { if ($this->consolidatedMethods !== null) { return $this->consolidatedMethods; } $methods = $this->methods; if ($this->parent) { $methods += $this->parent->getConsolidatedMethods(); } return $this->consolidatedMethods = $methods; }
php
protected function getConsolidatedMethods() { if ($this->consolidatedMethods !== null) { return $this->consolidatedMethods; } $methods = $this->methods; if ($this->parent) { $methods += $this->parent->getConsolidatedMethods(); } return $this->consolidatedMethods = $methods; }
Consolidate the methods of the prototype. The method creates a single array from the prototype methods and those of its parents. @return array[string]callable
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Prototype.php#L110-L123
schpill/thin
src/Prototype.php
Prototype.revokeConsolidatedMethods
protected function revokeConsolidatedMethods() { $class = $this->class; foreach (self::$prototypes as $prototype) { if (!is_subclass_of($prototype->class, $class)) { continue; } $prototype->consolidatedMethods = null; } $this->consolidatedMethods = null; }
php
protected function revokeConsolidatedMethods() { $class = $this->class; foreach (self::$prototypes as $prototype) { if (!is_subclass_of($prototype->class, $class)) { continue; } $prototype->consolidatedMethods = null; } $this->consolidatedMethods = null; }
Revokes the consolidated methods of the prototype. The method must be invoked when prototype methods are modified.
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Prototype.php#L130-L143
schpill/thin
src/Prototype.php
Prototype.offsetSet
public function offsetSet($method, $callback) { self::$prototypes[$this->class]->methods[$method] = $callback; $this->revokeConsolidatedMethods(); }
php
public function offsetSet($method, $callback) { self::$prototypes[$this->class]->methods[$method] = $callback; $this->revokeConsolidatedMethods(); }
Adds or replaces the specified method of the prototype. @param string $method The name of the method. @param callable $callback
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Prototype.php#L152-L157
schpill/thin
src/Prototype.php
Prototype.offsetGet
public function offsetGet($method) { $methods = $this->getConsolidatedMethods(); if (!isset($methods[$method])) { throw new Exception("$method, $this->class"); } return $methods[$method]; }
php
public function offsetGet($method) { $methods = $this->getConsolidatedMethods(); if (!isset($methods[$method])) { throw new Exception("$method, $this->class"); } return $methods[$method]; }
Returns the callback associated with the specified method. @param string $method The name of the method. @throws Exception if the method is not defined. @return callable
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Prototype.php#L194-L203
fxpio/fxp-doctrine-console
Util/ObjectFieldUtil.php
ObjectFieldUtil.addOptions
public static function addOptions(InputDefinition $definition, array $fields, $description) { foreach ($fields as $field => $type) { $mode = 'array' === $type ? InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY : InputOption::VALUE_REQUIRED; if (!$definition->hasOption($field) && !$definition->hasArgument($field)) { $definition->addOption(new InputOption($field, null, $mode, sprintf($description, $field, $type))); } } }
php
public static function addOptions(InputDefinition $definition, array $fields, $description) { foreach ($fields as $field => $type) { $mode = 'array' === $type ? InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY : InputOption::VALUE_REQUIRED; if (!$definition->hasOption($field) && !$definition->hasArgument($field)) { $definition->addOption(new InputOption($field, null, $mode, sprintf($description, $field, $type))); } } }
Add options in input definition. @param InputDefinition $definition The input definition @param array $fields The fields @param string $description The option description
https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Util/ObjectFieldUtil.php#L32-L43
fxpio/fxp-doctrine-console
Util/ObjectFieldUtil.php
ObjectFieldUtil.getFieldValue
public static function getFieldValue(InputInterface $input, $fieldName) { $value = null; if ($input->hasArgument($fieldName)) { $value = $input->getArgument($fieldName); } elseif ($input->hasOption($fieldName)) { $value = $input->getOption($fieldName); } return $value; }
php
public static function getFieldValue(InputInterface $input, $fieldName) { $value = null; if ($input->hasArgument($fieldName)) { $value = $input->getArgument($fieldName); } elseif ($input->hasOption($fieldName)) { $value = $input->getOption($fieldName); } return $value; }
Get field value in console input. @param InputInterface $input The console input @param string $fieldName The field name @return mixed|null
https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Util/ObjectFieldUtil.php#L53-L64
fxpio/fxp-doctrine-console
Util/ObjectFieldUtil.php
ObjectFieldUtil.setFieldValue
public static function setFieldValue($instance, $fieldName, $value) { $setterMethodName = 'set'.ucfirst($fieldName); try { $ref = new \ReflectionClass($instance); $ref->getMethod($setterMethodName); } catch (\Exception $e) { throw new \InvalidArgumentException(sprintf('The setter method "%s" that should be used for property "%s" seems not to exist. Please check your spelling in the command option or in your implementation class.', $setterMethodName, $fieldName)); } $instance->$setterMethodName($value); }
php
public static function setFieldValue($instance, $fieldName, $value) { $setterMethodName = 'set'.ucfirst($fieldName); try { $ref = new \ReflectionClass($instance); $ref->getMethod($setterMethodName); } catch (\Exception $e) { throw new \InvalidArgumentException(sprintf('The setter method "%s" that should be used for property "%s" seems not to exist. Please check your spelling in the command option or in your implementation class.', $setterMethodName, $fieldName)); } $instance->$setterMethodName($value); }
Set the field value. @param object $instance The object instance @param string $fieldName The field name @param mixed|null $value The field value
https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Util/ObjectFieldUtil.php#L91-L103
morrislaptop/error-tracker-adapter
src/Adapter/Raygun.php
Raygun.report
public function report(Exception $e, array $extra = []) { return $this->raygun->SendException($e, null, $extra); }
php
public function report(Exception $e, array $extra = []) { return $this->raygun->SendException($e, null, $extra); }
Reports the exception to the SaaS platform @param Exception $e @param array $extra @return mixed
https://github.com/morrislaptop/error-tracker-adapter/blob/955aea67c45892da2b8813517600f338bada6a01/src/Adapter/Raygun.php#L28-L31
chilimatic/chilimatic-framework
lib/config/Ini.php
Ini.load
public function load($param = null) { try { if (empty($param['file'])) { throw new ConfigException(_('No config file was give please, the parameter '), 0, 1, __METHOD__, __LINE__); } $this->configFile = (string)$param['file']; if (isset($param['process-sections'])) { $this->processSections = (bool)$param['process-sections']; } if (isset($param['scanner-mode'])) { $this->scannerMode = (int)$param['scanner-mode']; } $data = parse_ini_file($this->configFile, $this->processSections, $this->scannerMode); $this->mainNode = new Node(null, IConfig::MAIN_NODE_KEY, 'main node'); foreach ($data as $key => $group) { if (!is_array($group)) { $newNode = new Node($this->mainNode, $key, $group); $this->mainNode->addChild($newNode); continue; } $newNode = new Node($this->mainNode, $key, $key); foreach ($group as $name => $value) { $childNode = new Node($newNode, $name, $value); $newNode->addChild($childNode); } $this->mainNode->addChild($newNode); } } catch (ConfigException $e) { throw $e; } }
php
public function load($param = null) { try { if (empty($param['file'])) { throw new ConfigException(_('No config file was give please, the parameter '), 0, 1, __METHOD__, __LINE__); } $this->configFile = (string)$param['file']; if (isset($param['process-sections'])) { $this->processSections = (bool)$param['process-sections']; } if (isset($param['scanner-mode'])) { $this->scannerMode = (int)$param['scanner-mode']; } $data = parse_ini_file($this->configFile, $this->processSections, $this->scannerMode); $this->mainNode = new Node(null, IConfig::MAIN_NODE_KEY, 'main node'); foreach ($data as $key => $group) { if (!is_array($group)) { $newNode = new Node($this->mainNode, $key, $group); $this->mainNode->addChild($newNode); continue; } $newNode = new Node($this->mainNode, $key, $key); foreach ($group as $name => $value) { $childNode = new Node($newNode, $name, $value); $newNode->addChild($childNode); } $this->mainNode->addChild($newNode); } } catch (ConfigException $e) { throw $e; } }
@param null $param @throws ConfigException @throws \Exception @return void
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/config/Ini.php#L50-L86
rackberg/para
src/Command/DeleteGroupCommand.php
DeleteGroupCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $groupName = $input->getArgument('group_name'); try { $this->groupConfiguration->deleteGroup($groupName); $this->groupConfiguration->save(); } catch (GroupNotFoundException $e) { $output->writeln('<error>The group you are trying to delete is ' . 'not stored in the configuration.</error>', 1); $this->logger->error('Failed to delete the group.', [ 'groupName' => $groupName, ]); $output->writeln('<error>Failed to delete the group "' . $groupName . '".', 1); return; } $output->writeln('<info>Successfully deleted the group from the configuration.</info>'); }
php
protected function execute(InputInterface $input, OutputInterface $output) { $groupName = $input->getArgument('group_name'); try { $this->groupConfiguration->deleteGroup($groupName); $this->groupConfiguration->save(); } catch (GroupNotFoundException $e) { $output->writeln('<error>The group you are trying to delete is ' . 'not stored in the configuration.</error>', 1); $this->logger->error('Failed to delete the group.', [ 'groupName' => $groupName, ]); $output->writeln('<error>Failed to delete the group "' . $groupName . '".', 1); return; } $output->writeln('<info>Successfully deleted the group from the configuration.</info>'); }
{@inheritdoc}
https://github.com/rackberg/para/blob/e0ef1356ed2979670eb7c670d88921406cade46e/src/Command/DeleteGroupCommand.php#L69-L89
hal-platform/hal-core
src/Validation/ValidatorErrorTrait.php
ValidatorErrorTrait.addError
private function addError(string $msg, ?string $field = null): void { if (!$field) { $field = 'all'; } if (!($this->errors[$field] ?? [])) { $this->errors[$field] = []; } $this->errors[$field][] = $msg; }
php
private function addError(string $msg, ?string $field = null): void { if (!$field) { $field = 'all'; } if (!($this->errors[$field] ?? [])) { $this->errors[$field] = []; } $this->errors[$field][] = $msg; }
@param string $msg @param string|null $field @return void
https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/Validation/ValidatorErrorTrait.php#L61-L72
hal-platform/hal-core
src/Validation/ValidatorErrorTrait.php
ValidatorErrorTrait.importErrors
private function importErrors(array $errors): void { foreach ($errors as $field => $errors) { foreach ($errors as $message) { $this->addError($message, $field); } } }
php
private function importErrors(array $errors): void { foreach ($errors as $field => $errors) { foreach ($errors as $message) { $this->addError($message, $field); } } }
@param array $errors @return void
https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/Validation/ValidatorErrorTrait.php#L79-L86
hal-platform/hal-core
src/Validation/ValidatorErrorTrait.php
ValidatorErrorTrait.addRequiredError
private function addRequiredError($name, $field = null): void { $msg = sprintf('%s is required', $name); $this->addError($msg, $field); }
php
private function addRequiredError($name, $field = null): void { $msg = sprintf('%s is required', $name); $this->addError($msg, $field); }
@param string $name @param string|null $field @return void
https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/Validation/ValidatorErrorTrait.php#L94-L98
hal-platform/hal-core
src/Validation/ValidatorErrorTrait.php
ValidatorErrorTrait.addLengthError
private function addLengthError($name, $min, $max, $field = null): void { $isMinZero = ($min === 0); $isMaxBig = ($max > 200); if ($isMinZero) { $msg = sprintf('%s must be %d characters or fewer', $name, $max); } elseif ($isMaxBig) { $msg = sprintf('%s must be %d characters or more', $name, $min); } else { $msg = sprintf('%s must contain %d - %d characters', $name, $min, $max); } $this->addError($msg, $field); }
php
private function addLengthError($name, $min, $max, $field = null): void { $isMinZero = ($min === 0); $isMaxBig = ($max > 200); if ($isMinZero) { $msg = sprintf('%s must be %d characters or fewer', $name, $max); } elseif ($isMaxBig) { $msg = sprintf('%s must be %d characters or more', $name, $min); } else { $msg = sprintf('%s must contain %d - %d characters', $name, $min, $max); } $this->addError($msg, $field); }
@param string $name @param int $min @param int $max @param string|null $field @return void
https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/Validation/ValidatorErrorTrait.php#L108-L124
rbone/phactory
lib/Phactory/Factory.php
Factory.create
public function create($type, $override, $persisted) { $base = $this->factory->blueprint(); $variation = $this->getVariation($type); $blueprint = array_merge($base, $variation, $override); return new Blueprint($this->name, $type, $blueprint, $this->isFixture($type), $persisted); }
php
public function create($type, $override, $persisted) { $base = $this->factory->blueprint(); $variation = $this->getVariation($type); $blueprint = array_merge($base, $variation, $override); return new Blueprint($this->name, $type, $blueprint, $this->isFixture($type), $persisted); }
Creates a new blueprint @param string $type variation or fixture @param array $override attributes values overrides @param boolean $persisted wether it will save the object or not @return \Phactory\Blueprint
https://github.com/rbone/phactory/blob/f1c474084f9b310d171f393fe196e8a2a7aae1ec/lib/Phactory/Factory.php#L40-L48
rbone/phactory
lib/Phactory/Factory.php
Factory.getVariation
private function getVariation($type) { if ($type == 'blueprint') { return array(); } elseif (method_exists($this->factory, "{$type}Fixture")) { return call_user_func(array($this->factory, "{$type}Fixture")); } elseif (method_exists($this->factory, "{$type}_fixture")) { // @deprecated Backwards compatibility return call_user_func(array($this->factory, "{$type}_fixture")); } elseif (method_exists($this->factory, $type)) { return call_user_func(array($this->factory, $type)); } else { throw new \BadMethodCallException("No such variation '$type' on " . get_class($this->factory)); } }
php
private function getVariation($type) { if ($type == 'blueprint') { return array(); } elseif (method_exists($this->factory, "{$type}Fixture")) { return call_user_func(array($this->factory, "{$type}Fixture")); } elseif (method_exists($this->factory, "{$type}_fixture")) { // @deprecated Backwards compatibility return call_user_func(array($this->factory, "{$type}_fixture")); } elseif (method_exists($this->factory, $type)) { return call_user_func(array($this->factory, $type)); } else { throw new \BadMethodCallException("No such variation '$type' on " . get_class($this->factory)); } }
Applies a variation to the basic blueprint or calls the fixture @param string $type variation or fixture @return array @throws \BadMethodCallException
https://github.com/rbone/phactory/blob/f1c474084f9b310d171f393fe196e8a2a7aae1ec/lib/Phactory/Factory.php#L56-L69
UnionOfRAD/li3_quality
qa/rules/syntax/HasCorrectCommentStyle.php
HasCorrectCommentStyle.apply
public function apply($testable, array $config = array()) { $tokens = $testable->tokens(); $comments = $testable->findAll(array(T_COMMENT)); foreach ($comments as $tokenId) { $token = $tokens[$tokenId]; $parentId = $tokens[$tokenId]['parent']; if ($parentId === -1 || $tokens[$parentId]['id'] !== T_FUNCTION) { $this->addViolation(array( 'message' => 'Inline comments should never appear.', 'line' => $token['line'], )); } elseif (preg_match('/^test/', Parser::label($parentId, $tokens)) === 0) { $this->addViolation(array( 'message' => 'Inline comments should only appear in testing methods.', 'line' => $token['line'], )); } } }
php
public function apply($testable, array $config = array()) { $tokens = $testable->tokens(); $comments = $testable->findAll(array(T_COMMENT)); foreach ($comments as $tokenId) { $token = $tokens[$tokenId]; $parentId = $tokens[$tokenId]['parent']; if ($parentId === -1 || $tokens[$parentId]['id'] !== T_FUNCTION) { $this->addViolation(array( 'message' => 'Inline comments should never appear.', 'line' => $token['line'], )); } elseif (preg_match('/^test/', Parser::label($parentId, $tokens)) === 0) { $this->addViolation(array( 'message' => 'Inline comments should only appear in testing methods.', 'line' => $token['line'], )); } } }
Will iterate tokens looking for comments and if found will determine the regex to test the comment against. @param Testable $testable The testable object @return void
https://github.com/UnionOfRAD/li3_quality/blob/acb72a43ae835e6d200bc0eba1a61aee610e36bf/qa/rules/syntax/HasCorrectCommentStyle.php#L22-L43
gregorybesson/PlaygroundFlow
src/Service/WebTechno.php
WebTechno.getWebTechnoMapper
public function getWebTechnoMapper() { if (null === $this->webTechnoMapper) { $this->webTechnoMapper = $this->serviceLocator->get('playgroundflow_webtechno_mapper'); } return $this->webTechnoMapper; }
php
public function getWebTechnoMapper() { if (null === $this->webTechnoMapper) { $this->webTechnoMapper = $this->serviceLocator->get('playgroundflow_webtechno_mapper'); } return $this->webTechnoMapper; }
getWebTechnoMapper @return WebTechnoMapperInterface
https://github.com/gregorybesson/PlaygroundFlow/blob/f97493f8527e425d46223ac7b5c41331ab8b3022/src/Service/WebTechno.php#L263-L270
gregorybesson/PlaygroundFlow
src/Service/WebTechno.php
WebTechno.getStoryMappingMapper
public function getStoryMappingMapper() { if (null === $this->storyMappingMapper) { $this->storyMappingMapper = $this->serviceLocator->get('playgroundflow_storymapping_mapper'); } return $this->storyMappingMapper; }
php
public function getStoryMappingMapper() { if (null === $this->storyMappingMapper) { $this->storyMappingMapper = $this->serviceLocator->get('playgroundflow_storymapping_mapper'); } return $this->storyMappingMapper; }
getStoryMappingMapper @return StoryMappingMapperInterface
https://github.com/gregorybesson/PlaygroundFlow/blob/f97493f8527e425d46223ac7b5c41331ab8b3022/src/Service/WebTechno.php#L290-L297
gregorybesson/PlaygroundFlow
src/Service/WebTechno.php
WebTechno.getObjectAttributeMappingMapper
public function getObjectAttributeMappingMapper() { if (null === $this->objectAttributeMappingMapper) { $this->objectAttributeMappingMapper = $this->serviceLocator->get('playgroundflow_objectattributemapping_mapper'); } return $this->objectAttributeMappingMapper; }
php
public function getObjectAttributeMappingMapper() { if (null === $this->objectAttributeMappingMapper) { $this->objectAttributeMappingMapper = $this->serviceLocator->get('playgroundflow_objectattributemapping_mapper'); } return $this->objectAttributeMappingMapper; }
getObjectAttributeMappingMapper @return ObjectAttributeMapperInterface
https://github.com/gregorybesson/PlaygroundFlow/blob/f97493f8527e425d46223ac7b5c41331ab8b3022/src/Service/WebTechno.php#L317-L324
gregorybesson/PlaygroundFlow
src/Service/WebTechno.php
WebTechno.getObjectMappingMapper
public function getObjectMappingMapper() { if (null === $this->objectMappingMapper) { $this->objectMappingMapper = $this->serviceLocator->get('playgroundflow_objectmapping_mapper'); } return $this->objectMappingMapper; }
php
public function getObjectMappingMapper() { if (null === $this->objectMappingMapper) { $this->objectMappingMapper = $this->serviceLocator->get('playgroundflow_objectmapping_mapper'); } return $this->objectMappingMapper; }
getObjectMappingMapper @return ObjectMapperInterface
https://github.com/gregorybesson/PlaygroundFlow/blob/f97493f8527e425d46223ac7b5c41331ab8b3022/src/Service/WebTechno.php#L344-L351
Tuna-CMS/tuna-bundle
src/Tuna/Bundle/CategoryBundle/Form/Type/AddableCategoryType.php
AddableCategoryType.buildForm
public function buildForm(FormBuilderInterface $builder, array $options) { $repo = $this->em->getRepository($options['class']); $choiceOptions = [ 'choices' => $this->getChoices($repo), 'attr' => [ 'class' => 'filtered', ], ]; if ($options['nullable']) { $choiceOptions['empty_value'] = 'components.categories.form.empty'; } $builder ->add(self::CHOICE_FIELD, ChoiceType::class, $choiceOptions) ->add(self::NEW_VALUE_FIELD, new CategoryType($options['class']), []) ->addModelTransformer(new IdToCategoryTransformer($repo)); }
php
public function buildForm(FormBuilderInterface $builder, array $options) { $repo = $this->em->getRepository($options['class']); $choiceOptions = [ 'choices' => $this->getChoices($repo), 'attr' => [ 'class' => 'filtered', ], ]; if ($options['nullable']) { $choiceOptions['empty_value'] = 'components.categories.form.empty'; } $builder ->add(self::CHOICE_FIELD, ChoiceType::class, $choiceOptions) ->add(self::NEW_VALUE_FIELD, new CategoryType($options['class']), []) ->addModelTransformer(new IdToCategoryTransformer($repo)); }
{@inheritdoc}
https://github.com/Tuna-CMS/tuna-bundle/blob/1f999de44e14cbe9f992d46f2e5e74ddc117b04c/src/Tuna/Bundle/CategoryBundle/Form/Type/AddableCategoryType.php#L39-L56
Tuna-CMS/tuna-bundle
src/Tuna/Bundle/CategoryBundle/Form/Type/AddableCategoryType.php
AddableCategoryType.configureOptions
public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'class' => Category::class, 'compound' => true, 'error_mapping' => ['.' => self::NEW_VALUE_FIELD], 'error_bubbling' => false, 'translation_domain' => 'tuna_admin', 'nullable' => true, ]); }
php
public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'class' => Category::class, 'compound' => true, 'error_mapping' => ['.' => self::NEW_VALUE_FIELD], 'error_bubbling' => false, 'translation_domain' => 'tuna_admin', 'nullable' => true, ]); }
{@inheritdoc}
https://github.com/Tuna-CMS/tuna-bundle/blob/1f999de44e14cbe9f992d46f2e5e74ddc117b04c/src/Tuna/Bundle/CategoryBundle/Form/Type/AddableCategoryType.php#L61-L71
Tuna-CMS/tuna-bundle
src/Tuna/Bundle/CategoryBundle/Form/Type/AddableCategoryType.php
AddableCategoryType.getChoices
private function getChoices(EntityRepository $repo) { $choices = []; $entities = $repo->findAll(); foreach ($entities as $entity) { $choices[$entity->getId()] = $entity->getName(); } return [ self::NEW_VALUE_OPTION => 'components.categories.form.new', 'components.categories.form.existing' => $choices, ]; }
php
private function getChoices(EntityRepository $repo) { $choices = []; $entities = $repo->findAll(); foreach ($entities as $entity) { $choices[$entity->getId()] = $entity->getName(); } return [ self::NEW_VALUE_OPTION => 'components.categories.form.new', 'components.categories.form.existing' => $choices, ]; }
@param EntityRepository $repo @return array
https://github.com/Tuna-CMS/tuna-bundle/blob/1f999de44e14cbe9f992d46f2e5e74ddc117b04c/src/Tuna/Bundle/CategoryBundle/Form/Type/AddableCategoryType.php#L86-L98
pmdevelopment/tool-bundle
Framework/Form/SendMailFormType.php
SendMailFormType.buildForm
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('sender', EmailType::class, [ 'label' => 'mail_sender', 'constraints' => new Email(), ]) ->add('recipient', EmailType::class, [ 'label' => 'mail_recipient', 'constraints' => new Email(), ]) ->add('subject', TextType::class, [ 'label' => 'mail_subject', 'constraints' => new NotBlank(), ]) ->add('message', TextareaType::class, [ 'label' => 'mail_message', 'constraints' => new NotBlank(), 'attr' => [ 'rows' => $options['message_rows'], ], ]) ->add('send', SubmitType::class, [ 'label' => 'button.send', ]); }
php
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('sender', EmailType::class, [ 'label' => 'mail_sender', 'constraints' => new Email(), ]) ->add('recipient', EmailType::class, [ 'label' => 'mail_recipient', 'constraints' => new Email(), ]) ->add('subject', TextType::class, [ 'label' => 'mail_subject', 'constraints' => new NotBlank(), ]) ->add('message', TextareaType::class, [ 'label' => 'mail_message', 'constraints' => new NotBlank(), 'attr' => [ 'rows' => $options['message_rows'], ], ]) ->add('send', SubmitType::class, [ 'label' => 'button.send', ]); }
{@inheritdoc}
https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Framework/Form/SendMailFormType.php#L31-L56
PandaPlatform/jar
Http/Response.php
Response.addResponseHeader
public function addResponseHeader(ResponseHeader $header, $key = '') { if (empty($key)) { $this->responseHeaders[] = $header->toArray(); } else { $this->responseHeaders[$key] = $header->toArray(); } return $this; }
php
public function addResponseHeader(ResponseHeader $header, $key = '') { if (empty($key)) { $this->responseHeaders[] = $header->toArray(); } else { $this->responseHeaders[$key] = $header->toArray(); } return $this; }
@param ResponseHeader $header @param string $key @return $this
https://github.com/PandaPlatform/jar/blob/56b6d8687a565482f8315f3dde4cf08d6fc0e2b3/Http/Response.php#L105-L114
PandaPlatform/jar
Http/Response.php
Response.addResponseContent
public function addResponseContent(ResponseContent $content, $key = '') { if (empty($key)) { $this->responseContent[] = $content->toArray(); } else { $this->responseContent[$key] = $content->toArray(); } return $this; }
php
public function addResponseContent(ResponseContent $content, $key = '') { if (empty($key)) { $this->responseContent[] = $content->toArray(); } else { $this->responseContent[$key] = $content->toArray(); } return $this; }
@param ResponseContent $content @param string $key @return $this
https://github.com/PandaPlatform/jar/blob/56b6d8687a565482f8315f3dde4cf08d6fc0e2b3/Http/Response.php#L122-L131
PandaPlatform/jar
Http/Response.php
Response.send
public function send($allowOrigin = '', $withCredentials = true) { // Set allow origin if (!empty($allowOrigin)) { $this->headers->set('Access-Control-Allow-Origin', $allowOrigin); } // Set Allow Credentials Access-Control-Allow-Credentials if ($withCredentials) { $this->headers->set('Access-Control-Allow-Credentials', 'true'); } // Set json response content $response = [ 'headers' => $this->getResponseHeaders(), 'content' => $this->getResponseContent(), ]; $json = json_encode($response, JSON_FORCE_OBJECT); // Check if json is valid if ($json === false) { throw new Exception('The given response headers or content cannot be converted to json. Check your content and try again.'); } // Set response json $this->setJson($json); // Send the response parent::send(); return $this; }
php
public function send($allowOrigin = '', $withCredentials = true) { // Set allow origin if (!empty($allowOrigin)) { $this->headers->set('Access-Control-Allow-Origin', $allowOrigin); } // Set Allow Credentials Access-Control-Allow-Credentials if ($withCredentials) { $this->headers->set('Access-Control-Allow-Credentials', 'true'); } // Set json response content $response = [ 'headers' => $this->getResponseHeaders(), 'content' => $this->getResponseContent(), ]; $json = json_encode($response, JSON_FORCE_OBJECT); // Check if json is valid if ($json === false) { throw new Exception('The given response headers or content cannot be converted to json. Check your content and try again.'); } // Set response json $this->setJson($json); // Send the response parent::send(); return $this; }
@param string $allowOrigin @param bool $withCredentials @return $this @throws InvalidArgumentException @throws Exception
https://github.com/PandaPlatform/jar/blob/56b6d8687a565482f8315f3dde4cf08d6fc0e2b3/Http/Response.php#L141-L172
PHPColibri/framework
Database/AbstractDb/Driver.php
Driver.queries
public function queries(array $queries, $rollbackOnFail = false) { /* @var SqlException|\Exception $e */ try { foreach ($queries as &$query) { $this->connection->query($query . ';'); } } catch (\Exception $e) { $rollbackOnFail && $this->transactionRollback(); throw $e; } }
php
public function queries(array $queries, $rollbackOnFail = false) { /* @var SqlException|\Exception $e */ try { foreach ($queries as &$query) { $this->connection->query($query . ';'); } } catch (\Exception $e) { $rollbackOnFail && $this->transactionRollback(); throw $e; } }
Выполняет несколько запросов. Executes a number of $queries. @param array $queries запросы, которые нужно выполнить. queries to execute. @param bool $rollbackOnFail нужно ли откатывать транзакцию. if you need to roll back transaction. @throws \Colibri\Database\Exception\SqlException
https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Database/AbstractDb/Driver.php#L61-L72
chilimatic/chilimatic-framework
lib/database/sql/querybuilder/AbstractQueryBuilder.php
AbstractQueryBuilder.parseTableName
public function parseTableName(\ReflectionClass $reflection) { $hd = $this->parser->parse($reflection->getDocComment()); if (!empty($hd[0])) { return $hd[1]; } $table = substr($reflection->getName(), strlen($reflection->getNamespaceName())); return strtolower(str_replace('\\', '', $table)); }
php
public function parseTableName(\ReflectionClass $reflection) { $hd = $this->parser->parse($reflection->getDocComment()); if (!empty($hd[0])) { return $hd[1]; } $table = substr($reflection->getName(), strlen($reflection->getNamespaceName())); return strtolower(str_replace('\\', '', $table)); }
@param \ReflectionClass $reflection @return mixed|string
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/querybuilder/AbstractQueryBuilder.php#L88-L99
chilimatic/chilimatic-framework
lib/database/sql/querybuilder/AbstractQueryBuilder.php
AbstractQueryBuilder.fetchCacheData
public function fetchCacheData(AbstractModel $model) { $this->position = get_class($model); if (!isset($this->modelDataCache[$this->position])) { $this->modelDataCache[$this->position] = $this->prepareCacheData($model); } return $this->modelDataCache[$this->position]; }
php
public function fetchCacheData(AbstractModel $model) { $this->position = get_class($model); if (!isset($this->modelDataCache[$this->position])) { $this->modelDataCache[$this->position] = $this->prepareCacheData($model); } return $this->modelDataCache[$this->position]; }
@param AbstractModel $model @return array
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/querybuilder/AbstractQueryBuilder.php#L106-L114
chilimatic/chilimatic-framework
lib/database/sql/querybuilder/AbstractQueryBuilder.php
AbstractQueryBuilder.prepareCacheData
public function prepareCacheData(AbstractModel $model) { /** * @todo change MySQLTableData to a usecase based one */ $tableData = clone $this->tableData; $reflection = new \ReflectionClass($model); $tableData->setTableName($this->parseTableName($reflection)); return [ 'tableData' => $tableData, 'reflection' => new \ReflectionClass($model), 'relationList' => $this->extractRelations($reflection), ]; }
php
public function prepareCacheData(AbstractModel $model) { /** * @todo change MySQLTableData to a usecase based one */ $tableData = clone $this->tableData; $reflection = new \ReflectionClass($model); $tableData->setTableName($this->parseTableName($reflection)); return [ 'tableData' => $tableData, 'reflection' => new \ReflectionClass($model), 'relationList' => $this->extractRelations($reflection), ]; }
@param AbstractModel $model @return array
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/querybuilder/AbstractQueryBuilder.php#L121-L135
chilimatic/chilimatic-framework
lib/database/sql/querybuilder/AbstractQueryBuilder.php
AbstractQueryBuilder.extractRelations
public function extractRelations(\ReflectionClass $reflection) { $propertyList = $reflection->getDefaultProperties(); if ($this->cache && $res = $this->cache->get(md5(json_encode($propertyList)))) { return $res; } $relation = []; foreach ($propertyList as $name => $value) { $comment = $reflection->getProperty($name)->getDocComment(); $d = $this->parser->parse($comment); if (!$d) { continue; } $relation[] = [ 'mapping_id' => $d[0], 'model' => $d[1], 'target' => $name ]; } if ($this->cache) { $this->cache->set(md5(json_encode($propertyList)), $relation, 300); } return $relation; }
php
public function extractRelations(\ReflectionClass $reflection) { $propertyList = $reflection->getDefaultProperties(); if ($this->cache && $res = $this->cache->get(md5(json_encode($propertyList)))) { return $res; } $relation = []; foreach ($propertyList as $name => $value) { $comment = $reflection->getProperty($name)->getDocComment(); $d = $this->parser->parse($comment); if (!$d) { continue; } $relation[] = [ 'mapping_id' => $d[0], 'model' => $d[1], 'target' => $name ]; } if ($this->cache) { $this->cache->set(md5(json_encode($propertyList)), $relation, 300); } return $relation; }
@param \ReflectionClass $reflection @return bool|\SplFixedArray
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/querybuilder/AbstractQueryBuilder.php#L143-L171