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_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
Wedeto/HTTP
src/Forms/FormField.php
FormField.formatErrorMessage
public static function formatErrorMessage(array $error_message) { $msg = $error_message['msg'] ?? ""; $context = $error_message['context'] ?? []; if (class_exists("Wedeto\I18n\I18nShortcut")) { return t($msg, $context); } return WF::fillPlaceholders($msg, $context); }
php
public static function formatErrorMessage(array $error_message) { $msg = $error_message['msg'] ?? ""; $context = $error_message['context'] ?? []; if (class_exists("Wedeto\I18n\I18nShortcut")) { return t($msg, $context); } return WF::fillPlaceholders($msg, $context); }
[ "public", "static", "function", "formatErrorMessage", "(", "array", "$", "error_message", ")", "{", "$", "msg", "=", "$", "error_message", "[", "'msg'", "]", "??", "\"\"", ";", "$", "context", "=", "$", "error_message", "[", "'context'", "]", "??", "[", ...
Format the error message into a single string @return string The formatted error message
[ "Format", "the", "error", "message", "into", "a", "single", "string" ]
train
https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/Forms/FormField.php#L499-L509
cloudtek/dynamodm
lib/Cloudtek/DynamoDM/Repository/DefaultRepositoryFactory.php
DefaultRepositoryFactory.instantiateRepository
protected function instantiateRepository($repositoryClassName, DocumentManager $documentManager, ClassMetadata $metadata) { return new $repositoryClassName($documentManager, $documentManager->getUnitOfWork(), $metadata); }
php
protected function instantiateRepository($repositoryClassName, DocumentManager $documentManager, ClassMetadata $metadata) { return new $repositoryClassName($documentManager, $documentManager->getUnitOfWork(), $metadata); }
[ "protected", "function", "instantiateRepository", "(", "$", "repositoryClassName", ",", "DocumentManager", "$", "documentManager", ",", "ClassMetadata", "$", "metadata", ")", "{", "return", "new", "$", "repositoryClassName", "(", "$", "documentManager", ",", "$", "d...
{@inheritdoc}
[ "{" ]
train
https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/Repository/DefaultRepositoryFactory.php#L16-L19
horntell/php-sdk
lib/guzzle/GuzzleHttp/Subscriber/History.php
History.add
private function add( RequestInterface $request, ResponseInterface $response = null ) { $this->transactions[] = ['request' => $request, 'response' => $response]; if (count($this->transactions) > $this->limit) { array_shift($this->transactions); } }
php
private function add( RequestInterface $request, ResponseInterface $response = null ) { $this->transactions[] = ['request' => $request, 'response' => $response]; if (count($this->transactions) > $this->limit) { array_shift($this->transactions); } }
[ "private", "function", "add", "(", "RequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", "=", "null", ")", "{", "$", "this", "->", "transactions", "[", "]", "=", "[", "'request'", "=>", "$", "request", ",", "'response'", "=>", "$",...
Add a request to the history @param RequestInterface $request Request to add @param ResponseInterface $response Response of the request
[ "Add", "a", "request", "to", "the", "history" ]
train
https://github.com/horntell/php-sdk/blob/e5205e9396a21b754d5651a8aa5898da5922a1b7/lib/guzzle/GuzzleHttp/Subscriber/History.php#L133-L141
onoi/callback-container
src/CallbackContainerBuilder.php
CallbackContainerBuilder.registerFromFile
public function registerFromFile( $file ) { if ( !is_readable( ( $file = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, $file ) ) ) ) { throw new FileNotFoundException( "Cannot access or read {$file}" ); } $this->register( require $file ); }
php
public function registerFromFile( $file ) { if ( !is_readable( ( $file = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, $file ) ) ) ) { throw new FileNotFoundException( "Cannot access or read {$file}" ); } $this->register( require $file ); }
[ "public", "function", "registerFromFile", "(", "$", "file", ")", "{", "if", "(", "!", "is_readable", "(", "(", "$", "file", "=", "str_replace", "(", "array", "(", "'\\\\'", ",", "'/'", ")", ",", "DIRECTORY_SEPARATOR", ",", "$", "file", ")", ")", ")", ...
@since 2.0 {@inheritDoc}
[ "@since", "2", ".", "0" ]
train
https://github.com/onoi/callback-container/blob/70d2266c19b4bf0b4e78672fea340d8fdefb7500/src/CallbackContainerBuilder.php#L73-L80
onoi/callback-container
src/CallbackContainerBuilder.php
CallbackContainerBuilder.registerCallback
public function registerCallback( $serviceName, callable $callback ) { if ( !is_string( $serviceName ) ) { throw new InvalidParameterTypeException( "Expected a string" ); } $this->registry[$serviceName] = $callback; }
php
public function registerCallback( $serviceName, callable $callback ) { if ( !is_string( $serviceName ) ) { throw new InvalidParameterTypeException( "Expected a string" ); } $this->registry[$serviceName] = $callback; }
[ "public", "function", "registerCallback", "(", "$", "serviceName", ",", "callable", "$", "callback", ")", "{", "if", "(", "!", "is_string", "(", "$", "serviceName", ")", ")", "{", "throw", "new", "InvalidParameterTypeException", "(", "\"Expected a string\"", ")"...
@since 2.0 {@inheritDoc}
[ "@since", "2", ".", "0" ]
train
https://github.com/onoi/callback-container/blob/70d2266c19b4bf0b4e78672fea340d8fdefb7500/src/CallbackContainerBuilder.php#L87-L94
onoi/callback-container
src/CallbackContainerBuilder.php
CallbackContainerBuilder.registerObject
public function registerObject( $serviceName, $instance ) { if ( !is_string( $serviceName ) ) { throw new InvalidParameterTypeException( "Expected a string" ); } if ( isset( $this->aliases[$serviceName] ) ) { throw new ServiceAliasMismatchException( $serviceName ); } unset( $this->singletons[$serviceName] ); $this->registry[$serviceName] = $instance; $this->singletons[$serviceName]['#'] = $instance; }
php
public function registerObject( $serviceName, $instance ) { if ( !is_string( $serviceName ) ) { throw new InvalidParameterTypeException( "Expected a string" ); } if ( isset( $this->aliases[$serviceName] ) ) { throw new ServiceAliasMismatchException( $serviceName ); } unset( $this->singletons[$serviceName] ); $this->registry[$serviceName] = $instance; $this->singletons[$serviceName]['#'] = $instance; }
[ "public", "function", "registerObject", "(", "$", "serviceName", ",", "$", "instance", ")", "{", "if", "(", "!", "is_string", "(", "$", "serviceName", ")", ")", "{", "throw", "new", "InvalidParameterTypeException", "(", "\"Expected a string\"", ")", ";", "}", ...
If you are not running PHPUnit or for that matter any other testing environment then you are not suppose to use this function. @since 2.0 {@inheritDoc}
[ "If", "you", "are", "not", "running", "PHPUnit", "or", "for", "that", "matter", "any", "other", "testing", "environment", "then", "you", "are", "not", "suppose", "to", "use", "this", "function", "." ]
train
https://github.com/onoi/callback-container/blob/70d2266c19b4bf0b4e78672fea340d8fdefb7500/src/CallbackContainerBuilder.php#L104-L118
onoi/callback-container
src/CallbackContainerBuilder.php
CallbackContainerBuilder.registerExpectedReturnType
public function registerExpectedReturnType( $serviceName, $type ) { if ( !is_string( $serviceName ) || !is_string( $type ) ) { throw new InvalidParameterTypeException( "Expected a string" ); } $this->expectedReturnTypeByHandler[$serviceName] = $type; }
php
public function registerExpectedReturnType( $serviceName, $type ) { if ( !is_string( $serviceName ) || !is_string( $type ) ) { throw new InvalidParameterTypeException( "Expected a string" ); } $this->expectedReturnTypeByHandler[$serviceName] = $type; }
[ "public", "function", "registerExpectedReturnType", "(", "$", "serviceName", ",", "$", "type", ")", "{", "if", "(", "!", "is_string", "(", "$", "serviceName", ")", "||", "!", "is_string", "(", "$", "type", ")", ")", "{", "throw", "new", "InvalidParameterTy...
@since 2.0 {@inheritDoc}
[ "@since", "2", ".", "0" ]
train
https://github.com/onoi/callback-container/blob/70d2266c19b4bf0b4e78672fea340d8fdefb7500/src/CallbackContainerBuilder.php#L125-L132
onoi/callback-container
src/CallbackContainerBuilder.php
CallbackContainerBuilder.registerAlias
public function registerAlias( $serviceName, $alias ) { if ( !is_string( $serviceName ) || !is_string( $alias ) ) { throw new InvalidParameterTypeException( "Expected a string" ); } if ( isset( $this->registry[$alias] ) ) { throw new ServiceAliasAssignmentException( $alias ); } if ( isset( $this->aliases[$alias] ) && $this->aliases[$alias] !== $serviceName ) { throw new ServiceAliasCrossAssignmentException( $serviceName, $alias, $this->aliases[$alias] ); } $this->aliases[$alias] = $serviceName; }
php
public function registerAlias( $serviceName, $alias ) { if ( !is_string( $serviceName ) || !is_string( $alias ) ) { throw new InvalidParameterTypeException( "Expected a string" ); } if ( isset( $this->registry[$alias] ) ) { throw new ServiceAliasAssignmentException( $alias ); } if ( isset( $this->aliases[$alias] ) && $this->aliases[$alias] !== $serviceName ) { throw new ServiceAliasCrossAssignmentException( $serviceName, $alias, $this->aliases[$alias] ); } $this->aliases[$alias] = $serviceName; }
[ "public", "function", "registerAlias", "(", "$", "serviceName", ",", "$", "alias", ")", "{", "if", "(", "!", "is_string", "(", "$", "serviceName", ")", "||", "!", "is_string", "(", "$", "alias", ")", ")", "{", "throw", "new", "InvalidParameterTypeException...
@since 2.0 {@inheritDoc}
[ "@since", "2", ".", "0" ]
train
https://github.com/onoi/callback-container/blob/70d2266c19b4bf0b4e78672fea340d8fdefb7500/src/CallbackContainerBuilder.php#L139-L154
onoi/callback-container
src/CallbackContainerBuilder.php
CallbackContainerBuilder.isRegistered
public function isRegistered( $serviceName ) { if ( is_string( $serviceName ) && isset( $this->aliases[$serviceName] ) ) { $serviceName = $this->aliases[$serviceName]; } return isset( $this->registry[$serviceName] ); }
php
public function isRegistered( $serviceName ) { if ( is_string( $serviceName ) && isset( $this->aliases[$serviceName] ) ) { $serviceName = $this->aliases[$serviceName]; } return isset( $this->registry[$serviceName] ); }
[ "public", "function", "isRegistered", "(", "$", "serviceName", ")", "{", "if", "(", "is_string", "(", "$", "serviceName", ")", "&&", "isset", "(", "$", "this", "->", "aliases", "[", "$", "serviceName", "]", ")", ")", "{", "$", "serviceName", "=", "$", ...
@since 2.0 {@inheritDoc}
[ "@since", "2", ".", "0" ]
train
https://github.com/onoi/callback-container/blob/70d2266c19b4bf0b4e78672fea340d8fdefb7500/src/CallbackContainerBuilder.php#L161-L168
onoi/callback-container
src/CallbackContainerBuilder.php
CallbackContainerBuilder.create
public function create( $serviceName ) { if ( is_string( $serviceName ) && isset( $this->aliases[$serviceName] ) ) { $serviceName = $this->aliases[$serviceName]; } return $this->getReturnValueFromCallbackHandlerFor( $serviceName, func_get_args() ); }
php
public function create( $serviceName ) { if ( is_string( $serviceName ) && isset( $this->aliases[$serviceName] ) ) { $serviceName = $this->aliases[$serviceName]; } return $this->getReturnValueFromCallbackHandlerFor( $serviceName, func_get_args() ); }
[ "public", "function", "create", "(", "$", "serviceName", ")", "{", "if", "(", "is_string", "(", "$", "serviceName", ")", "&&", "isset", "(", "$", "this", "->", "aliases", "[", "$", "serviceName", "]", ")", ")", "{", "$", "serviceName", "=", "$", "thi...
@since 2.0 {@inheritDoc}
[ "@since", "2", ".", "0" ]
train
https://github.com/onoi/callback-container/blob/70d2266c19b4bf0b4e78672fea340d8fdefb7500/src/CallbackContainerBuilder.php#L175-L182
onoi/callback-container
src/CallbackContainerBuilder.php
CallbackContainerBuilder.singleton
public function singleton( $serviceName ) { if ( is_string( $serviceName ) && isset( $this->aliases[$serviceName] ) ) { $serviceName = $this->aliases[$serviceName]; } return $this->getReturnValueFromSingletonFor( $serviceName, func_get_args() ); }
php
public function singleton( $serviceName ) { if ( is_string( $serviceName ) && isset( $this->aliases[$serviceName] ) ) { $serviceName = $this->aliases[$serviceName]; } return $this->getReturnValueFromSingletonFor( $serviceName, func_get_args() ); }
[ "public", "function", "singleton", "(", "$", "serviceName", ")", "{", "if", "(", "is_string", "(", "$", "serviceName", ")", "&&", "isset", "(", "$", "this", "->", "aliases", "[", "$", "serviceName", "]", ")", ")", "{", "$", "serviceName", "=", "$", "...
@since 2.0 {@inheritDoc}
[ "@since", "2", ".", "0" ]
train
https://github.com/onoi/callback-container/blob/70d2266c19b4bf0b4e78672fea340d8fdefb7500/src/CallbackContainerBuilder.php#L189-L196
onoi/callback-container
src/CallbackContainerBuilder.php
CallbackContainerBuilder.deregister
public function deregister( $serviceName ) { unset( $this->registry[$serviceName] ); unset( $this->singletons[$serviceName] ); unset( $this->expectedReturnTypeByHandler[$serviceName] ); foreach ( $this->aliases as $alias => $service ) { if ( $service === $serviceName ) { unset( $this->aliases[$alias] ); } } }
php
public function deregister( $serviceName ) { unset( $this->registry[$serviceName] ); unset( $this->singletons[$serviceName] ); unset( $this->expectedReturnTypeByHandler[$serviceName] ); foreach ( $this->aliases as $alias => $service ) { if ( $service === $serviceName ) { unset( $this->aliases[$alias] ); } } }
[ "public", "function", "deregister", "(", "$", "serviceName", ")", "{", "unset", "(", "$", "this", "->", "registry", "[", "$", "serviceName", "]", ")", ";", "unset", "(", "$", "this", "->", "singletons", "[", "$", "serviceName", "]", ")", ";", "unset", ...
@since 2.0 @param string $serviceName
[ "@since", "2", ".", "0" ]
train
https://github.com/onoi/callback-container/blob/70d2266c19b4bf0b4e78672fea340d8fdefb7500/src/CallbackContainerBuilder.php#L203-L213
jfadich/json-property
src/JsonPropertyTrait.php
JsonPropertyTrait.saveJsonString
public function saveJsonString($property, $jsonString) { $this->jsonManager()->isJsonProperty($property, true); $this->{$property} = $jsonString; }
php
public function saveJsonString($property, $jsonString) { $this->jsonManager()->isJsonProperty($property, true); $this->{$property} = $jsonString; }
[ "public", "function", "saveJsonString", "(", "$", "property", ",", "$", "jsonString", ")", "{", "$", "this", "->", "jsonManager", "(", ")", "->", "isJsonProperty", "(", "$", "property", ",", "true", ")", ";", "$", "this", "->", "{", "$", "property", "}...
Set the raw json string on the model @param string $property @param string $jsonString @throws JsonPropertyException
[ "Set", "the", "raw", "json", "string", "on", "the", "model" ]
train
https://github.com/jfadich/json-property/blob/3c11ac731a7bc206529058a94047eeafa5827b15/src/JsonPropertyTrait.php#L34-L39
jfadich/json-property
src/JsonPropertyTrait.php
JsonPropertyTrait.jsonManager
private function jsonManager() { if($this->jsonManager === null) $this->jsonManager = new JsonManager($this, $this->jsonProperty); return $this->jsonManager; }
php
private function jsonManager() { if($this->jsonManager === null) $this->jsonManager = new JsonManager($this, $this->jsonProperty); return $this->jsonManager; }
[ "private", "function", "jsonManager", "(", ")", "{", "if", "(", "$", "this", "->", "jsonManager", "===", "null", ")", "$", "this", "->", "jsonManager", "=", "new", "JsonManager", "(", "$", "this", ",", "$", "this", "->", "jsonProperty", ")", ";", "retu...
Get the JsonManager instance @return JsonManager
[ "Get", "the", "JsonManager", "instance" ]
train
https://github.com/jfadich/json-property/blob/3c11ac731a7bc206529058a94047eeafa5827b15/src/JsonPropertyTrait.php#L64-L70
ekyna/PaymentBundle
Install/PaymentInstaller.php
PaymentInstaller.createImageFolder
private function createImageFolder() { $em = $this->container->get('ekyna_payment.method.manager'); $folderRepository = $this->container->get('ekyna_media.folder.repository'); if (null === $rootFolder = $folderRepository->findRoot()) { throw new \RuntimeException('Can\'t find root folder. Please run MediaBundle installer first.'); } $name = 'Payment method'; $paymentFolder = $folderRepository->findOneBy([ 'name' => $name, 'parent' => $rootFolder, ]); if (null !== $paymentFolder) { return $paymentFolder; } $paymentFolder = new Folder(); $paymentFolder ->setName($name) ->setParent($rootFolder) ; $em->persist($paymentFolder); $em->flush(); return $paymentFolder; }
php
private function createImageFolder() { $em = $this->container->get('ekyna_payment.method.manager'); $folderRepository = $this->container->get('ekyna_media.folder.repository'); if (null === $rootFolder = $folderRepository->findRoot()) { throw new \RuntimeException('Can\'t find root folder. Please run MediaBundle installer first.'); } $name = 'Payment method'; $paymentFolder = $folderRepository->findOneBy([ 'name' => $name, 'parent' => $rootFolder, ]); if (null !== $paymentFolder) { return $paymentFolder; } $paymentFolder = new Folder(); $paymentFolder ->setName($name) ->setParent($rootFolder) ; $em->persist($paymentFolder); $em->flush(); return $paymentFolder; }
[ "private", "function", "createImageFolder", "(", ")", "{", "$", "em", "=", "$", "this", "->", "container", "->", "get", "(", "'ekyna_payment.method.manager'", ")", ";", "$", "folderRepository", "=", "$", "this", "->", "container", "->", "get", "(", "'ekyna_m...
Creates the payment images folder. @return Folder
[ "Creates", "the", "payment", "images", "folder", "." ]
train
https://github.com/ekyna/PaymentBundle/blob/1b4f4103b28e3a4f8dbfac2cbd872d728238f4d1/Install/PaymentInstaller.php#L52-L81
ekyna/PaymentBundle
Install/PaymentInstaller.php
PaymentInstaller.createPaymentMethods
private function createPaymentMethods(OutputInterface $output) { $em = $this->container->get('ekyna_payment.method.manager'); //$registry = $this->container->get('payum'); $methodRepository = $this->container->get('ekyna_payment.method.repository'); $mediaRepository = $this->container->get('ekyna_media.media.repository'); $folder = $this->createImageFolder(); $imageDir = realpath(__DIR__.'/../Resources/asset/img'); $methods = [ 'Chèque' => [ 'offline', 'cheque.png', '<p>Veuillez adresser votre chèque à l\'ordre de ...</p>', true ], 'Virement' => [ 'offline', 'virement.png', '<p>Veuillez adresser votre virement à l\'ordre de ...</p>', true ], 'Paypal' => [ 'paypal_express_checkout_nvp', 'paypal.png', '<p>Réglez avec votre compte paypal, ou votre carte bancaire.</p>', false ], ]; if (class_exists('Ekyna\Bundle\PayumSipsBundle\EkynaPayumSipsBundle')) { $methods['Carte bancaire'] = [ 'atos_sips', 'credit-card.png', '<p>Réglez avec votre carte bancaire.</p>', false ]; } foreach ($methods as $name => $options) { $output->write(sprintf( '- <comment>%s</comment> %s ', $name, str_pad('.', 44 - mb_strlen($name), '.', STR_PAD_LEFT) )); // TODO check that factory method exists if (null !== $method = $methodRepository->findOneBy(['gatewayName' => $name])) { $output->writeln('already exists.'); continue; } $source = $imageDir.'/'.$options[1]; if (!file_exists($source)) { throw new \Exception(sprintf('File "%s" does not exists.', $source)); } $target = sys_get_temp_dir() . '/' . $options[1]; if (!copy($source, $target)) { throw new \Exception(sprintf('Failed to copy "%s" into "%s".', $source, $target)); } /** @var \Ekyna\Bundle\MediaBundle\Model\MediaInterface $image */ $image = $mediaRepository->createNew(); $image ->setFile(new File($target)) ->setFolder($folder) ->setTitle($name) ->setType(MediaTypes::IMAGE) ; /** @var \Ekyna\Bundle\PaymentBundle\Entity\Method $method */ $method = $methodRepository->createNew(); $method ->setGatewayName($name) ->setFactoryName($options[0]) ->setMedia($image) ->setDescription($options[2]) ->setEnabled($options[3]) ; $em->persist($method); $output->writeln('created.'); } $em->flush(); }
php
private function createPaymentMethods(OutputInterface $output) { $em = $this->container->get('ekyna_payment.method.manager'); //$registry = $this->container->get('payum'); $methodRepository = $this->container->get('ekyna_payment.method.repository'); $mediaRepository = $this->container->get('ekyna_media.media.repository'); $folder = $this->createImageFolder(); $imageDir = realpath(__DIR__.'/../Resources/asset/img'); $methods = [ 'Chèque' => [ 'offline', 'cheque.png', '<p>Veuillez adresser votre chèque à l\'ordre de ...</p>', true ], 'Virement' => [ 'offline', 'virement.png', '<p>Veuillez adresser votre virement à l\'ordre de ...</p>', true ], 'Paypal' => [ 'paypal_express_checkout_nvp', 'paypal.png', '<p>Réglez avec votre compte paypal, ou votre carte bancaire.</p>', false ], ]; if (class_exists('Ekyna\Bundle\PayumSipsBundle\EkynaPayumSipsBundle')) { $methods['Carte bancaire'] = [ 'atos_sips', 'credit-card.png', '<p>Réglez avec votre carte bancaire.</p>', false ]; } foreach ($methods as $name => $options) { $output->write(sprintf( '- <comment>%s</comment> %s ', $name, str_pad('.', 44 - mb_strlen($name), '.', STR_PAD_LEFT) )); // TODO check that factory method exists if (null !== $method = $methodRepository->findOneBy(['gatewayName' => $name])) { $output->writeln('already exists.'); continue; } $source = $imageDir.'/'.$options[1]; if (!file_exists($source)) { throw new \Exception(sprintf('File "%s" does not exists.', $source)); } $target = sys_get_temp_dir() . '/' . $options[1]; if (!copy($source, $target)) { throw new \Exception(sprintf('Failed to copy "%s" into "%s".', $source, $target)); } /** @var \Ekyna\Bundle\MediaBundle\Model\MediaInterface $image */ $image = $mediaRepository->createNew(); $image ->setFile(new File($target)) ->setFolder($folder) ->setTitle($name) ->setType(MediaTypes::IMAGE) ; /** @var \Ekyna\Bundle\PaymentBundle\Entity\Method $method */ $method = $methodRepository->createNew(); $method ->setGatewayName($name) ->setFactoryName($options[0]) ->setMedia($image) ->setDescription($options[2]) ->setEnabled($options[3]) ; $em->persist($method); $output->writeln('created.'); } $em->flush(); }
[ "private", "function", "createPaymentMethods", "(", "OutputInterface", "$", "output", ")", "{", "$", "em", "=", "$", "this", "->", "container", "->", "get", "(", "'ekyna_payment.method.manager'", ")", ";", "//$registry = $this->container->get('payum');", "$", "methodR...
Creates default payment methods entities. @param OutputInterface $output @throws \Exception
[ "Creates", "default", "payment", "methods", "entities", "." ]
train
https://github.com/ekyna/PaymentBundle/blob/1b4f4103b28e3a4f8dbfac2cbd872d728238f4d1/Install/PaymentInstaller.php#L89-L176
mglaman/toolstack-helper
src/Stacks/Drupal.php
Drupal.inspect
public function inspect($dir) { if ($this->source($dir)) { return true; } elseif ($this->built($dir)) { return true; } return false; }
php
public function inspect($dir) { if ($this->source($dir)) { return true; } elseif ($this->built($dir)) { return true; } return false; }
[ "public", "function", "inspect", "(", "$", "dir", ")", "{", "if", "(", "$", "this", "->", "source", "(", "$", "dir", ")", ")", "{", "return", "true", ";", "}", "elseif", "(", "$", "this", "->", "built", "(", "$", "dir", ")", ")", "{", "return",...
{@inheritdoc}
[ "{" ]
train
https://github.com/mglaman/toolstack-helper/blob/1b3b93ac284a6c77286988b5d41c75509dd3dc20/src/Stacks/Drupal.php#L24-L32
mglaman/toolstack-helper
src/Stacks/Drupal.php
Drupal.getMakefiles
public function getMakefiles($dir) { $finder = new Finder(); $finder->in($dir) ->files() ->depth('< 1') ->name('*.make*'); return $finder; }
php
public function getMakefiles($dir) { $finder = new Finder(); $finder->in($dir) ->files() ->depth('< 1') ->name('*.make*'); return $finder; }
[ "public", "function", "getMakefiles", "(", "$", "dir", ")", "{", "$", "finder", "=", "new", "Finder", "(", ")", ";", "$", "finder", "->", "in", "(", "$", "dir", ")", "->", "files", "(", ")", "->", "depth", "(", "'< 1'", ")", "->", "name", "(", ...
Return Finder with all makefiles in directory. @param $dir @return \Symfony\Component\Finder\Finder
[ "Return", "Finder", "with", "all", "makefiles", "in", "directory", "." ]
train
https://github.com/mglaman/toolstack-helper/blob/1b3b93ac284a6c77286988b5d41c75509dd3dc20/src/Stacks/Drupal.php#L41-L49
mglaman/toolstack-helper
src/Stacks/Drupal.php
Drupal.source
public function source($dir) { // Check if unbuilt Drupal foreach ($this->getMakefiles($dir) as $file) { $f = fopen($file, 'r'); $peek = fread($f, 1000); fclose($f); if (strpos($peek, 'api') !== FALSE && strpos($peek, 'core') !== FALSE) { return true; } } return false; }
php
public function source($dir) { // Check if unbuilt Drupal foreach ($this->getMakefiles($dir) as $file) { $f = fopen($file, 'r'); $peek = fread($f, 1000); fclose($f); if (strpos($peek, 'api') !== FALSE && strpos($peek, 'core') !== FALSE) { return true; } } return false; }
[ "public", "function", "source", "(", "$", "dir", ")", "{", "// Check if unbuilt Drupal", "foreach", "(", "$", "this", "->", "getMakefiles", "(", "$", "dir", ")", "as", "$", "file", ")", "{", "$", "f", "=", "fopen", "(", "$", "file", ",", "'r'", ")", ...
Checks if Drupal project, but source. @param $dir @return bool
[ "Checks", "if", "Drupal", "project", "but", "source", "." ]
train
https://github.com/mglaman/toolstack-helper/blob/1b3b93ac284a6c77286988b5d41c75509dd3dc20/src/Stacks/Drupal.php#L58-L71
mglaman/toolstack-helper
src/Stacks/Drupal.php
Drupal.built
public function built($dir) { $file = $dir . '/index.php'; if ($this->fs->exists($file)) { $f = fopen($file, 'r'); $beginning = fread($f, 3178); fclose($f); if (strpos($beginning, 'Drupal') !== false) { return true; } } return false; }
php
public function built($dir) { $file = $dir . '/index.php'; if ($this->fs->exists($file)) { $f = fopen($file, 'r'); $beginning = fread($f, 3178); fclose($f); if (strpos($beginning, 'Drupal') !== false) { return true; } } return false; }
[ "public", "function", "built", "(", "$", "dir", ")", "{", "$", "file", "=", "$", "dir", ".", "'/index.php'", ";", "if", "(", "$", "this", "->", "fs", "->", "exists", "(", "$", "file", ")", ")", "{", "$", "f", "=", "fopen", "(", "$", "file", "...
Checks if there is a built Drupal project. @param $dir @return bool
[ "Checks", "if", "there", "is", "a", "built", "Drupal", "project", ".", "@param", "$dir" ]
train
https://github.com/mglaman/toolstack-helper/blob/1b3b93ac284a6c77286988b5d41c75509dd3dc20/src/Stacks/Drupal.php#L79-L91
mglaman/toolstack-helper
src/Stacks/Drupal.php
Drupal.version
public function version($dir) { if ($this->source($dir)) { // Check if unbuilt Drupal foreach ($this->getMakefiles($dir) as $file) { $f = fopen($file, 'r'); $peek = fread($f, 1000); fclose($f); foreach (explode(PHP_EOL, $peek) as $line) { preg_match("/core\s*(:|=)\s*\"?(\d.\w?)\"?$/", $line, $output_array); if (!empty($output_array)) { return ($output_array[2] == self::DRUPAL7) ? self::DRUPAL7 : self::DRUPAL8; } } } } elseif ($this->built($dir)) { return (file_exists($dir . '/core/composer.json')) ? self::DRUPAL8 : self::DRUPAL7; } return null; }
php
public function version($dir) { if ($this->source($dir)) { // Check if unbuilt Drupal foreach ($this->getMakefiles($dir) as $file) { $f = fopen($file, 'r'); $peek = fread($f, 1000); fclose($f); foreach (explode(PHP_EOL, $peek) as $line) { preg_match("/core\s*(:|=)\s*\"?(\d.\w?)\"?$/", $line, $output_array); if (!empty($output_array)) { return ($output_array[2] == self::DRUPAL7) ? self::DRUPAL7 : self::DRUPAL8; } } } } elseif ($this->built($dir)) { return (file_exists($dir . '/core/composer.json')) ? self::DRUPAL8 : self::DRUPAL7; } return null; }
[ "public", "function", "version", "(", "$", "dir", ")", "{", "if", "(", "$", "this", "->", "source", "(", "$", "dir", ")", ")", "{", "// Check if unbuilt Drupal", "foreach", "(", "$", "this", "->", "getMakefiles", "(", "$", "dir", ")", "as", "$", "fil...
Determine the Drupal version (make sources or built.) @param $dir @return null|string
[ "Determine", "the", "Drupal", "version", "(", "make", "sources", "or", "built", ".", ")" ]
train
https://github.com/mglaman/toolstack-helper/blob/1b3b93ac284a6c77286988b5d41c75509dd3dc20/src/Stacks/Drupal.php#L99-L117
freialib/fenrir.system
src/Statement/Pdo.php
PdoStatement.execute
function execute() { try { $this->stmt->execute(); } catch (\Exception $pdo_exception) { $message = $pdo_exception->getMessage(); $message .= "\n".$this->formatQuery($this->query); throw new Panic($message, 500, $pdo_exception); } return $this; }
php
function execute() { try { $this->stmt->execute(); } catch (\Exception $pdo_exception) { $message = $pdo_exception->getMessage(); $message .= "\n".$this->formatQuery($this->query); throw new Panic($message, 500, $pdo_exception); } return $this; }
[ "function", "execute", "(", ")", "{", "try", "{", "$", "this", "->", "stmt", "->", "execute", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "pdo_exception", ")", "{", "$", "message", "=", "$", "pdo_exception", "->", "getMessage", "(", ")"...
Execute the statement. @return static $this
[ "Execute", "the", "statement", "." ]
train
https://github.com/freialib/fenrir.system/blob/388d360dbc3bc6dcf85b09bb06e08a2dce8f3ec8/src/Statement/Pdo.php#L135-L146
freialib/fenrir.system
src/Statement/Pdo.php
PdoStatement.fetch_entry
function fetch_entry() { $result = $this->stmt->fetch(\PDO::FETCH_ASSOC); if ($result === false) { return null; } else { // succesfully retrieved statement return $result; } }
php
function fetch_entry() { $result = $this->stmt->fetch(\PDO::FETCH_ASSOC); if ($result === false) { return null; } else { // succesfully retrieved statement return $result; } }
[ "function", "fetch_entry", "(", ")", "{", "$", "result", "=", "$", "this", "->", "stmt", "->", "fetch", "(", "\\", "PDO", "::", "FETCH_ASSOC", ")", ";", "if", "(", "$", "result", "===", "false", ")", "{", "return", "null", ";", "}", "else", "{", ...
Fetch row as associative. @return array or null
[ "Fetch", "row", "as", "associative", "." ]
train
https://github.com/freialib/fenrir.system/blob/388d360dbc3bc6dcf85b09bb06e08a2dce8f3ec8/src/Statement/Pdo.php#L162-L171
edineibauer/link-control
public/src/LinkControl/Sessao.php
Sessao.cookieLogin
private function cookieLogin() { $beforeDate = date('Y-m-d H:i:s', strtotime("-2 months", strtotime(date("Y-m-d H:i:s")))); $token = new TableCrud("usuarios"); $token->load("token", $_COOKIE['token']); if ($token->exist() && $token->status === 1 && $token->token_expira > $beforeDate) { //Obtém os dados de login $_SESSION['userlogin'] = $token->getDados(); //Atualiza tempo de expiração do Token no banco $token->token_expira = date("Y-m-d H:i:s"); $token->save(); //seta cookies para 2 meses de validade setcookie("token", $token, time() + (86400 * 30 * 3), "/"); // 2 meses de cookie //redireciona para dashboard header("Location: " . HOME . "dashboard"); } else { //remove cookie não integro $this->unsetCookie(); } }
php
private function cookieLogin() { $beforeDate = date('Y-m-d H:i:s', strtotime("-2 months", strtotime(date("Y-m-d H:i:s")))); $token = new TableCrud("usuarios"); $token->load("token", $_COOKIE['token']); if ($token->exist() && $token->status === 1 && $token->token_expira > $beforeDate) { //Obtém os dados de login $_SESSION['userlogin'] = $token->getDados(); //Atualiza tempo de expiração do Token no banco $token->token_expira = date("Y-m-d H:i:s"); $token->save(); //seta cookies para 2 meses de validade setcookie("token", $token, time() + (86400 * 30 * 3), "/"); // 2 meses de cookie //redireciona para dashboard header("Location: " . HOME . "dashboard"); } else { //remove cookie não integro $this->unsetCookie(); } }
[ "private", "function", "cookieLogin", "(", ")", "{", "$", "beforeDate", "=", "date", "(", "'Y-m-d H:i:s'", ",", "strtotime", "(", "\"-2 months\"", ",", "strtotime", "(", "date", "(", "\"Y-m-d H:i:s\"", ")", ")", ")", ")", ";", "$", "token", "=", "new", "...
Verifica se as informações mantidas no cookie condizem com um login válido
[ "Verifica", "se", "as", "informações", "mantidas", "no", "cookie", "condizem", "com", "um", "login", "válido" ]
train
https://github.com/edineibauer/link-control/blob/3e603d6f92cd2217c4fe9bfe89315b851a218961/public/src/LinkControl/Sessao.php#L24-L49
edineibauer/link-control
public/src/LinkControl/Sessao.php
Sessao.unsetCookie
private function unsetCookie() { $token = new TableCrud("usuarios"); $token->load("token", $_COOKIE['token']); if ($token->exist()) { //Remove token da base de dados $token->token = null; $token->token_expira = null; $token->save(); } //remove cookie setcookie("token", 0, time() - 1, "/"); }
php
private function unsetCookie() { $token = new TableCrud("usuarios"); $token->load("token", $_COOKIE['token']); if ($token->exist()) { //Remove token da base de dados $token->token = null; $token->token_expira = null; $token->save(); } //remove cookie setcookie("token", 0, time() - 1, "/"); }
[ "private", "function", "unsetCookie", "(", ")", "{", "$", "token", "=", "new", "TableCrud", "(", "\"usuarios\"", ")", ";", "$", "token", "->", "load", "(", "\"token\"", ",", "$", "_COOKIE", "[", "'token'", "]", ")", ";", "if", "(", "$", "token", "->"...
Remover Cookie
[ "Remover", "Cookie" ]
train
https://github.com/edineibauer/link-control/blob/3e603d6f92cd2217c4fe9bfe89315b851a218961/public/src/LinkControl/Sessao.php#L54-L68
stubbles/stubbles-dbal
src/main/php/config/PropertyBasedDatabaseConfigurations.php
PropertyBasedDatabaseConfigurations.contain
public function contain(string $id): bool { if ($this->properties()->containSection($id)) { return true; } return $this->hasFallback(); }
php
public function contain(string $id): bool { if ($this->properties()->containSection($id)) { return true; } return $this->hasFallback(); }
[ "public", "function", "contain", "(", "string", "$", "id", ")", ":", "bool", "{", "if", "(", "$", "this", "->", "properties", "(", ")", "->", "containSection", "(", "$", "id", ")", ")", "{", "return", "true", ";", "}", "return", "$", "this", "->", ...
checks whether database configuration for given id exists @param string $id @return bool
[ "checks", "whether", "database", "configuration", "for", "given", "id", "exists" ]
train
https://github.com/stubbles/stubbles-dbal/blob/b42a589025a9e511b40a2798ac84df94d6451c36/src/main/php/config/PropertyBasedDatabaseConfigurations.php#L82-L89
stubbles/stubbles-dbal
src/main/php/config/PropertyBasedDatabaseConfigurations.php
PropertyBasedDatabaseConfigurations.get
public function get(string $id) { if (!$this->properties()->containSection($id)) { if (!$this->hasFallback()) { throw new \OutOfBoundsException('No database configuration known for database requested with id ' . $id); } $id = DatabaseConfiguration::DEFAULT_ID; } if (!$this->properties()->containValue($id, 'dsn')) { throw new \LogicException('Missing dsn property in database configuration with id ' . $id); } return DatabaseConfiguration::fromArray( $id, $this->properties()->value($id, 'dsn'), $this->properties()->section($id) ); }
php
public function get(string $id) { if (!$this->properties()->containSection($id)) { if (!$this->hasFallback()) { throw new \OutOfBoundsException('No database configuration known for database requested with id ' . $id); } $id = DatabaseConfiguration::DEFAULT_ID; } if (!$this->properties()->containValue($id, 'dsn')) { throw new \LogicException('Missing dsn property in database configuration with id ' . $id); } return DatabaseConfiguration::fromArray( $id, $this->properties()->value($id, 'dsn'), $this->properties()->section($id) ); }
[ "public", "function", "get", "(", "string", "$", "id", ")", "{", "if", "(", "!", "$", "this", "->", "properties", "(", ")", "->", "containSection", "(", "$", "id", ")", ")", "{", "if", "(", "!", "$", "this", "->", "hasFallback", "(", ")", ")", ...
returns database configuration with given id @param string $id @return \stubbles\db\config\DatabaseConfiguration @throws \OutOfBoundsException in case no configuration for given id is found and fallback is disabled @throws \LogicException in case the found configuration misses the dsn property
[ "returns", "database", "configuration", "with", "given", "id" ]
train
https://github.com/stubbles/stubbles-dbal/blob/b42a589025a9e511b40a2798ac84df94d6451c36/src/main/php/config/PropertyBasedDatabaseConfigurations.php#L99-L118
stubbles/stubbles-dbal
src/main/php/config/PropertyBasedDatabaseConfigurations.php
PropertyBasedDatabaseConfigurations.properties
protected function properties(): Properties { if (null === $this->dbProperties) { $this->dbProperties = Properties::fromFile($this->configPath . '/' . $this->descriptor . '.ini'); } return $this->dbProperties; }
php
protected function properties(): Properties { if (null === $this->dbProperties) { $this->dbProperties = Properties::fromFile($this->configPath . '/' . $this->descriptor . '.ini'); } return $this->dbProperties; }
[ "protected", "function", "properties", "(", ")", ":", "Properties", "{", "if", "(", "null", "===", "$", "this", "->", "dbProperties", ")", "{", "$", "this", "->", "dbProperties", "=", "Properties", "::", "fromFile", "(", "$", "this", "->", "configPath", ...
reads properties if not done yet @return \stubbles\values\Properties
[ "reads", "properties", "if", "not", "done", "yet" ]
train
https://github.com/stubbles/stubbles-dbal/blob/b42a589025a9e511b40a2798ac84df94d6451c36/src/main/php/config/PropertyBasedDatabaseConfigurations.php#L125-L132
stubbles/stubbles-dbal
src/main/php/config/PropertyBasedDatabaseConfigurations.php
PropertyBasedDatabaseConfigurations.getIterator
public function getIterator(): \Traversable { return new MappingIterator( $this->properties(), function($value, $key) { return $this->get($key); } ); }
php
public function getIterator(): \Traversable { return new MappingIterator( $this->properties(), function($value, $key) { return $this->get($key); } ); }
[ "public", "function", "getIterator", "(", ")", ":", "\\", "Traversable", "{", "return", "new", "MappingIterator", "(", "$", "this", "->", "properties", "(", ")", ",", "function", "(", "$", "value", ",", "$", "key", ")", "{", "return", "$", "this", "->"...
returns an external iterator @return \Traversable
[ "returns", "an", "external", "iterator" ]
train
https://github.com/stubbles/stubbles-dbal/blob/b42a589025a9e511b40a2798ac84df94d6451c36/src/main/php/config/PropertyBasedDatabaseConfigurations.php#L139-L148
MasterkeyInformatica/browser-kit
Client.php
Client.insulate
public function insulate($insulated = true) { if ($insulated && !class_exists('Symfony\\Component\\Process\\Process')) { throw new \RuntimeException('Unable to isolate requests as the Symfony Process Component is not installed.'); } $this->insulated = (bool) $insulated; }
php
public function insulate($insulated = true) { if ($insulated && !class_exists('Symfony\\Component\\Process\\Process')) { throw new \RuntimeException('Unable to isolate requests as the Symfony Process Component is not installed.'); } $this->insulated = (bool) $insulated; }
[ "public", "function", "insulate", "(", "$", "insulated", "=", "true", ")", "{", "if", "(", "$", "insulated", "&&", "!", "class_exists", "(", "'Symfony\\\\Component\\\\Process\\\\Process'", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to...
Sets the insulated flag. @param bool $insulated Whether to insulate the requests or not @throws \RuntimeException When Symfony Process Component is not installed
[ "Sets", "the", "insulated", "flag", "." ]
train
https://github.com/MasterkeyInformatica/browser-kit/blob/fd735ad31c00af54d5c060d01218aa48308557f7/Client.php#L109-L116
MasterkeyInformatica/browser-kit
Client.php
Client.doRequestInProcess
protected function doRequestInProcess($request) { $process = new PhpProcess($this->getScript($request), null, null); $process->run(); if (!$process->isSuccessful() || !preg_match('/^O\:\d+\:/', $process->getOutput())) { throw new \RuntimeException(sprintf('OUTPUT: %s ERROR OUTPUT: %s', $process->getOutput(), $process->getErrorOutput())); } return unserialize($process->getOutput()); }
php
protected function doRequestInProcess($request) { $process = new PhpProcess($this->getScript($request), null, null); $process->run(); if (!$process->isSuccessful() || !preg_match('/^O\:\d+\:/', $process->getOutput())) { throw new \RuntimeException(sprintf('OUTPUT: %s ERROR OUTPUT: %s', $process->getOutput(), $process->getErrorOutput())); } return unserialize($process->getOutput()); }
[ "protected", "function", "doRequestInProcess", "(", "$", "request", ")", "{", "$", "process", "=", "new", "PhpProcess", "(", "$", "this", "->", "getScript", "(", "$", "request", ")", ",", "null", ",", "null", ")", ";", "$", "process", "->", "run", "(",...
Makes a request in another process. @param object $request An origin request instance @return object An origin response instance @throws \RuntimeException When processing returns exit code
[ "Makes", "a", "request", "in", "another", "process", "." ]
train
https://github.com/MasterkeyInformatica/browser-kit/blob/fd735ad31c00af54d5c060d01218aa48308557f7/Client.php#L346-L356
SagittariusX/Beluga.IO
src/Beluga/IO/Path.php
Path.Combine
public static function Combine( string $basePath, string ...$next ) : string { if ( count( $next ) < 1 ) { return rtrim( $basePath, "\r\n\t /\\" ); } // Remove leading and trailing directory separators + spaces from the next items \array_walk( $next, function( &$item ) { $item = \trim( $item, '/\\ ' ); } ); return \rtrim( \rtrim( $basePath, "\r\n\t /\\" ) . \DIRECTORY_SEPARATOR . \join( DIRECTORY_SEPARATOR, $next ), '/\\' ); }
php
public static function Combine( string $basePath, string ...$next ) : string { if ( count( $next ) < 1 ) { return rtrim( $basePath, "\r\n\t /\\" ); } // Remove leading and trailing directory separators + spaces from the next items \array_walk( $next, function( &$item ) { $item = \trim( $item, '/\\ ' ); } ); return \rtrim( \rtrim( $basePath, "\r\n\t /\\" ) . \DIRECTORY_SEPARATOR . \join( DIRECTORY_SEPARATOR, $next ), '/\\' ); }
[ "public", "static", "function", "Combine", "(", "string", "$", "basePath", ",", "string", "...", "$", "next", ")", ":", "string", "{", "if", "(", "count", "(", "$", "next", ")", "<", "1", ")", "{", "return", "rtrim", "(", "$", "basePath", ",", "\"\...
Combine 2 or 3 path elements to a single path and returns it. @param string $basePath The base path. @param string[] $next The next path parts. @return string
[ "Combine", "2", "or", "3", "path", "elements", "to", "a", "single", "path", "and", "returns", "it", "." ]
train
https://github.com/SagittariusX/Beluga.IO/blob/c8af09a1b3cc8a955e43c89b70779d11b30ae29e/src/Beluga/IO/Path.php#L50-L68
SagittariusX/Beluga.IO
src/Beluga/IO/Path.php
Path.Normalize
public static function Normalize( string $path ) : string { if ( empty( static::$NoFolderSeparator ) ) { static::$NoFolderSeparator = File::IS_WIN ? '/' : '\\'; } $tmpPath = ( File::IS_WIN ? \trim( \str_replace( static::$NoFolderSeparator, \DIRECTORY_SEPARATOR, $path ), \DIRECTORY_SEPARATOR ) : \rtrim( \str_replace( static::$NoFolderSeparator, \DIRECTORY_SEPARATOR, $path ), \DIRECTORY_SEPARATOR ) ); // return the resulting path and replace /./ or \.\ with a single directory separator return str_replace( \DIRECTORY_SEPARATOR . '.' . \DIRECTORY_SEPARATOR, \DIRECTORY_SEPARATOR, $tmpPath ); }
php
public static function Normalize( string $path ) : string { if ( empty( static::$NoFolderSeparator ) ) { static::$NoFolderSeparator = File::IS_WIN ? '/' : '\\'; } $tmpPath = ( File::IS_WIN ? \trim( \str_replace( static::$NoFolderSeparator, \DIRECTORY_SEPARATOR, $path ), \DIRECTORY_SEPARATOR ) : \rtrim( \str_replace( static::$NoFolderSeparator, \DIRECTORY_SEPARATOR, $path ), \DIRECTORY_SEPARATOR ) ); // return the resulting path and replace /./ or \.\ with a single directory separator return str_replace( \DIRECTORY_SEPARATOR . '.' . \DIRECTORY_SEPARATOR, \DIRECTORY_SEPARATOR, $tmpPath ); }
[ "public", "static", "function", "Normalize", "(", "string", "$", "path", ")", ":", "string", "{", "if", "(", "empty", "(", "static", "::", "$", "NoFolderSeparator", ")", ")", "{", "static", "::", "$", "NoFolderSeparator", "=", "File", "::", "IS_WIN", "?"...
Normalizes a path to directory separators, used by current system. @param string $path @return string
[ "Normalizes", "a", "path", "to", "directory", "separators", "used", "by", "current", "system", "." ]
train
https://github.com/SagittariusX/Beluga.IO/blob/c8af09a1b3cc8a955e43c89b70779d11b30ae29e/src/Beluga/IO/Path.php#L76-L110
SagittariusX/Beluga.IO
src/Beluga/IO/Path.php
Path.RemoveWorkingDir
public static function RemoveWorkingDir( string $path = null ) : string { if ( \is_null( $path ) ) { return ''; } $wd = '~^' . \preg_quote( static::Unixize( \getcwd() ) . '/' ) . '~'; return \preg_replace( $wd, '', static::Unixize( $path ) ); }
php
public static function RemoveWorkingDir( string $path = null ) : string { if ( \is_null( $path ) ) { return ''; } $wd = '~^' . \preg_quote( static::Unixize( \getcwd() ) . '/' ) . '~'; return \preg_replace( $wd, '', static::Unixize( $path ) ); }
[ "public", "static", "function", "RemoveWorkingDir", "(", "string", "$", "path", "=", "null", ")", ":", "string", "{", "if", "(", "\\", "is_null", "(", "$", "path", ")", ")", "{", "return", "''", ";", "}", "$", "wd", "=", "'~^'", ".", "\\", "preg_qu...
Removes the current working directory from defined path, if it starts with it. @param string $path @return string
[ "Removes", "the", "current", "working", "directory", "from", "defined", "path", "if", "it", "starts", "with", "it", "." ]
train
https://github.com/SagittariusX/Beluga.IO/blob/c8af09a1b3cc8a955e43c89b70779d11b30ae29e/src/Beluga/IO/Path.php#L172-L184
SagittariusX/Beluga.IO
src/Beluga/IO/Path.php
Path.GetPathinfo
public static function GetPathinfo( string $path, $infoType = null ) { $info = [ 'dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '' ]; $pathInfo = []; if ( preg_match( '%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $pathInfo ) ) { if ( array_key_exists( 1, $pathInfo ) ) { $info[ 'dirname' ] = $pathInfo[ 1 ]; } if ( array_key_exists( 2, $pathInfo ) ) { $info[ 'basename' ] = $pathInfo[ 2 ]; } if ( array_key_exists( 5, $pathInfo ) ) { $info[ 'extension' ] = $pathInfo[ 5 ]; } if ( array_key_exists( 3, $pathInfo ) ) { $info[ 'filename' ] = $pathInfo[ 3 ]; } } switch ( $infoType ) { case PATHINFO_DIRNAME: case 'dirname': return $info[ 'dirname' ]; case PATHINFO_BASENAME: case 'basename': return $info[ 'basename' ]; case PATHINFO_EXTENSION: case 'extension': return $info[ 'extension' ]; case PATHINFO_FILENAME: case 'filename': return $info[ 'filename' ]; default: return $info; } }
php
public static function GetPathinfo( string $path, $infoType = null ) { $info = [ 'dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '' ]; $pathInfo = []; if ( preg_match( '%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $pathInfo ) ) { if ( array_key_exists( 1, $pathInfo ) ) { $info[ 'dirname' ] = $pathInfo[ 1 ]; } if ( array_key_exists( 2, $pathInfo ) ) { $info[ 'basename' ] = $pathInfo[ 2 ]; } if ( array_key_exists( 5, $pathInfo ) ) { $info[ 'extension' ] = $pathInfo[ 5 ]; } if ( array_key_exists( 3, $pathInfo ) ) { $info[ 'filename' ] = $pathInfo[ 3 ]; } } switch ( $infoType ) { case PATHINFO_DIRNAME: case 'dirname': return $info[ 'dirname' ]; case PATHINFO_BASENAME: case 'basename': return $info[ 'basename' ]; case PATHINFO_EXTENSION: case 'extension': return $info[ 'extension' ]; case PATHINFO_FILENAME: case 'filename': return $info[ 'filename' ]; default: return $info; } }
[ "public", "static", "function", "GetPathinfo", "(", "string", "$", "path", ",", "$", "infoType", "=", "null", ")", "{", "$", "info", "=", "[", "'dirname'", "=>", "''", ",", "'basename'", "=>", "''", ",", "'extension'", "=>", "''", ",", "'filename'", "=...
This is a multi byte safe pathinfo() replacement. Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe. Works similarly to the one in PHP >= 5.2.0 @link http://www.php.net/manual/en/function.pathinfo.php#107461 @param string $path A filename or path, does not need to exist as a file @param integer|string $infoType Either a PATHINFO_* constant, or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2 @return string|array
[ "This", "is", "a", "multi", "byte", "safe", "pathinfo", "()", "replacement", "." ]
train
https://github.com/SagittariusX/Beluga.IO/blob/c8af09a1b3cc8a955e43c89b70779d11b30ae29e/src/Beluga/IO/Path.php#L199-L242
TiMESPLiNTER/tsFramework
src/ch/timesplinter/core/ErrorHandler.php
ErrorHandler.handlePHPError
public function handlePHPError($error_number, $error, $error_file, $error_line) { // respect the current error_reporting setting if((error_reporting() & $error_number) === 0) return; throw new PHPException($error_number, $error, $error_file, $error_line); }
php
public function handlePHPError($error_number, $error, $error_file, $error_line) { // respect the current error_reporting setting if((error_reporting() & $error_number) === 0) return; throw new PHPException($error_number, $error, $error_file, $error_line); }
[ "public", "function", "handlePHPError", "(", "$", "error_number", ",", "$", "error", ",", "$", "error_file", ",", "$", "error_line", ")", "{", "// respect the current error_reporting setting", "if", "(", "(", "error_reporting", "(", ")", "&", "$", "error_number", ...
Catches all the PHP errors and convert them into a PHP exception @param int $error_number @param string $error @param string $error_file @param int $error_line @throws PHPException
[ "Catches", "all", "the", "PHP", "errors", "and", "convert", "them", "into", "a", "PHP", "exception" ]
train
https://github.com/TiMESPLiNTER/tsFramework/blob/b3b9fd98f6d456a9e571015877ecca203786fd0c/src/ch/timesplinter/core/ErrorHandler.php#L34-L41
TiMESPLiNTER/tsFramework
src/ch/timesplinter/core/ErrorHandler.php
ErrorHandler.handleException
public function handleException(\Exception $e) { $environment = $this->core->getCurrentDomain()->environment; if(isset($this->core->getSettings()->errorhandling->controller->$environment) === true) { $controller = FrameworkUtils::stringToClassName($this->core->getSettings()->errorhandling->controller->$environment); $pc = new $controller->className($this->core, $this->core->getHttpRequest(), new Route()); $httpResponse = call_user_func(array($pc, $controller->methodName), $e); } else { $content = null; $httpErrorCode = ($e instanceof HttpException)?$e->getCode():500; $exceptionStr = null; if($this->core->getSettings()->core->environments->$environment->debug === true) { $exceptionStr = "\n<pre>"; $exceptionStr .= '<b>Uncaught exception' . "\n" . '==================</b>' . "\n"; $exceptionStr .= 'Type: ' . get_class($e) . "\n"; $exceptionStr .= 'Message: ' . $e->getMessage() . ' (Code: ' . $e->getCode() . ')' . "\n"; $exceptionStr .= 'Thrown in: ' . $e->getFile() . ' (Line: ' . $e->getLine() . ")\n\n"; $exceptionStr .= $e->getTraceAsString(); $exceptionStr .= '</pre>'; } $errorStr = $httpErrorCode . ' ' . HttpResponse::getHttpStatusString($httpErrorCode); $content = "<!doctype html>\n<html>\n<head>\n<title>" . $errorStr . "</title>\n</head>\n<body>\n<h1>" . $errorStr . "</h1>" . $exceptionStr . "\n</body>\n</html>"; $httpResponse = new HttpResponse($httpErrorCode, $content); } $httpResponse->send(); exit; }
php
public function handleException(\Exception $e) { $environment = $this->core->getCurrentDomain()->environment; if(isset($this->core->getSettings()->errorhandling->controller->$environment) === true) { $controller = FrameworkUtils::stringToClassName($this->core->getSettings()->errorhandling->controller->$environment); $pc = new $controller->className($this->core, $this->core->getHttpRequest(), new Route()); $httpResponse = call_user_func(array($pc, $controller->methodName), $e); } else { $content = null; $httpErrorCode = ($e instanceof HttpException)?$e->getCode():500; $exceptionStr = null; if($this->core->getSettings()->core->environments->$environment->debug === true) { $exceptionStr = "\n<pre>"; $exceptionStr .= '<b>Uncaught exception' . "\n" . '==================</b>' . "\n"; $exceptionStr .= 'Type: ' . get_class($e) . "\n"; $exceptionStr .= 'Message: ' . $e->getMessage() . ' (Code: ' . $e->getCode() . ')' . "\n"; $exceptionStr .= 'Thrown in: ' . $e->getFile() . ' (Line: ' . $e->getLine() . ")\n\n"; $exceptionStr .= $e->getTraceAsString(); $exceptionStr .= '</pre>'; } $errorStr = $httpErrorCode . ' ' . HttpResponse::getHttpStatusString($httpErrorCode); $content = "<!doctype html>\n<html>\n<head>\n<title>" . $errorStr . "</title>\n</head>\n<body>\n<h1>" . $errorStr . "</h1>" . $exceptionStr . "\n</body>\n</html>"; $httpResponse = new HttpResponse($httpErrorCode, $content); } $httpResponse->send(); exit; }
[ "public", "function", "handleException", "(", "\\", "Exception", "$", "e", ")", "{", "$", "environment", "=", "$", "this", "->", "core", "->", "getCurrentDomain", "(", ")", "->", "environment", ";", "if", "(", "isset", "(", "$", "this", "->", "core", "...
Default stub for print an exception @param \Exception $e
[ "Default", "stub", "for", "print", "an", "exception" ]
train
https://github.com/TiMESPLiNTER/tsFramework/blob/b3b9fd98f6d456a9e571015877ecca203786fd0c/src/ch/timesplinter/core/ErrorHandler.php#L48-L86
Clastic-Contrib/BlogBundle
Form/Module/BlogFormExtension.php
BlogFormExtension.buildForm
public function buildForm(FormBuilderInterface $builder, array $options) { $this->getTabHelper($builder)->findTab('general') ->add('introduction', WysiwygType::class, [ 'label' => 'blog.form.tab.general.field.introduction', ]) ->add('body', WysiwygType::class, [ 'label' => 'blog.form.tab.general.field.body', ]); $this->getTabHelper($builder) ->createTab('category', 'blog.form.tab.category.label') ->add('categories', EntityMultiSelectType::class, [ 'label' => 'blog.form.tab.category.field.categories', 'class' => 'ClasticBlogBundle:Category', 'required' => false, ]); }
php
public function buildForm(FormBuilderInterface $builder, array $options) { $this->getTabHelper($builder)->findTab('general') ->add('introduction', WysiwygType::class, [ 'label' => 'blog.form.tab.general.field.introduction', ]) ->add('body', WysiwygType::class, [ 'label' => 'blog.form.tab.general.field.body', ]); $this->getTabHelper($builder) ->createTab('category', 'blog.form.tab.category.label') ->add('categories', EntityMultiSelectType::class, [ 'label' => 'blog.form.tab.category.field.categories', 'class' => 'ClasticBlogBundle:Category', 'required' => false, ]); }
[ "public", "function", "buildForm", "(", "FormBuilderInterface", "$", "builder", ",", "array", "$", "options", ")", "{", "$", "this", "->", "getTabHelper", "(", "$", "builder", ")", "->", "findTab", "(", "'general'", ")", "->", "add", "(", "'introduction'", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/Clastic-Contrib/BlogBundle/blob/b2e749ec87783d98b54e1562a6dea1b2921c9dc8/Form/Module/BlogFormExtension.php#L27-L44
buildok/validator
src/types/StringValidator.php
StringValidator.maxLength
private function maxLength() { $max = mb_strlen($this->value); if (!$ret = $max <= $this->options->max) { $this->error(1); } return $ret; }
php
private function maxLength() { $max = mb_strlen($this->value); if (!$ret = $max <= $this->options->max) { $this->error(1); } return $ret; }
[ "private", "function", "maxLength", "(", ")", "{", "$", "max", "=", "mb_strlen", "(", "$", "this", "->", "value", ")", ";", "if", "(", "!", "$", "ret", "=", "$", "max", "<=", "$", "this", "->", "options", "->", "max", ")", "{", "$", "this", "->...
Check max length @return boolean
[ "Check", "max", "length" ]
train
https://github.com/buildok/validator/blob/3612ebca7901c84be2f26f641470933e468a0811/src/types/StringValidator.php#L42-L50
buildok/validator
src/types/StringValidator.php
StringValidator.minLength
private function minLength() { $min = mb_strlen($this->value); if (!$ret = $min >= $this->options->min) { $this->error(2); } return $ret; }
php
private function minLength() { $min = mb_strlen($this->value); if (!$ret = $min >= $this->options->min) { $this->error(2); } return $ret; }
[ "private", "function", "minLength", "(", ")", "{", "$", "min", "=", "mb_strlen", "(", "$", "this", "->", "value", ")", ";", "if", "(", "!", "$", "ret", "=", "$", "min", ">=", "$", "this", "->", "options", "->", "min", ")", "{", "$", "this", "->...
Check min length @return boolean
[ "Check", "min", "length" ]
train
https://github.com/buildok/validator/blob/3612ebca7901c84be2f26f641470933e468a0811/src/types/StringValidator.php#L56-L64
PenoaksDev/Milky-Framework
src/Milky/Account/Traits/AuthenticatesUsers.php
AuthenticatesUsers.showLoginForm
public function showLoginForm() { $view = property_exists( $this, 'loginView' ) ? $this->loginView : 'auth.authenticate'; if ( View::exists( $view ) ) return View::render( $view ); return View::render( 'auth.login' ); }
php
public function showLoginForm() { $view = property_exists( $this, 'loginView' ) ? $this->loginView : 'auth.authenticate'; if ( View::exists( $view ) ) return View::render( $view ); return View::render( 'auth.login' ); }
[ "public", "function", "showLoginForm", "(", ")", "{", "$", "view", "=", "property_exists", "(", "$", "this", ",", "'loginView'", ")", "?", "$", "this", "->", "loginView", ":", "'auth.authenticate'", ";", "if", "(", "View", "::", "exists", "(", "$", "view...
Show the application login form. @return Response
[ "Show", "the", "application", "login", "form", "." ]
train
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Account/Traits/AuthenticatesUsers.php#L44-L51
PenoaksDev/Milky-Framework
src/Milky/Account/Traits/AuthenticatesUsers.php
AuthenticatesUsers.login
public function login( Request $request ) { $this->validateLogin( $request ); // If the class is using the ThrottlesLogins trait, we can automatically throttle // the login attempts for this application. We'll key this by the username and // the IP address of the client making these requests into this application. $throttles = $this->isUsingThrottlesLoginsTrait(); if ( $throttles && $lockedOut = $this->hasTooManyLoginAttempts( $request ) ) { $this->fireLockoutEvent( $request ); // return $this->sendLockoutResponse( $request ); } $credentials = $this->getCredentials( $request ); if ( Acct::guard( $this->getGuard() )->attempt( $credentials, $request->has( 'remember' ) ) ) return $this->handleUserWasAuthenticated( $request, $throttles ); // If the login attempt was unsuccessful we will increment the number of attempts // to login and redirect the user back to the login form. Of course, when this // user surpasses their maximum number of attempts they will get locked out. if ( $throttles && !$lockedOut ) $this->incrementLoginAttempts( $request ); return $this->sendFailedLoginResponse( $request ); }
php
public function login( Request $request ) { $this->validateLogin( $request ); // If the class is using the ThrottlesLogins trait, we can automatically throttle // the login attempts for this application. We'll key this by the username and // the IP address of the client making these requests into this application. $throttles = $this->isUsingThrottlesLoginsTrait(); if ( $throttles && $lockedOut = $this->hasTooManyLoginAttempts( $request ) ) { $this->fireLockoutEvent( $request ); // return $this->sendLockoutResponse( $request ); } $credentials = $this->getCredentials( $request ); if ( Acct::guard( $this->getGuard() )->attempt( $credentials, $request->has( 'remember' ) ) ) return $this->handleUserWasAuthenticated( $request, $throttles ); // If the login attempt was unsuccessful we will increment the number of attempts // to login and redirect the user back to the login form. Of course, when this // user surpasses their maximum number of attempts they will get locked out. if ( $throttles && !$lockedOut ) $this->incrementLoginAttempts( $request ); return $this->sendFailedLoginResponse( $request ); }
[ "public", "function", "login", "(", "Request", "$", "request", ")", "{", "$", "this", "->", "validateLogin", "(", "$", "request", ")", ";", "// If the class is using the ThrottlesLogins trait, we can automatically throttle", "// the login attempts for this application. We'll ke...
Handle a login request to the application. @param Request $request @return Response
[ "Handle", "a", "login", "request", "to", "the", "application", "." ]
train
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Account/Traits/AuthenticatesUsers.php#L70-L97
PenoaksDev/Milky-Framework
src/Milky/Account/Traits/AuthenticatesUsers.php
AuthenticatesUsers.handleUserWasAuthenticated
protected function handleUserWasAuthenticated( Request $request, $throttles ) { if ( $throttles ) $this->clearLoginAttempts( $request ); if ( method_exists( $this, 'authenticated' ) ) return $this->authenticated( $request, Acct::guard( $this->getGuard() )->acct() ); return Redirect::intended( $this->redirectPath() ); }
php
protected function handleUserWasAuthenticated( Request $request, $throttles ) { if ( $throttles ) $this->clearLoginAttempts( $request ); if ( method_exists( $this, 'authenticated' ) ) return $this->authenticated( $request, Acct::guard( $this->getGuard() )->acct() ); return Redirect::intended( $this->redirectPath() ); }
[ "protected", "function", "handleUserWasAuthenticated", "(", "Request", "$", "request", ",", "$", "throttles", ")", "{", "if", "(", "$", "throttles", ")", "$", "this", "->", "clearLoginAttempts", "(", "$", "request", ")", ";", "if", "(", "method_exists", "(",...
Send the response after the user was authenticated. @param Request $request @param bool $throttles @return Response
[ "Send", "the", "response", "after", "the", "user", "was", "authenticated", "." ]
train
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Account/Traits/AuthenticatesUsers.php#L120-L129
PenoaksDev/Milky-Framework
src/Milky/Account/Traits/AuthenticatesUsers.php
AuthenticatesUsers.sendFailedLoginResponse
protected function sendFailedLoginResponse( Request $request ) { return Redirect::back()->withInput( $request->only( $this->loginUsername(), 'remember' ) )->withErrors( [ $this->loginUsername() => $this->getFailedLoginMessage(), ] ); }
php
protected function sendFailedLoginResponse( Request $request ) { return Redirect::back()->withInput( $request->only( $this->loginUsername(), 'remember' ) )->withErrors( [ $this->loginUsername() => $this->getFailedLoginMessage(), ] ); }
[ "protected", "function", "sendFailedLoginResponse", "(", "Request", "$", "request", ")", "{", "return", "Redirect", "::", "back", "(", ")", "->", "withInput", "(", "$", "request", "->", "only", "(", "$", "this", "->", "loginUsername", "(", ")", ",", "'reme...
Get the failed login response instance. @param Request $request @return Response
[ "Get", "the", "failed", "login", "response", "instance", "." ]
train
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Account/Traits/AuthenticatesUsers.php#L137-L142
PenoaksDev/Milky-Framework
src/Milky/Account/Traits/AuthenticatesUsers.php
AuthenticatesUsers.logout
public function logout() { Acct::guard( $this->getGuard() )->logout(); return Redirect::to( property_exists( $this, 'redirectAfterLogout' ) ? $this->redirectAfterLogout : '/' )->withMessages( [ 'success' => "You are now logged out." ] ); }
php
public function logout() { Acct::guard( $this->getGuard() )->logout(); return Redirect::to( property_exists( $this, 'redirectAfterLogout' ) ? $this->redirectAfterLogout : '/' )->withMessages( [ 'success' => "You are now logged out." ] ); }
[ "public", "function", "logout", "(", ")", "{", "Acct", "::", "guard", "(", "$", "this", "->", "getGuard", "(", ")", ")", "->", "logout", "(", ")", ";", "return", "Redirect", "::", "to", "(", "property_exists", "(", "$", "this", ",", "'redirectAfterLogo...
Log the user out of the application. @return Response
[ "Log", "the", "user", "out", "of", "the", "application", "." ]
train
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Account/Traits/AuthenticatesUsers.php#L180-L185
ciims/ciims-modules-hybridauth
components/RemoteUserIdentity.php
RemoteUserIdentity.authenticate
public function authenticate($force=false) { // Set the error code first $this->errorCode == NULL; // Check that the user isn't NULL, or that they're not in a locked state if ($this->_user == NULL) $this->errorCode = Yii_DEBUG ? self::ERROR_USERNAME_INVALID : self::ERROR_UNKNOWN_IDENTITY; else if ($this->_user->status == Users::BANNED || $this->_user->status == Users::INACTIVE || $this->_user->status == Users::PENDING_INVITATION) $this->errorCode=self::ERROR_UNKNOWN_IDENTITY; // The user has already been provided to us, so immediately log the user in using that information $this->setIdentity(); return !$this->errorCode; }
php
public function authenticate($force=false) { // Set the error code first $this->errorCode == NULL; // Check that the user isn't NULL, or that they're not in a locked state if ($this->_user == NULL) $this->errorCode = Yii_DEBUG ? self::ERROR_USERNAME_INVALID : self::ERROR_UNKNOWN_IDENTITY; else if ($this->_user->status == Users::BANNED || $this->_user->status == Users::INACTIVE || $this->_user->status == Users::PENDING_INVITATION) $this->errorCode=self::ERROR_UNKNOWN_IDENTITY; // The user has already been provided to us, so immediately log the user in using that information $this->setIdentity(); return !$this->errorCode; }
[ "public", "function", "authenticate", "(", "$", "force", "=", "false", ")", "{", "// Set the error code first", "$", "this", "->", "errorCode", "==", "NULL", ";", "// Check that the user isn't NULL, or that they're not in a locked state", "if", "(", "$", "this", "->", ...
Overload of CiiUserIdentity::authenticate to authenticate the user TODO: Is this secure? We're not really authenticating _anything_ in this class, just using what we have provider @param boolean $force Unused variable for class extension only @return boolean $this->errorCode
[ "Overload", "of", "CiiUserIdentity", "::", "authenticate", "to", "authenticate", "the", "user", "TODO", ":", "Is", "this", "secure?", "We", "re", "not", "really", "authenticating", "_anything_", "in", "this", "class", "just", "using", "what", "we", "have", "pr...
train
https://github.com/ciims/ciims-modules-hybridauth/blob/417b2682bf3468dd509164a9b773d886359a7aec/components/RemoteUserIdentity.php#L45-L60
swiftphp/config
src/ConfigurationFactory.php
ConfigurationFactory.create
public static function create($configFile,$baseDir="",$userDir="",$extConfigs=[]) { //配置文件 $pathInfo=pathinfo($configFile); $_configFile=$pathInfo["dirname"]."/".$pathInfo["filename"]; $phpConfigFile=$_configFile.".php"; $xmlConfigFile=$_configFile.".xml"; $_configFile=file_exists($phpConfigFile)?$phpConfigFile:$xmlConfigFile; if(!file_exists($_configFile)){ throw new \Exception("Fail to load configuration file '".$configFile."'!"); } //如果缓存存在,则直接返回实例 $configKey=$_configFile; if(array_key_exists($configKey, self::$m_configs)){ return self::returnConfig(self::$m_configs[$configKey],$baseDir,$userDir,$extConfigs); } //从php配置文件读取配置:如果php配置文件存在且修改时间大于所有的xml配置文件 if(file_exists($phpConfigFile)){ //从php读取配置 $config=new PhpConfiguration($phpConfigFile); //如果xml配置文件不存在,则直接从php配置直接返回 if(!file_exists($xmlConfigFile)){ self::$m_configs[$configKey]=$config; return self::returnConfig($config,$baseDir,$userDir,$extConfigs); } //如果xml配置文件存在,则要检查文件最后修改时间 $phpTime=filemtime($phpConfigFile); $overrided=false; foreach ($config->getConfigValues(self::$m_configFilesKey) as $f){ if(file_exists($f) && filemtime($f) > $phpTime){ $overrided=true; } } //php文件较新且非调试模式下 if(!$overrided && !self::$m_debug){ self::$m_configs[$configKey]=$config; return self::returnConfig($config,$baseDir,$userDir,$extConfigs); } } //从xml配置读取配置,并持久化到php if(file_exists($xmlConfigFile)){ $config=new XmlConfiguration($xmlConfigFile); self::$m_configs[$configKey]=$config; self::dump2PhpFile($config, $phpConfigFile); } //返回实例 if(array_key_exists($configKey, self::$m_configs)){ return self::returnConfig(self::$m_configs[$configKey],$baseDir,$userDir,$extConfigs); } return null; }
php
public static function create($configFile,$baseDir="",$userDir="",$extConfigs=[]) { //配置文件 $pathInfo=pathinfo($configFile); $_configFile=$pathInfo["dirname"]."/".$pathInfo["filename"]; $phpConfigFile=$_configFile.".php"; $xmlConfigFile=$_configFile.".xml"; $_configFile=file_exists($phpConfigFile)?$phpConfigFile:$xmlConfigFile; if(!file_exists($_configFile)){ throw new \Exception("Fail to load configuration file '".$configFile."'!"); } //如果缓存存在,则直接返回实例 $configKey=$_configFile; if(array_key_exists($configKey, self::$m_configs)){ return self::returnConfig(self::$m_configs[$configKey],$baseDir,$userDir,$extConfigs); } //从php配置文件读取配置:如果php配置文件存在且修改时间大于所有的xml配置文件 if(file_exists($phpConfigFile)){ //从php读取配置 $config=new PhpConfiguration($phpConfigFile); //如果xml配置文件不存在,则直接从php配置直接返回 if(!file_exists($xmlConfigFile)){ self::$m_configs[$configKey]=$config; return self::returnConfig($config,$baseDir,$userDir,$extConfigs); } //如果xml配置文件存在,则要检查文件最后修改时间 $phpTime=filemtime($phpConfigFile); $overrided=false; foreach ($config->getConfigValues(self::$m_configFilesKey) as $f){ if(file_exists($f) && filemtime($f) > $phpTime){ $overrided=true; } } //php文件较新且非调试模式下 if(!$overrided && !self::$m_debug){ self::$m_configs[$configKey]=$config; return self::returnConfig($config,$baseDir,$userDir,$extConfigs); } } //从xml配置读取配置,并持久化到php if(file_exists($xmlConfigFile)){ $config=new XmlConfiguration($xmlConfigFile); self::$m_configs[$configKey]=$config; self::dump2PhpFile($config, $phpConfigFile); } //返回实例 if(array_key_exists($configKey, self::$m_configs)){ return self::returnConfig(self::$m_configs[$configKey],$baseDir,$userDir,$extConfigs); } return null; }
[ "public", "static", "function", "create", "(", "$", "configFile", ",", "$", "baseDir", "=", "\"\"", ",", "$", "userDir", "=", "\"\"", ",", "$", "extConfigs", "=", "[", "]", ")", "{", "//配置文件\r", "$", "pathInfo", "=", "pathinfo", "(", "$", "configFile",...
创建配置实例 @param string $configFile 入口配置文件名 @param string $baseDir 应用根目录 @param string $userDir 用户根目录 @param array $extConfigs 附加扩展的配置(section,name,value形式的数组) @return IConfiguration
[ "创建配置实例" ]
train
https://github.com/swiftphp/config/blob/c93e1a45d0aa9fdcb7d583f3eadfc60785c039df/src/ConfigurationFactory.php#L49-L106
swiftphp/config
src/ConfigurationFactory.php
ConfigurationFactory.returnConfig
private static function returnConfig(IConfiguration $config,$baseDir="",$userDir="",$extConfigs=[]) { $config->setBaseDir($baseDir); $config->setUserDir($userDir); if(!empty($extConfigs)){ foreach ($extConfigs as $ext){ $config->addConfigValue($ext["section"], $ext["name"], $ext["value"]); } } return $config; }
php
private static function returnConfig(IConfiguration $config,$baseDir="",$userDir="",$extConfigs=[]) { $config->setBaseDir($baseDir); $config->setUserDir($userDir); if(!empty($extConfigs)){ foreach ($extConfigs as $ext){ $config->addConfigValue($ext["section"], $ext["name"], $ext["value"]); } } return $config; }
[ "private", "static", "function", "returnConfig", "(", "IConfiguration", "$", "config", ",", "$", "baseDir", "=", "\"\"", ",", "$", "userDir", "=", "\"\"", ",", "$", "extConfigs", "=", "[", "]", ")", "{", "$", "config", "->", "setBaseDir", "(", "$", "ba...
返回的配置实例 @param IConfiguration $config @param string $baseDir @param string $userDir @param array $extConfigs @return IConfiguration
[ "返回的配置实例" ]
train
https://github.com/swiftphp/config/blob/c93e1a45d0aa9fdcb7d583f3eadfc60785c039df/src/ConfigurationFactory.php#L116-L126
swiftphp/config
src/ConfigurationFactory.php
ConfigurationFactory.dump2PhpFile
private static function dump2PhpFile(IConfiguration $config,$file) { $values=$config->getAllValues(); $values[self::$m_configFilesKey]=$config->getConfigFiles(); $content=var_export($values, TRUE); $content="<?php\r\nreturn\r\n".$content.";"; file_put_contents($file, $content); }
php
private static function dump2PhpFile(IConfiguration $config,$file) { $values=$config->getAllValues(); $values[self::$m_configFilesKey]=$config->getConfigFiles(); $content=var_export($values, TRUE); $content="<?php\r\nreturn\r\n".$content.";"; file_put_contents($file, $content); }
[ "private", "static", "function", "dump2PhpFile", "(", "IConfiguration", "$", "config", ",", "$", "file", ")", "{", "$", "values", "=", "$", "config", "->", "getAllValues", "(", ")", ";", "$", "values", "[", "self", "::", "$", "m_configFilesKey", "]", "="...
把配置内容持久化成php文件 @param IConfiguration $config @param string $file
[ "把配置内容持久化成php文件" ]
train
https://github.com/swiftphp/config/blob/c93e1a45d0aa9fdcb7d583f3eadfc60785c039df/src/ConfigurationFactory.php#L133-L140
Wedeto/Util
src/DI/DefaultFactory.php
DefaultFactory.produce
public function produce(string $class, array $args, string $selector = Injector::DEFAULT_SELECTOR, Injector $injector) { $const_name = $class . '::WDI_NO_AUTO'; if (defined($const_name) && constant($const_name) === true) { throw new DIException("Cannot instantiate $class because $class::WDI_NO_AUTO is true"); } try { $reflect = new ReflectionClass($class); $instance = null; $dc = $reflect->getDocComment(); if (!empty($dc)) { $dc = new DocComment($dc); $gen = $dc->getAnnotationTokens("generator"); if (!empty($gen)) { $instance = $this->attemptGeneratorMethod($gen, $class, $args, $selector, $injector); } } if (null === $instance) { $constructor = $reflect->getConstructor(); if (null === $constructor) return $reflect->newInstance(); if (!$constructor->isPublic()) throw new DIException("Class $class does not have a public constructor"); $constructor_args = $this->determineArgumentsFor($constructor, $class, "constructor", $args, $selector, $injector); $instance = $reflect->newInstanceArgs($constructor_args); } } catch (DIException $e) { throw new DIException("Could not instantiate class $class", 0, $e); } return $instance; }
php
public function produce(string $class, array $args, string $selector = Injector::DEFAULT_SELECTOR, Injector $injector) { $const_name = $class . '::WDI_NO_AUTO'; if (defined($const_name) && constant($const_name) === true) { throw new DIException("Cannot instantiate $class because $class::WDI_NO_AUTO is true"); } try { $reflect = new ReflectionClass($class); $instance = null; $dc = $reflect->getDocComment(); if (!empty($dc)) { $dc = new DocComment($dc); $gen = $dc->getAnnotationTokens("generator"); if (!empty($gen)) { $instance = $this->attemptGeneratorMethod($gen, $class, $args, $selector, $injector); } } if (null === $instance) { $constructor = $reflect->getConstructor(); if (null === $constructor) return $reflect->newInstance(); if (!$constructor->isPublic()) throw new DIException("Class $class does not have a public constructor"); $constructor_args = $this->determineArgumentsFor($constructor, $class, "constructor", $args, $selector, $injector); $instance = $reflect->newInstanceArgs($constructor_args); } } catch (DIException $e) { throw new DIException("Could not instantiate class $class", 0, $e); } return $instance; }
[ "public", "function", "produce", "(", "string", "$", "class", ",", "array", "$", "args", ",", "string", "$", "selector", "=", "Injector", "::", "DEFAULT_SELECTOR", ",", "Injector", "$", "injector", ")", "{", "$", "const_name", "=", "$", "class", ".", "':...
The Factory interface: call the provided function to do the factory job.
[ "The", "Factory", "interface", ":", "call", "the", "provided", "function", "to", "do", "the", "factory", "job", "." ]
train
https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/DI/DefaultFactory.php#L42-L85
Wedeto/Util
src/DI/DefaultFactory.php
DefaultFactory.attemptGeneratorMethod
protected function attemptGeneratorMethod(array $tokens, string $class, array $args, string $selector, Injector $injector) { $fn_name = $tokens[0] ?? ""; if (!method_exists($class, $fn_name)) throw new DIException("Annotated generator method $class::$fn_name does not exist"); $method = new ReflectionMethod($class, $fn_name); if (!$method->isStatic() || !$method->isPublic()) throw new DIException("Generator method $class::$fn_name must be public and static"); $method_args = $this->determineArgumentsFor($method, $class, $fn_name, $args, $selector, $injector); $instance = $method->invokeArgs(null, $method_args); return $instance; }
php
protected function attemptGeneratorMethod(array $tokens, string $class, array $args, string $selector, Injector $injector) { $fn_name = $tokens[0] ?? ""; if (!method_exists($class, $fn_name)) throw new DIException("Annotated generator method $class::$fn_name does not exist"); $method = new ReflectionMethod($class, $fn_name); if (!$method->isStatic() || !$method->isPublic()) throw new DIException("Generator method $class::$fn_name must be public and static"); $method_args = $this->determineArgumentsFor($method, $class, $fn_name, $args, $selector, $injector); $instance = $method->invokeArgs(null, $method_args); return $instance; }
[ "protected", "function", "attemptGeneratorMethod", "(", "array", "$", "tokens", ",", "string", "$", "class", ",", "array", "$", "args", ",", "string", "$", "selector", ",", "Injector", "$", "injector", ")", "{", "$", "fn_name", "=", "$", "tokens", "[", "...
Attempt to create an instance using a generator method supplied by a annotation in the class' DocComment: @generator MyFactoryMethodName This method will be attempted to invoke, the arguments should therefore be instantiatable by the injector.
[ "Attempt", "to", "create", "an", "instance", "using", "a", "generator", "method", "supplied", "by", "a", "annotation", "in", "the", "class", "DocComment", ":" ]
train
https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/DI/DefaultFactory.php#L96-L110
Wedeto/Util
src/DI/DefaultFactory.php
DefaultFactory.determineArgumentsFor
protected function determineArgumentsFor( ReflectionMethod $method, string $class, string $method_name, array $args, string $selector, Injector $injector ) { $params = $method->getParameters(); $method_args = []; // Determine values for each parameter $used_optional = false; foreach ($params as $param) { $name = $param->getName(); if (array_key_exists($name, $args)) { $method_args[] = $args[$name]; continue; } $pclass = $param->getClass(); if (null !== $pclass) { $instance = $injector->getInstance($pclass->getName(), $selector); $method_args[] = $instance; continue; } if ($param->isDefaultValueAvailable()) { $default = $param->getDefaultValue(); $method_args[] = $default; continue; } if ($param->isOptional()) { // This and all remaining parameters have a default value break; } throw new DIException("Unable to determine value for parameter $name for $method_name of '$class'"); } // There should be a argument for every parameter return $method_args; }
php
protected function determineArgumentsFor( ReflectionMethod $method, string $class, string $method_name, array $args, string $selector, Injector $injector ) { $params = $method->getParameters(); $method_args = []; // Determine values for each parameter $used_optional = false; foreach ($params as $param) { $name = $param->getName(); if (array_key_exists($name, $args)) { $method_args[] = $args[$name]; continue; } $pclass = $param->getClass(); if (null !== $pclass) { $instance = $injector->getInstance($pclass->getName(), $selector); $method_args[] = $instance; continue; } if ($param->isDefaultValueAvailable()) { $default = $param->getDefaultValue(); $method_args[] = $default; continue; } if ($param->isOptional()) { // This and all remaining parameters have a default value break; } throw new DIException("Unable to determine value for parameter $name for $method_name of '$class'"); } // There should be a argument for every parameter return $method_args; }
[ "protected", "function", "determineArgumentsFor", "(", "ReflectionMethod", "$", "method", ",", "string", "$", "class", ",", "string", "$", "method_name", ",", "array", "$", "args", ",", "string", "$", "selector", ",", "Injector", "$", "injector", ")", "{", "...
Find arguments for a method
[ "Find", "arguments", "for", "a", "method" ]
train
https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/DI/DefaultFactory.php#L115-L165
nirou8/php-multiple-saml
lib/Saml2/LogoutRequest.php
OneLogin_Saml2_LogoutRequest.getID
public static function getID($request) { if ($request instanceof DOMDocument) { $dom = $request; } else { $dom = new DOMDocument(); $dom = OneLogin_Saml2_Utils::loadXML($dom, $request); } $id = $dom->documentElement->getAttribute('ID'); return $id; }
php
public static function getID($request) { if ($request instanceof DOMDocument) { $dom = $request; } else { $dom = new DOMDocument(); $dom = OneLogin_Saml2_Utils::loadXML($dom, $request); } $id = $dom->documentElement->getAttribute('ID'); return $id; }
[ "public", "static", "function", "getID", "(", "$", "request", ")", "{", "if", "(", "$", "request", "instanceof", "DOMDocument", ")", "{", "$", "dom", "=", "$", "request", ";", "}", "else", "{", "$", "dom", "=", "new", "DOMDocument", "(", ")", ";", ...
Returns the ID of the Logout Request. @param string|DOMDocument $request Logout Request Message @return string ID
[ "Returns", "the", "ID", "of", "the", "Logout", "Request", "." ]
train
https://github.com/nirou8/php-multiple-saml/blob/7eb5786e678db7d45459ce3441fa187946ae9a3b/lib/Saml2/LogoutRequest.php#L154-L165
squareproton/Bond
src/Bond/Database/Enum.php
Enum.getValues
public function getValues( $name ) { if( !isset( $this->enums[$name] ) ) { throw new UnknownEnumException($name); } return $this->enums[$name]; }
php
public function getValues( $name ) { if( !isset( $this->enums[$name] ) ) { throw new UnknownEnumException($name); } return $this->enums[$name]; }
[ "public", "function", "getValues", "(", "$", "name", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "enums", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "UnknownEnumException", "(", "$", "name", ")", ";", "}", "return", "$", ...
Public accessor for enum options @param string @return array Allowed values
[ "Public", "accessor", "for", "enum", "options" ]
train
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Database/Enum.php#L36-L42
squareproton/Bond
src/Bond/Database/Enum.php
Enum.isValid
public function isValid( $name, $value = null ) { if( !isset( $this->enums[$name] ) ) { return false; } elseif( $value === null ) { return true; } return !isset( $value ) || in_array( $value, $this->enums[$name] ); }
php
public function isValid( $name, $value = null ) { if( !isset( $this->enums[$name] ) ) { return false; } elseif( $value === null ) { return true; } return !isset( $value ) || in_array( $value, $this->enums[$name] ); }
[ "public", "function", "isValid", "(", "$", "name", ",", "$", "value", "=", "null", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "enums", "[", "$", "name", "]", ")", ")", "{", "return", "false", ";", "}", "elseif", "(", "$", "value...
Is valid check @param string enum name @param string value @return bool
[ "Is", "valid", "check" ]
train
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Database/Enum.php#L60-L68
squareproton/Bond
src/Bond/Database/Enum.php
Enum.getRandomValue
public function getRandomValue( $name ) { if( !isset( $this->enums[$name] ) ) { throw new UnknownEnumException($name); } return $this->enums[$name][array_rand($this->enums[$name])]; }
php
public function getRandomValue( $name ) { if( !isset( $this->enums[$name] ) ) { throw new UnknownEnumException($name); } return $this->enums[$name][array_rand($this->enums[$name])]; }
[ "public", "function", "getRandomValue", "(", "$", "name", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "enums", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "UnknownEnumException", "(", "$", "name", ")", ";", "}", "return", "...
Get a random value from a enum. Primarily used by the import script @return string
[ "Get", "a", "random", "value", "from", "a", "enum", ".", "Primarily", "used", "by", "the", "import", "script" ]
train
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Database/Enum.php#L74-L80
eureka-framework/component-http
src/Http/Message/ResponseSender.php
ResponseSender.writeStatus
private function writeStatus() { $string = $this->response->getProtocolVersion() . ' ' . $this->response->getStatusCode() . ' ' . $this->response->getReasonPhrase(); header($string, true, $this->response->getStatusCode()); }
php
private function writeStatus() { $string = $this->response->getProtocolVersion() . ' ' . $this->response->getStatusCode() . ' ' . $this->response->getReasonPhrase(); header($string, true, $this->response->getStatusCode()); }
[ "private", "function", "writeStatus", "(", ")", "{", "$", "string", "=", "$", "this", "->", "response", "->", "getProtocolVersion", "(", ")", ".", "' '", ".", "$", "this", "->", "response", "->", "getStatusCode", "(", ")", ".", "' '", ".", "$", "this",...
Write response status @return void
[ "Write", "response", "status" ]
train
https://github.com/eureka-framework/component-http/blob/698c3b73581a9703a9c932890c57e50f8774607a/src/Http/Message/ResponseSender.php#L51-L55
eureka-framework/component-http
src/Http/Message/ResponseSender.php
ResponseSender.writeHeaders
private function writeHeaders() { $headers = $this->response->getHeaders(); foreach ($headers as $name => $list) { header("$name: " . implode(', ', $list)); } }
php
private function writeHeaders() { $headers = $this->response->getHeaders(); foreach ($headers as $name => $list) { header("$name: " . implode(', ', $list)); } }
[ "private", "function", "writeHeaders", "(", ")", "{", "$", "headers", "=", "$", "this", "->", "response", "->", "getHeaders", "(", ")", ";", "foreach", "(", "$", "headers", "as", "$", "name", "=>", "$", "list", ")", "{", "header", "(", "\"$name: \"", ...
Write headers. @return void
[ "Write", "headers", "." ]
train
https://github.com/eureka-framework/component-http/blob/698c3b73581a9703a9c932890c57e50f8774607a/src/Http/Message/ResponseSender.php#L62-L68
rafrsr/lib-array2object
src/Parser/DateTimeParser.php
DateTimeParser.toObjectValue
public function toObjectValue($value, $type, \ReflectionProperty $property, $object) { if (is_string($value) && ($type === 'DateTime' || $type === '\DateTime')) { return new \DateTime($value); } return $value; }
php
public function toObjectValue($value, $type, \ReflectionProperty $property, $object) { if (is_string($value) && ($type === 'DateTime' || $type === '\DateTime')) { return new \DateTime($value); } return $value; }
[ "public", "function", "toObjectValue", "(", "$", "value", ",", "$", "type", ",", "\\", "ReflectionProperty", "$", "property", ",", "$", "object", ")", "{", "if", "(", "is_string", "(", "$", "value", ")", "&&", "(", "$", "type", "===", "'DateTime'", "||...
{@inheritdoc}
[ "{" ]
train
https://github.com/rafrsr/lib-array2object/blob/d15db63b5f5740dbc7c2213373320445785856ef/src/Parser/DateTimeParser.php#L28-L35
rafrsr/lib-array2object
src/Parser/DateTimeParser.php
DateTimeParser.toArrayValue
public function toArrayValue($value, $type, \ReflectionProperty $property, $object) { if ($value instanceof \DateTime) { return $value->format('Y-m-d H:i:s'); } return $value; }
php
public function toArrayValue($value, $type, \ReflectionProperty $property, $object) { if ($value instanceof \DateTime) { return $value->format('Y-m-d H:i:s'); } return $value; }
[ "public", "function", "toArrayValue", "(", "$", "value", ",", "$", "type", ",", "\\", "ReflectionProperty", "$", "property", ",", "$", "object", ")", "{", "if", "(", "$", "value", "instanceof", "\\", "DateTime", ")", "{", "return", "$", "value", "->", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/rafrsr/lib-array2object/blob/d15db63b5f5740dbc7c2213373320445785856ef/src/Parser/DateTimeParser.php#L40-L47
flextype-components/notification
Notification.php
Notification.get
public static function get(string $key) { return isset(Notification::$notifications[$key]) ? Notification::$notifications[$key] : null; }
php
public static function get(string $key) { return isset(Notification::$notifications[$key]) ? Notification::$notifications[$key] : null; }
[ "public", "static", "function", "get", "(", "string", "$", "key", ")", "{", "return", "isset", "(", "Notification", "::", "$", "notifications", "[", "$", "key", "]", ")", "?", "Notification", "::", "$", "notifications", "[", "$", "key", "]", ":", "null...
Returns a specific variable from the Notifications array. echo Notification::get('success'); echo Notification::get('errors'); @param string $key Variable name @return mixed
[ "Returns", "a", "specific", "variable", "from", "the", "Notifications", "array", "." ]
train
https://github.com/flextype-components/notification/blob/5a813df5a455a06efab672ae19ca1ce106584c16/Notification.php#L40-L43
flextype-components/notification
Notification.php
Notification.set
public static function set(string $key, $value) : void { $_SESSION[Notification::SESSION_KEY][$key] = $value; }
php
public static function set(string $key, $value) : void { $_SESSION[Notification::SESSION_KEY][$key] = $value; }
[ "public", "static", "function", "set", "(", "string", "$", "key", ",", "$", "value", ")", ":", "void", "{", "$", "_SESSION", "[", "Notification", "::", "SESSION_KEY", "]", "[", "$", "key", "]", "=", "$", "value", ";", "}" ]
Adds specific variable to the Notifications array. Notification::set('success', 'Data has been saved with success!'); Notification::set('errors', 'Data not saved!'); @param string $key Variable name @param mixed $value Variable value
[ "Adds", "specific", "variable", "to", "the", "Notifications", "array", "." ]
train
https://github.com/flextype-components/notification/blob/5a813df5a455a06efab672ae19ca1ce106584c16/Notification.php#L54-L57
flextype-components/notification
Notification.php
Notification.init
public static function init() : void { if ( ! empty($_SESSION[Notification::SESSION_KEY]) && is_array($_SESSION[Notification::SESSION_KEY])) { Notification::$notifications = $_SESSION[Notification::SESSION_KEY]; } $_SESSION[Notification::SESSION_KEY] = []; }
php
public static function init() : void { if ( ! empty($_SESSION[Notification::SESSION_KEY]) && is_array($_SESSION[Notification::SESSION_KEY])) { Notification::$notifications = $_SESSION[Notification::SESSION_KEY]; } $_SESSION[Notification::SESSION_KEY] = []; }
[ "public", "static", "function", "init", "(", ")", ":", "void", "{", "if", "(", "!", "empty", "(", "$", "_SESSION", "[", "Notification", "::", "SESSION_KEY", "]", ")", "&&", "is_array", "(", "$", "_SESSION", "[", "Notification", "::", "SESSION_KEY", "]", ...
Initializes the Notification service. Notification::init(); This will read notification/flash data from the $_SESSION variable and load it into the $this->previous array.
[ "Initializes", "the", "Notification", "service", "." ]
train
https://github.com/flextype-components/notification/blob/5a813df5a455a06efab672ae19ca1ce106584c16/Notification.php#L93-L100
emmb14/CMessage
src/CMessage/CMessage.php
CMessage.addMessage
public function addMessage($message, $type) { if (isset($_SESSION[$this->sessionKey])) { $messages = $_SESSION[$this->sessionKey]; } $messages[] = [ 'message' => $message, 'type' => $type, ]; $_SESSION[$this->sessionKey] = $messages; }
php
public function addMessage($message, $type) { if (isset($_SESSION[$this->sessionKey])) { $messages = $_SESSION[$this->sessionKey]; } $messages[] = [ 'message' => $message, 'type' => $type, ]; $_SESSION[$this->sessionKey] = $messages; }
[ "public", "function", "addMessage", "(", "$", "message", ",", "$", "type", ")", "{", "if", "(", "isset", "(", "$", "_SESSION", "[", "$", "this", "->", "sessionKey", "]", ")", ")", "{", "$", "messages", "=", "$", "_SESSION", "[", "$", "this", "->", ...
Add errormessage in the session
[ "Add", "errormessage", "in", "the", "session" ]
train
https://github.com/emmb14/CMessage/blob/7786f5acf7f92401bdc73769bc484baafe933a82/src/CMessage/CMessage.php#L25-L37
emmb14/CMessage
src/CMessage/CMessage.php
CMessage.printMessage
public function printMessage() { $messages = $_SESSION[$this->sessionKey]; $html = ''; foreach ($messages as $message){ $html .='<div id="message" class="' . $message['type'] . '"><p>' . $message['message'] . '</p></div>'; } $this->clearSession(); return $html; }
php
public function printMessage() { $messages = $_SESSION[$this->sessionKey]; $html = ''; foreach ($messages as $message){ $html .='<div id="message" class="' . $message['type'] . '"><p>' . $message['message'] . '</p></div>'; } $this->clearSession(); return $html; }
[ "public", "function", "printMessage", "(", ")", "{", "$", "messages", "=", "$", "_SESSION", "[", "$", "this", "->", "sessionKey", "]", ";", "$", "html", "=", "''", ";", "foreach", "(", "$", "messages", "as", "$", "message", ")", "{", "$", "html", "...
Print out message
[ "Print", "out", "message" ]
train
https://github.com/emmb14/CMessage/blob/7786f5acf7f92401bdc73769bc484baafe933a82/src/CMessage/CMessage.php#L74-L85
mpf-soft/admin-widgets
datatable/columns/actions/Basic.php
Basic.getString
public function getString($row, Table $table) { if (!$this->isVisible($row)) { return ""; } $options = $this->htmlOptions; if ($this->title != "") { eval("\$options['title'] = {$this->title};"); } elseif (!isset($options['title'])) { $options['title'] = ''; } if ($this->confirmation && (!$this->post)) { if ($this->jsAction) { $options['onclick'] = "if (confirm('{$this->confirmation}')) {$this->jsAction}({$row->{$this->dataProvider->getPkKey()}}, '{$this->name}', this);"; } else { $options['onclick'] = "return confirm('{$this->confirmation}');"; } } elseif ($this->jsAction) { $options['onclick'] = "return {$this->jsAction}({$row->id}, '{$this->name}', this);"; } if ('#' != $this->url) { eval("\$url = {$this->url};"); } else { $url = '#'; } if (false !== $this->post && is_array($this->post)) { $options['class'] = isset($options['class']) ? $options['class'] . ' mdata-table-post-link' : 'mdata-table-post-link'; $parsed = array(); foreach ($this->post as $name=>$value){ eval('$value = '. $value.';'); if ('{{modelKey}}' == $name){ $name = $table->dataProvider->filtersKey; } $parsed[$name] = $value; } $options['post-data'] = json_encode($parsed); if ($this->confirmation){ $options['post-confirmation'] = $this->confirmation; } } $icon = $this->getIcon($options['title'], $table); return Html::get()->link($url, $icon . $this->label, $options); }
php
public function getString($row, Table $table) { if (!$this->isVisible($row)) { return ""; } $options = $this->htmlOptions; if ($this->title != "") { eval("\$options['title'] = {$this->title};"); } elseif (!isset($options['title'])) { $options['title'] = ''; } if ($this->confirmation && (!$this->post)) { if ($this->jsAction) { $options['onclick'] = "if (confirm('{$this->confirmation}')) {$this->jsAction}({$row->{$this->dataProvider->getPkKey()}}, '{$this->name}', this);"; } else { $options['onclick'] = "return confirm('{$this->confirmation}');"; } } elseif ($this->jsAction) { $options['onclick'] = "return {$this->jsAction}({$row->id}, '{$this->name}', this);"; } if ('#' != $this->url) { eval("\$url = {$this->url};"); } else { $url = '#'; } if (false !== $this->post && is_array($this->post)) { $options['class'] = isset($options['class']) ? $options['class'] . ' mdata-table-post-link' : 'mdata-table-post-link'; $parsed = array(); foreach ($this->post as $name=>$value){ eval('$value = '. $value.';'); if ('{{modelKey}}' == $name){ $name = $table->dataProvider->filtersKey; } $parsed[$name] = $value; } $options['post-data'] = json_encode($parsed); if ($this->confirmation){ $options['post-confirmation'] = $this->confirmation; } } $icon = $this->getIcon($options['title'], $table); return Html::get()->link($url, $icon . $this->label, $options); }
[ "public", "function", "getString", "(", "$", "row", ",", "Table", "$", "table", ")", "{", "if", "(", "!", "$", "this", "->", "isVisible", "(", "$", "row", ")", ")", "{", "return", "\"\"", ";", "}", "$", "options", "=", "$", "this", "->", "htmlOpt...
Final result, a HTML Element for current action; @param Model $row @param \mpf\widgets\datatable\Table $table @return string
[ "Final", "result", "a", "HTML", "Element", "for", "current", "action", ";" ]
train
https://github.com/mpf-soft/admin-widgets/blob/92597f9a09d086664268d6b7e0111d5a5586d8c7/datatable/columns/actions/Basic.php#L149-L191
mpf-soft/admin-widgets
datatable/columns/actions/Basic.php
Basic.getIcon
public function getIcon($title, Table $table) { if ($this->icon) { $icon = str_replace(array('%DATATABLE_ASSETS%', '%SIZE%'), array($table->getAssetsURL(), $this->iconSize . 'x' . $this->iconSize), $this->icon); if ('%MPF_ASSETS%' == substr($icon, 0, 12)) { $icon = AssetsPublisher::get()->mpfAssetFile(substr($icon, 12)); } return Html::get()->image($icon, $title); } return ''; }
php
public function getIcon($title, Table $table) { if ($this->icon) { $icon = str_replace(array('%DATATABLE_ASSETS%', '%SIZE%'), array($table->getAssetsURL(), $this->iconSize . 'x' . $this->iconSize), $this->icon); if ('%MPF_ASSETS%' == substr($icon, 0, 12)) { $icon = AssetsPublisher::get()->mpfAssetFile(substr($icon, 12)); } return Html::get()->image($icon, $title); } return ''; }
[ "public", "function", "getIcon", "(", "$", "title", ",", "Table", "$", "table", ")", "{", "if", "(", "$", "this", "->", "icon", ")", "{", "$", "icon", "=", "str_replace", "(", "array", "(", "'%DATATABLE_ASSETS%'", ",", "'%SIZE%'", ")", ",", "array", ...
Get HTML img tag for icon or an empty string if there is no icon @param string $title @param \mpf\widgets\datatable\Table $table @return string
[ "Get", "HTML", "img", "tag", "for", "icon", "or", "an", "empty", "string", "if", "there", "is", "no", "icon" ]
train
https://github.com/mpf-soft/admin-widgets/blob/92597f9a09d086664268d6b7e0111d5a5586d8c7/datatable/columns/actions/Basic.php#L199-L208
mpf-soft/admin-widgets
datatable/columns/actions/Basic.php
Basic.isVisible
public function isVisible($row) { if (false === $this->visible) // check if it's visible return false; elseif (is_string($this->visible)) { $visible = true; eval("\$visible = {$this->visible};"); if (false == $visible) return false; } return true; }
php
public function isVisible($row) { if (false === $this->visible) // check if it's visible return false; elseif (is_string($this->visible)) { $visible = true; eval("\$visible = {$this->visible};"); if (false == $visible) return false; } return true; }
[ "public", "function", "isVisible", "(", "$", "row", ")", "{", "if", "(", "false", "===", "$", "this", "->", "visible", ")", "// check if it's visible", "return", "false", ";", "elseif", "(", "is_string", "(", "$", "this", "->", "visible", ")", ")", "{", ...
Checks if action is visible or not @return boolean
[ "Checks", "if", "action", "is", "visible", "or", "not" ]
train
https://github.com/mpf-soft/admin-widgets/blob/92597f9a09d086664268d6b7e0111d5a5586d8c7/datatable/columns/actions/Basic.php#L214-L224
fond-of/spryker-companies-rest-api
src/FondOfSpryker/Glue/CompaniesRestApi/Processor/Companies/CompaniesWriter.php
CompaniesWriter.createCompany
public function createCompany( RestRequestInterface $restRequest, RestCompaniesRequestAttributesTransfer $restCompaniesRequestAttributesTransfer ): RestResponseInterface { $restCompaniesResponseTransfer = $this->companiesRestApiClient->create( $restCompaniesRequestAttributesTransfer ); if (!$restCompaniesResponseTransfer->getIsSuccess()) { return $this->createSaveCompanyFailedErrorResponse($restCompaniesResponseTransfer); } return $this->createCompanySavedResponse($restCompaniesResponseTransfer); }
php
public function createCompany( RestRequestInterface $restRequest, RestCompaniesRequestAttributesTransfer $restCompaniesRequestAttributesTransfer ): RestResponseInterface { $restCompaniesResponseTransfer = $this->companiesRestApiClient->create( $restCompaniesRequestAttributesTransfer ); if (!$restCompaniesResponseTransfer->getIsSuccess()) { return $this->createSaveCompanyFailedErrorResponse($restCompaniesResponseTransfer); } return $this->createCompanySavedResponse($restCompaniesResponseTransfer); }
[ "public", "function", "createCompany", "(", "RestRequestInterface", "$", "restRequest", ",", "RestCompaniesRequestAttributesTransfer", "$", "restCompaniesRequestAttributesTransfer", ")", ":", "RestResponseInterface", "{", "$", "restCompaniesResponseTransfer", "=", "$", "this", ...
@param \Spryker\Glue\GlueApplication\Rest\Request\Data\RestRequestInterface $restRequest @param \Generated\Shared\Transfer\RestCompaniesRequestAttributesTransfer $restCompaniesRequestAttributesTransfer @return \Spryker\Glue\GlueApplication\Rest\JsonApi\RestResponseInterface
[ "@param", "\\", "Spryker", "\\", "Glue", "\\", "GlueApplication", "\\", "Rest", "\\", "Request", "\\", "Data", "\\", "RestRequestInterface", "$restRequest", "@param", "\\", "Generated", "\\", "Shared", "\\", "Transfer", "\\", "RestCompaniesRequestAttributesTransfer", ...
train
https://github.com/fond-of/spryker-companies-rest-api/blob/0df688aa37cd6d18f90ac2af0a1cbc39357d94d7/src/FondOfSpryker/Glue/CompaniesRestApi/Processor/Companies/CompaniesWriter.php#L62-L75
fond-of/spryker-companies-rest-api
src/FondOfSpryker/Glue/CompaniesRestApi/Processor/Companies/CompaniesWriter.php
CompaniesWriter.updateCompany
public function updateCompany( RestRequestInterface $restRequest, RestCompaniesRequestAttributesTransfer $restCompaniesRequestAttributesTransfer ): RestResponseInterface { $restResponse = $this->restResourceBuilder->createRestResponse(); if (!$restRequest->getResource()->getId()) { return $this->restApiError->addExternalReferenceMissingError($restResponse); } $restCompaniesRequestTransfer = new RestCompaniesRequestTransfer(); $restCompaniesRequestTransfer->setId($restRequest->getResource()->getId()) ->setRestCompaniesRequestAttributes($restCompaniesRequestAttributesTransfer); $restCompaniesResponseTransfer = $this->companiesRestApiClient->update( $restCompaniesRequestTransfer ); if (!$restCompaniesResponseTransfer->getIsSuccess()) { return $this->createSaveCompanyFailedErrorResponse($restCompaniesResponseTransfer); } return $this->createCompanySavedResponse($restCompaniesResponseTransfer); }
php
public function updateCompany( RestRequestInterface $restRequest, RestCompaniesRequestAttributesTransfer $restCompaniesRequestAttributesTransfer ): RestResponseInterface { $restResponse = $this->restResourceBuilder->createRestResponse(); if (!$restRequest->getResource()->getId()) { return $this->restApiError->addExternalReferenceMissingError($restResponse); } $restCompaniesRequestTransfer = new RestCompaniesRequestTransfer(); $restCompaniesRequestTransfer->setId($restRequest->getResource()->getId()) ->setRestCompaniesRequestAttributes($restCompaniesRequestAttributesTransfer); $restCompaniesResponseTransfer = $this->companiesRestApiClient->update( $restCompaniesRequestTransfer ); if (!$restCompaniesResponseTransfer->getIsSuccess()) { return $this->createSaveCompanyFailedErrorResponse($restCompaniesResponseTransfer); } return $this->createCompanySavedResponse($restCompaniesResponseTransfer); }
[ "public", "function", "updateCompany", "(", "RestRequestInterface", "$", "restRequest", ",", "RestCompaniesRequestAttributesTransfer", "$", "restCompaniesRequestAttributesTransfer", ")", ":", "RestResponseInterface", "{", "$", "restResponse", "=", "$", "this", "->", "restRe...
@param \Spryker\Glue\GlueApplication\Rest\Request\Data\RestRequestInterface $restRequest @param \Generated\Shared\Transfer\RestCompaniesRequestAttributesTransfer $restCompaniesRequestAttributesTransfer @return \Spryker\Glue\GlueApplication\Rest\JsonApi\RestResponseInterface
[ "@param", "\\", "Spryker", "\\", "Glue", "\\", "GlueApplication", "\\", "Rest", "\\", "Request", "\\", "Data", "\\", "RestRequestInterface", "$restRequest", "@param", "\\", "Generated", "\\", "Shared", "\\", "Transfer", "\\", "RestCompaniesRequestAttributesTransfer", ...
train
https://github.com/fond-of/spryker-companies-rest-api/blob/0df688aa37cd6d18f90ac2af0a1cbc39357d94d7/src/FondOfSpryker/Glue/CompaniesRestApi/Processor/Companies/CompaniesWriter.php#L83-L106
weareunite/unisys-transactions
src/Http/Controllers/HandleTransaction.php
HandleTransaction.addTransaction
public function addTransaction(int $id, StoreRequest $request) { /** @var HasTransactionsInterface $object */ if(!$object = $this->repository->find($id)) { abort(404); } $transaction = $object->addTransaction( $request->all() ); event(new MadeTransaction($transaction)); \Cache::tags('response')->flush(); return new TransactionResource($transaction); }
php
public function addTransaction(int $id, StoreRequest $request) { /** @var HasTransactionsInterface $object */ if(!$object = $this->repository->find($id)) { abort(404); } $transaction = $object->addTransaction( $request->all() ); event(new MadeTransaction($transaction)); \Cache::tags('response')->flush(); return new TransactionResource($transaction); }
[ "public", "function", "addTransaction", "(", "int", "$", "id", ",", "StoreRequest", "$", "request", ")", "{", "/** @var HasTransactionsInterface $object */", "if", "(", "!", "$", "object", "=", "$", "this", "->", "repository", "->", "find", "(", "$", "id", "...
Add Transaction Add transaction to given model find by model primary id @param int $id @param StoreRequest $request @return TransactionResource
[ "Add", "Transaction" ]
train
https://github.com/weareunite/unisys-transactions/blob/3bfaf6993cc209871298340f5dabbe56f1eeab5d/src/Http/Controllers/HandleTransaction.php#L26-L40
weareunite/unisys-transactions
src/Http/Controllers/HandleTransaction.php
HandleTransaction.allTransactions
public function allTransactions(int $id) { /** @var HasTransactionsInterface $object */ if(!$object = $this->repository->find($id)) { abort(404); } $transactions = $object->getLatestTransactions(); return TransactionResource::collection($transactions); }
php
public function allTransactions(int $id) { /** @var HasTransactionsInterface $object */ if(!$object = $this->repository->find($id)) { abort(404); } $transactions = $object->getLatestTransactions(); return TransactionResource::collection($transactions); }
[ "public", "function", "allTransactions", "(", "int", "$", "id", ")", "{", "/** @var HasTransactionsInterface $object */", "if", "(", "!", "$", "object", "=", "$", "this", "->", "repository", "->", "find", "(", "$", "id", ")", ")", "{", "abort", "(", "404",...
Get latest Transactions Get all transactions order by created desc for given model find by model primary id @param int $id @return AnonymousResourceCollection|TransactionResource[]
[ "Get", "latest", "Transactions" ]
train
https://github.com/weareunite/unisys-transactions/blob/3bfaf6993cc209871298340f5dabbe56f1eeab5d/src/Http/Controllers/HandleTransaction.php#L51-L61
cloudtek/dynamodm
lib/Cloudtek/DynamoDM/Client/Pool/CommandPool.php
CommandPool.addTransferStats
protected function addTransferStats(TransferStats $transferStats, $key = null) { if (!isset($this->transferStats[$key])) { $this->transferStats[$key] = $transferStats; return; } if (!is_array($this->transferStats[$key])) { $this->transferStats[$key] = [$this->transferStats[$key]]; } $this->transferStats[$key][] = $transferStats; }
php
protected function addTransferStats(TransferStats $transferStats, $key = null) { if (!isset($this->transferStats[$key])) { $this->transferStats[$key] = $transferStats; return; } if (!is_array($this->transferStats[$key])) { $this->transferStats[$key] = [$this->transferStats[$key]]; } $this->transferStats[$key][] = $transferStats; }
[ "protected", "function", "addTransferStats", "(", "TransferStats", "$", "transferStats", ",", "$", "key", "=", "null", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "transferStats", "[", "$", "key", "]", ")", ")", "{", "$", "this", "->", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/Client/Pool/CommandPool.php#L47-L60
cloudtek/dynamodm
lib/Cloudtek/DynamoDM/Client/Pool/CommandPool.php
CommandPool.getFulfilledCallback
protected function getFulfilledCallback(\AppendIterator $items, $hydrationMode) { return function (\Aws\ResultInterface $result, $i) use ($items, $hydrationMode) { $this->captureResponseMetadata($result, $i); if ($hydrationMode !== self::RESULT_TYPE_NONE) { if ($hydrationMode === self::RESULT_TYPE_SDK) { $iterator = new \ArrayIterator($result); } else { $command = $this->queue[$i]; $iterator = $command->parseResult( $result, $hydrationMode, $this->refresh, $this->readOnly, $this->primers[$command->parameters['TableName']] ); } $items->append($iterator); } $this->updateQueueFromResult($result, $i); }; }
php
protected function getFulfilledCallback(\AppendIterator $items, $hydrationMode) { return function (\Aws\ResultInterface $result, $i) use ($items, $hydrationMode) { $this->captureResponseMetadata($result, $i); if ($hydrationMode !== self::RESULT_TYPE_NONE) { if ($hydrationMode === self::RESULT_TYPE_SDK) { $iterator = new \ArrayIterator($result); } else { $command = $this->queue[$i]; $iterator = $command->parseResult( $result, $hydrationMode, $this->refresh, $this->readOnly, $this->primers[$command->parameters['TableName']] ); } $items->append($iterator); } $this->updateQueueFromResult($result, $i); }; }
[ "protected", "function", "getFulfilledCallback", "(", "\\", "AppendIterator", "$", "items", ",", "$", "hydrationMode", ")", "{", "return", "function", "(", "\\", "Aws", "\\", "ResultInterface", "$", "result", ",", "$", "i", ")", "use", "(", "$", "items", "...
@param \AppendIterator $items @param int $hydrationMode @return \Closure
[ "@param", "\\", "AppendIterator", "$items", "@param", "int", "$hydrationMode" ]
train
https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/Client/Pool/CommandPool.php#L76-L100
cloudtek/dynamodm
lib/Cloudtek/DynamoDM/Client/Pool/CommandPool.php
CommandPool.getQueue
protected function getQueue() { $sdkCommands = []; foreach ($this->queue as $command) { $sdkCommands[] = $command->getSdkCommand($this->parameters); } return $sdkCommands; }
php
protected function getQueue() { $sdkCommands = []; foreach ($this->queue as $command) { $sdkCommands[] = $command->getSdkCommand($this->parameters); } return $sdkCommands; }
[ "protected", "function", "getQueue", "(", ")", "{", "$", "sdkCommands", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "queue", "as", "$", "command", ")", "{", "$", "sdkCommands", "[", "]", "=", "$", "command", "->", "getSdkCommand", "(", "$"...
{@inheritdoc}
[ "{" ]
train
https://github.com/cloudtek/dynamodm/blob/119d355e2c5cbaef1f867970349b4432f5704fcd/lib/Cloudtek/DynamoDM/Client/Pool/CommandPool.php#L105-L114
agentmedia/phine-core
src/Core/Logic/Util/ArrayLinesSerializer.php
ArrayLinesSerializer.LinesToArray
function LinesToArray($text) { $result = array(); $lines = Str::SplitLines($text); foreach ($lines as $line) { $line = trim($line); if (!$line) { continue; } $pos = strpos($line, $this->separator); $key = $line; $value = ''; if ($pos !== false) { $key = substr($line, 0, $pos); $value = substr($line, $pos + strlen($this->separator)); } $result[trim($key)] = trim($value); } return $result; }
php
function LinesToArray($text) { $result = array(); $lines = Str::SplitLines($text); foreach ($lines as $line) { $line = trim($line); if (!$line) { continue; } $pos = strpos($line, $this->separator); $key = $line; $value = ''; if ($pos !== false) { $key = substr($line, 0, $pos); $value = substr($line, $pos + strlen($this->separator)); } $result[trim($key)] = trim($value); } return $result; }
[ "function", "LinesToArray", "(", "$", "text", ")", "{", "$", "result", "=", "array", "(", ")", ";", "$", "lines", "=", "Str", "::", "SplitLines", "(", "$", "text", ")", ";", "foreach", "(", "$", "lines", "as", "$", "line", ")", "{", "$", "line", ...
Fetches the lines of a text and serializes them to an array of key value pairs @param string $text The text representation of the array @return array Returns the array representation as associative array
[ "Fetches", "the", "lines", "of", "a", "text", "and", "serializes", "them", "to", "an", "array", "of", "key", "value", "pairs" ]
train
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Logic/Util/ArrayLinesSerializer.php#L36-L58
brunschgi/TerrificComposerBundle
Controller/SearchController.php
SearchController.searchAction
public function searchAction(Request $request) { // get all modules $moduleManager = $this->get('terrific.composer.module.manager'); $modules = $moduleManager->getModules(); // get all pages $pageManager = $this->get('terrific.composer.page.manager'); $pages = $pageManager->getPages(); // merge the results $results = array_merge($modules, $pages); return array('results' => $results); }
php
public function searchAction(Request $request) { // get all modules $moduleManager = $this->get('terrific.composer.module.manager'); $modules = $moduleManager->getModules(); // get all pages $pageManager = $this->get('terrific.composer.page.manager'); $pages = $pageManager->getPages(); // merge the results $results = array_merge($modules, $pages); return array('results' => $results); }
[ "public", "function", "searchAction", "(", "Request", "$", "request", ")", "{", "// get all modules", "$", "moduleManager", "=", "$", "this", "->", "get", "(", "'terrific.composer.module.manager'", ")", ";", "$", "modules", "=", "$", "moduleManager", "->", "getM...
Displays the terrific component search. @Route("/search", name="composer_search") @Template() @param Request $request @return Response
[ "Displays", "the", "terrific", "component", "search", "." ]
train
https://github.com/brunschgi/TerrificComposerBundle/blob/6eef4ace887c19ef166ab6654de385bc1ffbf5f1/Controller/SearchController.php#L40-L54
ekyna/Resource
Configuration/Configuration.php
Configuration.getClass
private function getClass($key) { if (!array_key_exists($key, $this->config['classes'])) { throw new \InvalidArgumentException(sprintf('Undefined resource class "%s".', $key)); } return $this->config['classes'][$key]; }
php
private function getClass($key) { if (!array_key_exists($key, $this->config['classes'])) { throw new \InvalidArgumentException(sprintf('Undefined resource class "%s".', $key)); } return $this->config['classes'][$key]; }
[ "private", "function", "getClass", "(", "$", "key", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "config", "[", "'classes'", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", ...
Returns the class for the given key. @param string $key @return string
[ "Returns", "the", "class", "for", "the", "given", "key", "." ]
train
https://github.com/ekyna/Resource/blob/96ee3d28e02bd9513705408e3bb7f88a76e52f56/Configuration/Configuration.php#L228-L235
genial-framework/Environment
Config.php
Config.validate
public static function validate(array $conf): void { if (empty($conf)) { throw new Exception\DomainException('The config array is empty.'); } if (depth($conf) != 2) { throw new Exception\DomainException(\sprintf( 'The config array does not have a depth of 2. Depth: `%s`.', (string) \depth($conf) )); } foreach ($conf as $var => $val) { if (!is_array($val)) { throw new Exception\UnexpectedValueException(\sprintf( 'The section is not the start of an array. Passed: `%s`.', e($var) )); } foreach ($val as $var2 => $val2) { if (!ctype_upper(str_replace('_', '', $var2))) { throw new Exception\UnexpectedValueException(\sprintf( 'The section variable name must all be caps. Passed: `%s`.', e($var2) )); } if (strlen($var2) > 30 || strlen($val2) > 250) { throw new Exception\LengthException(sprintf( 'The `$var2` and/or `$val2` variable is too long. Passed: `$var2` = `%s` `$val2` = `%s`.', (string) strlen($var2), (string) strlen($val2) )); } } } self::clearConfig(); self::$conf = $conf; }
php
public static function validate(array $conf): void { if (empty($conf)) { throw new Exception\DomainException('The config array is empty.'); } if (depth($conf) != 2) { throw new Exception\DomainException(\sprintf( 'The config array does not have a depth of 2. Depth: `%s`.', (string) \depth($conf) )); } foreach ($conf as $var => $val) { if (!is_array($val)) { throw new Exception\UnexpectedValueException(\sprintf( 'The section is not the start of an array. Passed: `%s`.', e($var) )); } foreach ($val as $var2 => $val2) { if (!ctype_upper(str_replace('_', '', $var2))) { throw new Exception\UnexpectedValueException(\sprintf( 'The section variable name must all be caps. Passed: `%s`.', e($var2) )); } if (strlen($var2) > 30 || strlen($val2) > 250) { throw new Exception\LengthException(sprintf( 'The `$var2` and/or `$val2` variable is too long. Passed: `$var2` = `%s` `$val2` = `%s`.', (string) strlen($var2), (string) strlen($val2) )); } } } self::clearConfig(); self::$conf = $conf; }
[ "public", "static", "function", "validate", "(", "array", "$", "conf", ")", ":", "void", "{", "if", "(", "empty", "(", "$", "conf", ")", ")", "{", "throw", "new", "Exception", "\\", "DomainException", "(", "'The config array is empty.'", ")", ";", "}", "...
validate(). Validate the config array. @param array $conf The config array. @throws DomainException If `$conf` argument is empty. @throws DomainException If `$conf` argument does not have a depth of 2. @throws UnexpectedValueException If a section is not the start of an array. @throws UnexpectedValueException If the section variable names are not capital letters. @throws LengthException If the section variable name and/or value is too long. @return void.
[ "validate", "()", "." ]
train
https://github.com/genial-framework/Environment/blob/f052c048a73ea06b8ebb6f2110a6ae5abba30030/Config.php#L28-L64
horntell/php-sdk
lib/guzzle/GuzzleHttp/Event/BeforeEvent.php
BeforeEvent.intercept
public function intercept(ResponseInterface $response) { $this->getTransaction()->setResponse($response); $this->stopPropagation(); RequestEvents::emitComplete($this->getTransaction()); }
php
public function intercept(ResponseInterface $response) { $this->getTransaction()->setResponse($response); $this->stopPropagation(); RequestEvents::emitComplete($this->getTransaction()); }
[ "public", "function", "intercept", "(", "ResponseInterface", "$", "response", ")", "{", "$", "this", "->", "getTransaction", "(", ")", "->", "setResponse", "(", "$", "response", ")", ";", "$", "this", "->", "stopPropagation", "(", ")", ";", "RequestEvents", ...
Intercept the request and associate a response @param ResponseInterface $response Response to set
[ "Intercept", "the", "request", "and", "associate", "a", "response" ]
train
https://github.com/horntell/php-sdk/blob/e5205e9396a21b754d5651a8aa5898da5922a1b7/lib/guzzle/GuzzleHttp/Event/BeforeEvent.php#L20-L25
Xiphe/THEWPTOOLS
src/Xiphe/THEWPTOOLS.php
THEWPTOOLS.shorten
public static function shorten($text, $maxlength = 140, $end = '[...]') { $maxlength++; if (mb_strlen($text) > $maxlength) { $subex = mb_substr($text, 0, $maxlength - 5); $exwords = explode(' ', $subex); $excut = - (mb_strlen($exwords[count($exwords)-1])); if ($excut < 0) { $text = mb_substr($subex, 0, $excut); } else { $text = $subex; } $text .= $end; } return $text; }
php
public static function shorten($text, $maxlength = 140, $end = '[...]') { $maxlength++; if (mb_strlen($text) > $maxlength) { $subex = mb_substr($text, 0, $maxlength - 5); $exwords = explode(' ', $subex); $excut = - (mb_strlen($exwords[count($exwords)-1])); if ($excut < 0) { $text = mb_substr($subex, 0, $excut); } else { $text = $subex; } $text .= $end; } return $text; }
[ "public", "static", "function", "shorten", "(", "$", "text", ",", "$", "maxlength", "=", "140", ",", "$", "end", "=", "'[...]'", ")", "{", "$", "maxlength", "++", ";", "if", "(", "mb_strlen", "(", "$", "text", ")", ">", "$", "maxlength", ")", "{", ...
Builds an excerpt from a longer text. @param string $text the input text @param integer $maxlength maximal length of the text @param string $end a string that will be attached to the short version of $text @return string
[ "Builds", "an", "excerpt", "from", "a", "longer", "text", "." ]
train
https://github.com/Xiphe/THEWPTOOLS/blob/4d36d99f3f55f87e9a664c66d2bdcd8dedf0d780/src/Xiphe/THEWPTOOLS.php#L94-L108
Xiphe/THEWPTOOLS
src/Xiphe/THEWPTOOLS.php
THEWPTOOLS.get_nav_menu_item_children
function get_nav_menu_item_children( $parent_id, $nav_menu_items, $depth = true ) { $nav_menu_item_list = array(); foreach ( (array) $nav_menu_items as $nav_menu_item ) { if ( $nav_menu_item->menu_item_parent == $parent_id ) { $nav_menu_item_list[] = $nav_menu_item; if ( $depth ) { if ( $children = self::get_nav_menu_item_children( $nav_menu_item->ID, $nav_menu_items ) ) $nav_menu_item_list = array_merge( $nav_menu_item_list, $children ); } } } return $nav_menu_item_list; }
php
function get_nav_menu_item_children( $parent_id, $nav_menu_items, $depth = true ) { $nav_menu_item_list = array(); foreach ( (array) $nav_menu_items as $nav_menu_item ) { if ( $nav_menu_item->menu_item_parent == $parent_id ) { $nav_menu_item_list[] = $nav_menu_item; if ( $depth ) { if ( $children = self::get_nav_menu_item_children( $nav_menu_item->ID, $nav_menu_items ) ) $nav_menu_item_list = array_merge( $nav_menu_item_list, $children ); } } } return $nav_menu_item_list; }
[ "function", "get_nav_menu_item_children", "(", "$", "parent_id", ",", "$", "nav_menu_items", ",", "$", "depth", "=", "true", ")", "{", "$", "nav_menu_item_list", "=", "array", "(", ")", ";", "foreach", "(", "(", "array", ")", "$", "nav_menu_items", "as", "...
Returns all child nav_menu_items under a specific parent http://wpsmith.net/2011/wp/how-to-get-all-the-children-of-a-specific-nav-menu-item/ @param int the parent nav_menu_item ID @param array nav_menu_items @param bool gives all children or direct children only @return array returns filtered array of nav_menu_items
[ "Returns", "all", "child", "nav_menu_items", "under", "a", "specific", "parent" ]
train
https://github.com/Xiphe/THEWPTOOLS/blob/4d36d99f3f55f87e9a664c66d2bdcd8dedf0d780/src/Xiphe/THEWPTOOLS.php#L217-L229
Xiphe/THEWPTOOLS
src/Xiphe/THEWPTOOLS.php
THEWPTOOLS.posted_on
public static function posted_on() { return sprintf(__('<span class="sep">Posted on </span><a href="%1$s" title="%2$s" rel="bookmark"><time class="entry-date" datetime="%3$s" pubdate>%4$s</time></a><span class="by-author"> <span class="sep"> by </span> <span class="author vcard"><a class="url fn n" href="%5$s" title="%6$s" rel="author">%7$s</a></span></span>', 'themaster'), esc_url(get_permalink()), esc_attr(get_the_time()), esc_attr(get_the_date('c')), esc_html(get_the_date()), esc_url(get_author_posts_url(get_the_author_meta('ID'))), esc_attr(sprintf(__('View all posts by %s', 'themaster'), get_the_author())), get_the_author() ); }
php
public static function posted_on() { return sprintf(__('<span class="sep">Posted on </span><a href="%1$s" title="%2$s" rel="bookmark"><time class="entry-date" datetime="%3$s" pubdate>%4$s</time></a><span class="by-author"> <span class="sep"> by </span> <span class="author vcard"><a class="url fn n" href="%5$s" title="%6$s" rel="author">%7$s</a></span></span>', 'themaster'), esc_url(get_permalink()), esc_attr(get_the_time()), esc_attr(get_the_date('c')), esc_html(get_the_date()), esc_url(get_author_posts_url(get_the_author_meta('ID'))), esc_attr(sprintf(__('View all posts by %s', 'themaster'), get_the_author())), get_the_author() ); }
[ "public", "static", "function", "posted_on", "(", ")", "{", "return", "sprintf", "(", "__", "(", "'<span class=\"sep\">Posted on </span><a href=\"%1$s\" title=\"%2$s\" rel=\"bookmark\"><time class=\"entry-date\" datetime=\"%3$s\" pubdate>%4$s</time></a><span class=\"by-author\"> <span class=...
The "Posted by Derp in FooBar" post-meta. Taken from TwentyEleven Wordpress Theme. @return string
[ "The", "Posted", "by", "Derp", "in", "FooBar", "post", "-", "meta", ".", "Taken", "from", "TwentyEleven", "Wordpress", "Theme", "." ]
train
https://github.com/Xiphe/THEWPTOOLS/blob/4d36d99f3f55f87e9a664c66d2bdcd8dedf0d780/src/Xiphe/THEWPTOOLS.php#L263-L274
Xiphe/THEWPTOOLS
src/Xiphe/THEWPTOOLS.php
THEWPTOOLS.get_title
public static function get_title() { global $page, $paged; $r = wp_title('|', false, 'right'); // Add the blog name. $r .= get_bloginfo('name'); // Add the blog description for the home/front page. $site_description = get_bloginfo('description', 'display'); if ($site_description && (is_home() || is_front_page())) { $r .= " | $site_description"; } // Add a page number if necessary: if ($paged >= 2 || $page >= 2) { $r .= ' | ' . sprintf(__('Page %s', 'themaster'), max($paged, $page)); } return $r; }
php
public static function get_title() { global $page, $paged; $r = wp_title('|', false, 'right'); // Add the blog name. $r .= get_bloginfo('name'); // Add the blog description for the home/front page. $site_description = get_bloginfo('description', 'display'); if ($site_description && (is_home() || is_front_page())) { $r .= " | $site_description"; } // Add a page number if necessary: if ($paged >= 2 || $page >= 2) { $r .= ' | ' . sprintf(__('Page %s', 'themaster'), max($paged, $page)); } return $r; }
[ "public", "static", "function", "get_title", "(", ")", "{", "global", "$", "page", ",", "$", "paged", ";", "$", "r", "=", "wp_title", "(", "'|'", ",", "false", ",", "'right'", ")", ";", "// Add the blog name.\r", "$", "r", ".=", "get_bloginfo", "(", "'...
A Standard title for Wordpress Pages. Taken from TwentyEleven Wordpress Theme. @access public @return string the title.
[ "A", "Standard", "title", "for", "Wordpress", "Pages", ".", "Taken", "from", "TwentyEleven", "Wordpress", "Theme", "." ]
train
https://github.com/Xiphe/THEWPTOOLS/blob/4d36d99f3f55f87e9a664c66d2bdcd8dedf0d780/src/Xiphe/THEWPTOOLS.php#L283-L303
Xiphe/THEWPTOOLS
src/Xiphe/THEWPTOOLS.php
THEWPTOOLS.get_language_attributes
public static function get_language_attributes() { ob_start(); language_attributes(); $r = ob_get_clean(); $r = str_replace('"', '', $r); $r = str_replace(' ', '|', $r); return $r; }
php
public static function get_language_attributes() { ob_start(); language_attributes(); $r = ob_get_clean(); $r = str_replace('"', '', $r); $r = str_replace(' ', '|', $r); return $r; }
[ "public", "static", "function", "get_language_attributes", "(", ")", "{", "ob_start", "(", ")", ";", "language_attributes", "(", ")", ";", "$", "r", "=", "ob_get_clean", "(", ")", ";", "$", "r", "=", "str_replace", "(", "'\"'", ",", "''", ",", "$", "r"...
Wrapper for language_attributes() to return its content instead of echoing it. @access public @return string the attributes string ready to be used in !HTML Class.
[ "Wrapper", "for", "language_attributes", "()", "to", "return", "its", "content", "instead", "of", "echoing", "it", "." ]
train
https://github.com/Xiphe/THEWPTOOLS/blob/4d36d99f3f55f87e9a664c66d2bdcd8dedf0d780/src/Xiphe/THEWPTOOLS.php#L311-L320
OxfordInfoLabs/kinikit-core
src/Util/HTTP/HttpRequest.php
HttpRequest.instance
public static function instance($reload = false) { if (HttpRequest::$instance == null || $reload) { HttpRequest::$instance = new HttpRequest (); } return HttpRequest::$instance; }
php
public static function instance($reload = false) { if (HttpRequest::$instance == null || $reload) { HttpRequest::$instance = new HttpRequest (); } return HttpRequest::$instance; }
[ "public", "static", "function", "instance", "(", "$", "reload", "=", "false", ")", "{", "if", "(", "HttpRequest", "::", "$", "instance", "==", "null", "||", "$", "reload", ")", "{", "HttpRequest", "::", "$", "instance", "=", "new", "HttpRequest", "(", ...
Enforce a singleton session object @return HttpRequest
[ "Enforce", "a", "singleton", "session", "object" ]
train
https://github.com/OxfordInfoLabs/kinikit-core/blob/edc1b2e6ffabd595c4c7d322279b3dd1e59ef359/src/Util/HTTP/HttpRequest.php#L99-L107
Dhii/iterator-abstract
src/IteratorIteratorTrait.php
IteratorIteratorTrait._advanceTracker
protected function _advanceTracker($tracker) { if (!($tracker instanceof Iterator)) { throw $this->_createInvalidArgumentException($this->__('Can only advance an Iterator tracker'), null, null, $tracker); } $tracker->next(); }
php
protected function _advanceTracker($tracker) { if (!($tracker instanceof Iterator)) { throw $this->_createInvalidArgumentException($this->__('Can only advance an Iterator tracker'), null, null, $tracker); } $tracker->next(); }
[ "protected", "function", "_advanceTracker", "(", "$", "tracker", ")", "{", "if", "(", "!", "(", "$", "tracker", "instanceof", "Iterator", ")", ")", "{", "throw", "$", "this", "->", "_createInvalidArgumentException", "(", "$", "this", "->", "__", "(", "'Can...
Advances the iterator forward. @since [*next-version*] @param Iterator $tracker The iterator used to track the loop. @throws InvalidArgumentException If problem advancing iterator.
[ "Advances", "the", "iterator", "forward", "." ]
train
https://github.com/Dhii/iterator-abstract/blob/576484183865575ffc2a0d586132741329626fb8/src/IteratorIteratorTrait.php#L28-L35
Dhii/iterator-abstract
src/IteratorIteratorTrait.php
IteratorIteratorTrait._resetTracker
protected function _resetTracker($tracker) { if (!($tracker instanceof Iterator)) { throw $this->_createInvalidArgumentException($this->__('Can only reset an Iterator tracker'), null, null, $tracker); } $tracker->rewind(); }
php
protected function _resetTracker($tracker) { if (!($tracker instanceof Iterator)) { throw $this->_createInvalidArgumentException($this->__('Can only reset an Iterator tracker'), null, null, $tracker); } $tracker->rewind(); }
[ "protected", "function", "_resetTracker", "(", "$", "tracker", ")", "{", "if", "(", "!", "(", "$", "tracker", "instanceof", "Iterator", ")", ")", "{", "throw", "$", "this", "->", "_createInvalidArgumentException", "(", "$", "this", "->", "__", "(", "'Can o...
Reset the iterator back to the start. @param Iterator $tracker The iterator used to track the loop. @throws InvalidArgumentException If problem resetting tracker.
[ "Reset", "the", "iterator", "back", "to", "the", "start", "." ]
train
https://github.com/Dhii/iterator-abstract/blob/576484183865575ffc2a0d586132741329626fb8/src/IteratorIteratorTrait.php#L44-L51
Dhii/iterator-abstract
src/IteratorIteratorTrait.php
IteratorIteratorTrait._createIterationFromTracker
protected function _createIterationFromTracker($tracker) { if (!($tracker instanceof Iterator)) { throw $this->_createInvalidArgumentException($this->__('Can only create an iteration from an Iterator tracker'), null, null, $tracker); } $key = $this->_calculateKey($tracker); $value = $this->_calculateValue($tracker); return $this->_createIteration($key, $value); }
php
protected function _createIterationFromTracker($tracker) { if (!($tracker instanceof Iterator)) { throw $this->_createInvalidArgumentException($this->__('Can only create an iteration from an Iterator tracker'), null, null, $tracker); } $key = $this->_calculateKey($tracker); $value = $this->_calculateValue($tracker); return $this->_createIteration($key, $value); }
[ "protected", "function", "_createIterationFromTracker", "(", "$", "tracker", ")", "{", "if", "(", "!", "(", "$", "tracker", "instanceof", "Iterator", ")", ")", "{", "throw", "$", "this", "->", "_createInvalidArgumentException", "(", "$", "this", "->", "__", ...
Creates a new iteration using an internal iterator. @since [*next-version*] @param Iterator $tracker The iterator used to track the iteration. @return IterationInterface The new iteration.
[ "Creates", "a", "new", "iteration", "using", "an", "internal", "iterator", "." ]
train
https://github.com/Dhii/iterator-abstract/blob/576484183865575ffc2a0d586132741329626fb8/src/IteratorIteratorTrait.php#L62-L72
DreadLabs/typo3-cms-phing-helper
Classes/Utility/TYPO3/ArrayUtility.php
ArrayUtility.array_merge_recursive_overrule
static public function array_merge_recursive_overrule(array $arr0, array $arr1, $notAddKeys = FALSE, $includeEmptyValues = TRUE, $enableUnsetFeature = TRUE) { foreach ($arr1 as $key => $val) { if ($enableUnsetFeature && $val === '__UNSET') { unset($arr0[$key]); continue; } if (isset($arr0[$key]) && is_array($arr0[$key])) { if (is_array($arr1[$key])) { $arr0[$key] = self::array_merge_recursive_overrule($arr0[$key], $arr1[$key], $notAddKeys, $includeEmptyValues, $enableUnsetFeature); } } elseif ( (!$notAddKeys || isset($arr0[$key])) && ($includeEmptyValues || $val) ) { $arr0[$key] = $val; } } reset($arr0); return $arr0; }
php
static public function array_merge_recursive_overrule(array $arr0, array $arr1, $notAddKeys = FALSE, $includeEmptyValues = TRUE, $enableUnsetFeature = TRUE) { foreach ($arr1 as $key => $val) { if ($enableUnsetFeature && $val === '__UNSET') { unset($arr0[$key]); continue; } if (isset($arr0[$key]) && is_array($arr0[$key])) { if (is_array($arr1[$key])) { $arr0[$key] = self::array_merge_recursive_overrule($arr0[$key], $arr1[$key], $notAddKeys, $includeEmptyValues, $enableUnsetFeature); } } elseif ( (!$notAddKeys || isset($arr0[$key])) && ($includeEmptyValues || $val) ) { $arr0[$key] = $val; } } reset($arr0); return $arr0; }
[ "static", "public", "function", "array_merge_recursive_overrule", "(", "array", "$", "arr0", ",", "array", "$", "arr1", ",", "$", "notAddKeys", "=", "FALSE", ",", "$", "includeEmptyValues", "=", "TRUE", ",", "$", "enableUnsetFeature", "=", "TRUE", ")", "{", ...
Merges two arrays recursively and "binary safe" (integer keys are overridden as well), overruling similar values in the first array ($arr0) with the values of the second array ($arr1) In case of identical keys, ie. keeping the values of the second. @author Kasper Skårhøj <kasperYYYY@typo3.com> @see typo3/sysext/core/Classes/Utility/GeneralUtility.php::array_merge_recursive_overrule @param array $arr0 First array @param array $arr1 Second array, overruling the first array @param boolean $notAddKeys If set, keys that are NOT found in $arr0 (first array) will not be set. Thus only existing value can/will be overruled from second array. @param boolean $includeEmptyValues If set, values from $arr1 will overrule if they are empty or zero. Default: TRUE @param boolean $enableUnsetFeature If set, special values "__UNSET" can be used in the second array in order to unset array keys in the resulting array. @return array Resulting array where $arr1 values has overruled $arr0 values
[ "Merges", "two", "arrays", "recursively", "and", "binary", "safe", "(", "integer", "keys", "are", "overridden", "as", "well", ")", "overruling", "similar", "values", "in", "the", "first", "array", "(", "$arr0", ")", "with", "the", "values", "of", "the", "s...
train
https://github.com/DreadLabs/typo3-cms-phing-helper/blob/b6606102c4702a92bc1872eba962febceaa0e645/Classes/Utility/TYPO3/ArrayUtility.php#L52-L72
DreadLabs/typo3-cms-phing-helper
Classes/Utility/TYPO3/ArrayUtility.php
ArrayUtility.sortByKeyRecursive
static public function sortByKeyRecursive(array $array) { ksort($array); foreach ($array as $key => $value) { if (is_array($value) && !empty($value)) { $array[$key] = self::sortByKeyRecursive($value); } } return $array; }
php
static public function sortByKeyRecursive(array $array) { ksort($array); foreach ($array as $key => $value) { if (is_array($value) && !empty($value)) { $array[$key] = self::sortByKeyRecursive($value); } } return $array; }
[ "static", "public", "function", "sortByKeyRecursive", "(", "array", "$", "array", ")", "{", "ksort", "(", "$", "array", ")", ";", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ...
Sorts an array recursively by key @param $array Array to sort recursively by key @return array Sorted array
[ "Sorts", "an", "array", "recursively", "by", "key" ]
train
https://github.com/DreadLabs/typo3-cms-phing-helper/blob/b6606102c4702a92bc1872eba962febceaa0e645/Classes/Utility/TYPO3/ArrayUtility.php#L80-L90
DreadLabs/typo3-cms-phing-helper
Classes/Utility/TYPO3/ArrayUtility.php
ArrayUtility.renumberKeysToAvoidLeapsIfKeysAreAllNumeric
static public function renumberKeysToAvoidLeapsIfKeysAreAllNumeric(array $array = array(), $level = 0) { $level++; $allKeysAreNumeric = TRUE; foreach (array_keys($array) as $key) { if (is_numeric($key) === FALSE) { $allKeysAreNumeric = FALSE; break; } } $renumberedArray = $array; if ($allKeysAreNumeric === TRUE) { $renumberedArray = array_values($array); } foreach ($renumberedArray as $key => $value) { if (is_array($value)) { $renumberedArray[$key] = self::renumberKeysToAvoidLeapsIfKeysAreAllNumeric($value, $level); } } return $renumberedArray; }
php
static public function renumberKeysToAvoidLeapsIfKeysAreAllNumeric(array $array = array(), $level = 0) { $level++; $allKeysAreNumeric = TRUE; foreach (array_keys($array) as $key) { if (is_numeric($key) === FALSE) { $allKeysAreNumeric = FALSE; break; } } $renumberedArray = $array; if ($allKeysAreNumeric === TRUE) { $renumberedArray = array_values($array); } foreach ($renumberedArray as $key => $value) { if (is_array($value)) { $renumberedArray[$key] = self::renumberKeysToAvoidLeapsIfKeysAreAllNumeric($value, $level); } } return $renumberedArray; }
[ "static", "public", "function", "renumberKeysToAvoidLeapsIfKeysAreAllNumeric", "(", "array", "$", "array", "=", "array", "(", ")", ",", "$", "level", "=", "0", ")", "{", "$", "level", "++", ";", "$", "allKeysAreNumeric", "=", "TRUE", ";", "foreach", "(", "...
Renumber the keys of an array to avoid leaps is keys are all numeric. Is called recursively for nested arrays. Example: Given array(0 => 'Zero' 1 => 'One', 2 => 'Two', 4 => 'Three') as input, it will return array(0 => 'Zero' 1 => 'One', 2 => 'Two', 3 => 'Three') Will treat keys string representations of number (ie. '1') equal to the numeric value (ie. 1). Example: Given array('0' => 'Zero', '1' => 'One' ) it will return array(0 => 'Zero', 1 => 'One') @author Susanne Moog <typo3@susanne-moog.de> @see typo3/sysext/core/Classes/Utility/ArrayUtility.php @param array $array Input array @param integer $level Internal level used for recursion, do *not* set from outside! @return array
[ "Renumber", "the", "keys", "of", "an", "array", "to", "avoid", "leaps", "is", "keys", "are", "all", "numeric", "." ]
train
https://github.com/DreadLabs/typo3-cms-phing-helper/blob/b6606102c4702a92bc1872eba962febceaa0e645/Classes/Utility/TYPO3/ArrayUtility.php#L120-L141
DreadLabs/typo3-cms-phing-helper
Classes/Utility/TYPO3/ArrayUtility.php
ArrayUtility.arrayExport
static public function arrayExport(array $array = array(), $level = 0) { $lines = 'array(' . chr(10); $level++; $writeKeyIndex = FALSE; $expectedKeyIndex = 0; foreach ($array as $key => $value) { if ($key === $expectedKeyIndex) { $expectedKeyIndex++; } else { // Found a non integer or non consecutive key, so we can break here $writeKeyIndex = TRUE; break; } } foreach ($array as $key => $value) { // Indention $lines .= str_repeat(chr(9), $level); if ($writeKeyIndex) { // Numeric / string keys $lines .= is_int($key) ? $key . ' => ' : '\'' . $key . '\' => '; } if (is_array($value)) { if (count($value) > 0) { $lines .= self::arrayExport($value, $level); } else { $lines .= 'array(),' . chr(10); } } elseif (is_int($value) || is_float($value)) { $lines .= $value . ',' . chr(10); } elseif (is_null($value)) { $lines .= 'NULL' . ',' . chr(10); } elseif (is_bool($value)) { $lines .= $value ? 'TRUE' : 'FALSE'; $lines .= ',' . chr(10); } elseif (is_string($value)) { // Quote \ to \\ $stringContent = str_replace('\\', '\\\\', $value); // Quote ' to \' $stringContent = str_replace('\'', '\\\'', $stringContent); $lines .= '\'' . $stringContent . '\'' . ',' . chr(10); } else { throw new RuntimeException('Objects are not supported', 1342294986); } } $lines .= str_repeat(chr(9), ($level - 1)) . ')' . ($level - 1 == 0 ? '' : ',' . chr(10)); return $lines; }
php
static public function arrayExport(array $array = array(), $level = 0) { $lines = 'array(' . chr(10); $level++; $writeKeyIndex = FALSE; $expectedKeyIndex = 0; foreach ($array as $key => $value) { if ($key === $expectedKeyIndex) { $expectedKeyIndex++; } else { // Found a non integer or non consecutive key, so we can break here $writeKeyIndex = TRUE; break; } } foreach ($array as $key => $value) { // Indention $lines .= str_repeat(chr(9), $level); if ($writeKeyIndex) { // Numeric / string keys $lines .= is_int($key) ? $key . ' => ' : '\'' . $key . '\' => '; } if (is_array($value)) { if (count($value) > 0) { $lines .= self::arrayExport($value, $level); } else { $lines .= 'array(),' . chr(10); } } elseif (is_int($value) || is_float($value)) { $lines .= $value . ',' . chr(10); } elseif (is_null($value)) { $lines .= 'NULL' . ',' . chr(10); } elseif (is_bool($value)) { $lines .= $value ? 'TRUE' : 'FALSE'; $lines .= ',' . chr(10); } elseif (is_string($value)) { // Quote \ to \\ $stringContent = str_replace('\\', '\\\\', $value); // Quote ' to \' $stringContent = str_replace('\'', '\\\'', $stringContent); $lines .= '\'' . $stringContent . '\'' . ',' . chr(10); } else { throw new RuntimeException('Objects are not supported', 1342294986); } } $lines .= str_repeat(chr(9), ($level - 1)) . ')' . ($level - 1 == 0 ? '' : ',' . chr(10)); return $lines; }
[ "static", "public", "function", "arrayExport", "(", "array", "$", "array", "=", "array", "(", ")", ",", "$", "level", "=", "0", ")", "{", "$", "lines", "=", "'array('", ".", "chr", "(", "10", ")", ";", "$", "level", "++", ";", "$", "writeKeyIndex",...
Exports an array as string. Similar to var_export(), but representation follows the TYPO3 core CGL. See unit tests for detailed examples @author Susanne Moog <typo3@susanne-moog.de> @see typo3/sysext/core/Classes/Utility/ArrayUtility.php @param array $array Array to export @param integer $level Internal level used for recursion, do *not* set from outside! @return string String representation of array @throws \RuntimeException
[ "Exports", "an", "array", "as", "string", ".", "Similar", "to", "var_export", "()", "but", "representation", "follows", "the", "TYPO3", "core", "CGL", "." ]
train
https://github.com/DreadLabs/typo3-cms-phing-helper/blob/b6606102c4702a92bc1872eba962febceaa0e645/Classes/Utility/TYPO3/ArrayUtility.php#L157-L205
bandama-framework/bandama-framework
src/foundation/dependency-injection/Container.php
Container.setInstance
public function setInstance($instance) { $reflection = new ReflectionClass($instance); $name = str_replace('\\', ':', $reflection->getName()); $this->instances[$name] = $instance; }
php
public function setInstance($instance) { $reflection = new ReflectionClass($instance); $name = str_replace('\\', ':', $reflection->getName()); $this->instances[$name] = $instance; }
[ "public", "function", "setInstance", "(", "$", "instance", ")", "{", "$", "reflection", "=", "new", "ReflectionClass", "(", "$", "instance", ")", ";", "$", "name", "=", "str_replace", "(", "'\\\\'", ",", "':'", ",", "$", "reflection", "->", "getName", "(...
Add new entry in instances. @param string $key Key of entry @param Callable $resolver Callable of entry @return void
[ "Add", "new", "entry", "in", "instances", "." ]
train
https://github.com/bandama-framework/bandama-framework/blob/234ed703baf9e31268941c9d5f6d5e004cc53066/src/foundation/dependency-injection/Container.php#L113-L117
bandama-framework/bandama-framework
src/foundation/dependency-injection/Container.php
Container.get
public function get($key) { // If the key is in factories the return new instance of class if (isset($this->factories[$key])) { return $this->factories[$key](); } // If the key is not in instances if (!isset($this->instances[$key])) { // If the key is in registry, instanciate the corresponding class and add it in instances if (isset($this->registry[$key])) { $this->instances[$key] = $this->registry[$key](); } else { // If the key is not in registry, instanciate the corresponding class and add it in instances $this->instances[$key] = self::newInstance($key); } } return $this->instances[$key]; }
php
public function get($key) { // If the key is in factories the return new instance of class if (isset($this->factories[$key])) { return $this->factories[$key](); } // If the key is not in instances if (!isset($this->instances[$key])) { // If the key is in registry, instanciate the corresponding class and add it in instances if (isset($this->registry[$key])) { $this->instances[$key] = $this->registry[$key](); } else { // If the key is not in registry, instanciate the corresponding class and add it in instances $this->instances[$key] = self::newInstance($key); } } return $this->instances[$key]; }
[ "public", "function", "get", "(", "$", "key", ")", "{", "// If the key is in factories the return new instance of class", "if", "(", "isset", "(", "$", "this", "->", "factories", "[", "$", "key", "]", ")", ")", "{", "return", "$", "this", "->", "factories", ...
Get an entry by key @param string $key Key of entry @return Callable|Object
[ "Get", "an", "entry", "by", "key" ]
train
https://github.com/bandama-framework/bandama-framework/blob/234ed703baf9e31268941c9d5f6d5e004cc53066/src/foundation/dependency-injection/Container.php#L126-L144
bandama-framework/bandama-framework
src/foundation/dependency-injection/Container.php
Container.newInstance
public static function newInstance($class) { $className = str_replace(':', '\\', $class); $reflectedClass = new ReflectionClass($className); if ($reflectedClass->isInstantiable()) { $constructor = $reflectedClass->getConstructor(); if ($constructor) { $parameters = $constructor->getParameters(); $constructorParameters = array(); foreach ($parameters as $parameter) { if ($parameter->getClass()) { $constructorParameters[] = self::newInstance($parameter->getClass()->getName()); } else { $constructorParameters[] = $parameter->getDefaultValue(); } } return $reflectedClass->newInstanceArgs($constructorParameters); } else { return $reflectedClass->newInstance(); } } else { throw new Exception($class." is not instantiable Class"); } }
php
public static function newInstance($class) { $className = str_replace(':', '\\', $class); $reflectedClass = new ReflectionClass($className); if ($reflectedClass->isInstantiable()) { $constructor = $reflectedClass->getConstructor(); if ($constructor) { $parameters = $constructor->getParameters(); $constructorParameters = array(); foreach ($parameters as $parameter) { if ($parameter->getClass()) { $constructorParameters[] = self::newInstance($parameter->getClass()->getName()); } else { $constructorParameters[] = $parameter->getDefaultValue(); } } return $reflectedClass->newInstanceArgs($constructorParameters); } else { return $reflectedClass->newInstance(); } } else { throw new Exception($class." is not instantiable Class"); } }
[ "public", "static", "function", "newInstance", "(", "$", "class", ")", "{", "$", "className", "=", "str_replace", "(", "':'", ",", "'\\\\'", ",", "$", "class", ")", ";", "$", "reflectedClass", "=", "new", "ReflectionClass", "(", "$", "className", ")", ";...
An instance factory method @param string $class Full class name with used : as namespace separator @return mixed
[ "An", "instance", "factory", "method" ]
train
https://github.com/bandama-framework/bandama-framework/blob/234ed703baf9e31268941c9d5f6d5e004cc53066/src/foundation/dependency-injection/Container.php#L153-L180
zodream/html
src/Bootstrap/FormWidget.php
FormWidget.html
public function html($content) { if (func_num_args() == 1) { $this->_data['fields'][] = $content; return $this; } $this->__attributes['fields'][$content] = func_get_arg(1); return $this; }
php
public function html($content) { if (func_num_args() == 1) { $this->_data['fields'][] = $content; return $this; } $this->__attributes['fields'][$content] = func_get_arg(1); return $this; }
[ "public", "function", "html", "(", "$", "content", ")", "{", "if", "(", "func_num_args", "(", ")", "==", "1", ")", "{", "$", "this", "->", "_data", "[", "'fields'", "]", "[", "]", "=", "$", "content", ";", "return", "$", "this", ";", "}", "$", ...
加入原生HTML代码 @param string $content @return $this
[ "加入原生HTML代码" ]
train
https://github.com/zodream/html/blob/bc21574091380007742bbc5c1c6d78bb87c47896/src/Bootstrap/FormWidget.php#L80-L87
zodream/html
src/Bootstrap/FormWidget.php
FormWidget.listBox
public function listBox($name, $items, $size = '10', $allowMultiple = false, $option = array()) { $option['size'] = $size; $option['multiple'] = $allowMultiple; return $this->select($name, $items, $option); }
php
public function listBox($name, $items, $size = '10', $allowMultiple = false, $option = array()) { $option['size'] = $size; $option['multiple'] = $allowMultiple; return $this->select($name, $items, $option); }
[ "public", "function", "listBox", "(", "$", "name", ",", "$", "items", ",", "$", "size", "=", "'10'", ",", "$", "allowMultiple", "=", "false", ",", "$", "option", "=", "array", "(", ")", ")", "{", "$", "option", "[", "'size'", "]", "=", "$", "size...
列表框 @param $name 名称 @param $items 列表项 @param string $size 显示个数 @param bool $allowMultiple 是否允许多选 @param array $option @return FormWidget
[ "列表框" ]
train
https://github.com/zodream/html/blob/bc21574091380007742bbc5c1c6d78bb87c47896/src/Bootstrap/FormWidget.php#L175-L179
hamjoint/mustard-media
src/lib/Http/Controllers/ItemController.php
ItemController.postAddPhotos
public function postAddPhotos(Request $request) { if (!$request->hasFile('photos')) { return response('', 400); } foreach ($request->file('photos') as $file) { $photo = Photo::upload($file->getRealPath()); session()->push('photos', [ 'photo_id' => $photo->getKey(), 'filename' => $file->getClientOriginalName(), ]); } }
php
public function postAddPhotos(Request $request) { if (!$request->hasFile('photos')) { return response('', 400); } foreach ($request->file('photos') as $file) { $photo = Photo::upload($file->getRealPath()); session()->push('photos', [ 'photo_id' => $photo->getKey(), 'filename' => $file->getClientOriginalName(), ]); } }
[ "public", "function", "postAddPhotos", "(", "Request", "$", "request", ")", "{", "if", "(", "!", "$", "request", "->", "hasFile", "(", "'photos'", ")", ")", "{", "return", "response", "(", "''", ",", "400", ")", ";", "}", "foreach", "(", "$", "reques...
Process and store several photos. @param \Illuminate\Http\Request $request @return \Illuminate\Http\RedirectResponse
[ "Process", "and", "store", "several", "photos", "." ]
train
https://github.com/hamjoint/mustard-media/blob/d3c799dbc3578e1e1022bb4eccae7a20e285ba06/src/lib/Http/Controllers/ItemController.php#L37-L51
hamjoint/mustard-media
src/lib/Http/Controllers/ItemController.php
ItemController.postDeletePhoto
public function postDeletePhoto(Request $request) { if (session()->has('photos')) { $photos = session('photos'); foreach ($photos as $index => $photo) { if (in_array($request->input('file'), $photo)) { $photo = Photo::find($photo['photo_id']); $photo->delete(); unset($photos[$index]); session('photos', $photos); return response('', 200); } } } return response('', 400); }
php
public function postDeletePhoto(Request $request) { if (session()->has('photos')) { $photos = session('photos'); foreach ($photos as $index => $photo) { if (in_array($request->input('file'), $photo)) { $photo = Photo::find($photo['photo_id']); $photo->delete(); unset($photos[$index]); session('photos', $photos); return response('', 200); } } } return response('', 400); }
[ "public", "function", "postDeletePhoto", "(", "Request", "$", "request", ")", "{", "if", "(", "session", "(", ")", "->", "has", "(", "'photos'", ")", ")", "{", "$", "photos", "=", "session", "(", "'photos'", ")", ";", "foreach", "(", "$", "photos", "...
Delete a photo. @param \Illuminate\Http\Request $request @return \Illuminate\Http\Response
[ "Delete", "a", "photo", "." ]
train
https://github.com/hamjoint/mustard-media/blob/d3c799dbc3578e1e1022bb4eccae7a20e285ba06/src/lib/Http/Controllers/ItemController.php#L60-L81