_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q265800
jSoapRequest.getParam
test
public function getParam($name, $defaultValue=null, $useDefaultIfEmpty=false){ if (!isset($this->params[$name])) { return $defaultValue; } // we cannot use the empty() function because 0 returns true. And maybe we want 0 // as a normal value... if (is_scalar($this->params[$name])) { if ($useDefaultIfEmpty && trim($this->params[$name]) == '' ) { return $defaultValue; } else { return $this->params[$name]; } } else{ // array or object if ( $useDefaultIfEmpty && empty($this->params[$name]) ) { return $defaultValue; } else { return $this->params[$name]; } } }
php
{ "resource": "" }
q265801
ExistValidator.checkTargetRelationExistence
test
private function checkTargetRelationExistence($model, $attribute) { /** @var ActiveQuery $relationQuery */ $relationQuery = $model->{'get' . ucfirst($this->targetRelation)}(); if ($this->filter instanceof \Closure) { call_user_func($this->filter, $relationQuery); } elseif ($this->filter !== null) { $relationQuery->andWhere($this->filter); } return $relationQuery->exists() ->then(null, function() use ($model, $attribute) { $this->addError($model, $attribute, $this->message); return null; }); }
php
{ "resource": "" }
q265802
ExistValidator.checkTargetAttributeExistence
test
private function checkTargetAttributeExistence($model, $attribute) { $targetAttribute = $this->targetAttribute === null ? $attribute : $this->targetAttribute; $params = $this->prepareConditions($targetAttribute, $model, $attribute); $conditions = [$this->targetAttributeJunction == 'or' ? 'or' : 'and']; if (!$this->allowArray) { foreach ($params as $key => $value) { if (is_array($value)) { $this->addError($model, $attribute, Reaction::t('rct', '{attribute} is invalid.')); return null; } $conditions[] = [$key => $value]; } } else { $conditions[] = $params; } $targetClass = $this->targetClass === null ? get_class($model) : $this->targetClass; $query = $this->createQuery($targetClass, $conditions); return $this->valueExists($query, $model->$attribute) ->then(null, function() use (&$model, $attribute) { $this->addError($model, $attribute, $this->message); return null; }); }
php
{ "resource": "" }
q265803
ExistValidator.valueExists
test
private function valueExists($query, $value) { if (is_array($value)) { return $query->count("DISTINCT [[$this->targetAttribute]]") ->then(function($count) use ($value) { return $count == count($value) ? true : reject(new Error("Not exists (count mismatch)")); }); } return $query->exists(); }
php
{ "resource": "" }
q265804
AbstractMySqlDao.getClause
test
protected final function getClause(TableInterface $table): string { $mySql = ""; $column = $table->get($table::ATTR_COLUMN); foreach ($table->get($table::ATTR_CLAUSE) as $key => $clause) { $mySql .= rtrim(" " . $this->constant($clause->getType()) . " " . $clause->getSubject() . " " . $this->constant($clause->getOperator())); if ($clause->getOperator()) { $type = isset($column[$clause->getSubject()]) ? $column[$clause->getSubject()]->getParam() : (is_int($clause->getValue()) ? PDO::PARAM_INT : (is_string($clause->getValue()) ? PDO::PARAM_STR : PDO::PARAM_NULL)); $id = ":c" . $key . "_" . ($clause->getSubject() ? str_replace(".", "_", $clause->getSubject()) : ""); $this->setParam($id, $clause->getValue(), $type); $mySql .= " " . $id; } } return ltrim($mySql); }
php
{ "resource": "" }
q265805
Renderer.render
test
public function render(Modal $modal, $template = 'EkynaCoreBundle:Modal:modal.xml.twig') { $response = new Response(); // Translations $modal->setTitle($this->translator->trans($modal->getTitle())); $buttons = $modal->getButtons(); foreach($buttons as &$button) { $button['label'] = $this->translator->trans($button['label']); } $modal->setButtons($buttons); $response->setContent($this->twig->render($template, ['modal' => $modal])); $response->headers->add(['Content-Type' => 'application/xml; charset='.strtolower($this->charset)]); return $response; }
php
{ "resource": "" }
q265806
FileHelper.localize
test
public function localize($file, $language = null, $sourceLanguage = null) { return $this->proxyWithLanguage(__FUNCTION__, [$file, $language, $sourceLanguage], -2); }
php
{ "resource": "" }
q265807
Stream.detach
test
public function detach() { $previous_stream = $this->stream; $this->stream = null; $this->meta_data = null; return $previous_stream; }
php
{ "resource": "" }
q265808
Stream.read
test
public function read($length) { if (!$this->isReadable()) { throw new \RuntimeException('Could not read the stream because it is not readable'); } $string = fread($this->stream, (int)$length); if ($string === false) { throw new \RuntimeException('Could not read the stream because of an error on fread()'); } return $string; }
php
{ "resource": "" }
q265809
NativeRequest.factory
test
public static function factory( array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null ): Request { return new static( $query, $request, $attributes, $cookies, $files, $server, $content ); }
php
{ "resource": "" }
q265810
NativeRequest.createFromGlobals
test
public static function createFromGlobals(): Request { // Create a new request from the PHP globals /** @var Request $request */ $request = new static($_GET, $_POST, [], $_COOKIE, $_FILES, $_SERVER); if ( 0 === strpos( $request->headers()->get('Content-Type'), 'application/x-www-form-urlencoded' ) && \in_array( strtoupper( $request->server()->get( 'REQUEST_METHOD', RequestMethod::GET ) ), [ RequestMethod::PUT, RequestMethod::DELETE, RequestMethod::PATCH, ], true ) ) { parse_str($request->getContent(), $data); $request->request = new Collection($data); } return $request; }
php
{ "resource": "" }
q265811
NativeRequest.setServer
test
public function setServer(array $server = []): Request { $server = $server ?: $_SERVER; $this->server = new Server($server); return $this; }
php
{ "resource": "" }
q265812
NativeRequest.setHeaders
test
public function setHeaders(array $headers = []): Request { $headers = $headers ?: $this->server()->getHeaders(); $this->headers = new Headers($headers); return $this; }
php
{ "resource": "" }
q265813
NativeRequest.getPath
test
public function getPath(): string { if (null === $this->path) { $this->path = $this->server()->get('REQUEST_URI'); } return $this->path; }
php
{ "resource": "" }
q265814
NativeRequest.getPathOnly
test
public function getPathOnly(): string { $requestUri = $this->getPath(); // Determine if the request uri has any query parameters if (false !== $queryPosition = strpos($requestUri, '?')) { // If so get the substring of the uri from start until the query param position $requestUri = substr($requestUri, 0, $queryPosition); } return $requestUri; }
php
{ "resource": "" }
q265815
NativeRequest.getHttpHost
test
public function getHttpHost(): string { $scheme = $this->getScheme(); $port = $this->getPort(); if ( ('http' === $scheme && $port === 80) || ('https' === $scheme && $port === 443) ) { return $this->getHost(); } return $this->getHost() . ':' . $port; }
php
{ "resource": "" }
q265816
NativeRequest.setMethod
test
public function setMethod(string $method): Request { $this->method = null; $this->server->set('REQUEST_METHOD', $method); return $this; }
php
{ "resource": "" }
q265817
NativeRequest.getMethod
test
public function getMethod(): string { if (null === $this->method) { $this->method = strtoupper( $this->server->get('REQUEST_METHOD', RequestMethod::GET) ); if (RequestMethod::POST === $this->method) { if ($method = $this->headers->get('X-HTTP-METHOD-OVERRIDE')) { $this->method = strtoupper($method); } elseif (self::$httpMethodParameterOverride) { $this->method = strtoupper( $this->request->get( '_method', $this->query->get( '_method', RequestMethod::POST ) ) ); } } } return $this->method; }
php
{ "resource": "" }
q265818
NativeRequest.getMimeType
test
public function getMimeType(string $format): string { return isset(static::$formats[$format]) ? static::$formats[$format][0] : null; }
php
{ "resource": "" }
q265819
NativeRequest.getFormat
test
public function getFormat(string $mimeType): string { $canonicalMimeType = null; if (false !== $pos = strpos($mimeType, ';')) { $canonicalMimeType = substr($mimeType, 0, $pos); } foreach (static::FORMATS as $format => $mimeTypes) { if (\in_array($mimeType, $mimeTypes, true)) { return $format; } if ( null !== $canonicalMimeType && \in_array( $canonicalMimeType, $mimeTypes, true ) ) { return $format; } } return 'html'; }
php
{ "resource": "" }
q265820
NativeRequest.getRequestFormat
test
public function getRequestFormat(string $default = 'html'): string { if (null === $this->format) { $this->format = $this->attributes->get('_format', $default); } return $this->format; }
php
{ "resource": "" }
q265821
TemplateViewProcessor.render
test
public function render($controller, $method, $parameters) { $templateMapping = []; foreach ($this->templateRoots as $templateRoot) { if ($templateRoot['name']) { $templateMapping[$templateRoot['name']] = $templateRoot['directory']; } } foreach ($this->templateRoots as $templateRoot) { try { return $this->renderingChain->render( $templateRoot['directory'], \str_replace($templateRoot['trim'], '', $controller) . DIRECTORY_SEPARATOR . $method, $parameters, $templateMapping ); } catch (TemplateNotFoundException $e) { //pass } } throw new TemplateNotFoundException('No template available for ' . $controller . '::' . $method . ' in directories ' . \implode(', ', \array_keys($this->templateRoots))); }
php
{ "resource": "" }
q265822
StaticApplicationAbstract.initHttp
test
public function initHttp() { $this->socket = Reaction::create(SocketServerInterface::class); $this->http = Reaction::create(Http::class, [$this->middleware]); $this->http->listen($this->socket); //Exception handler $this->http->on('error', function(\Throwable $error) { $this->logger->alert($error); }); }
php
{ "resource": "" }
q265823
StaticApplicationAbstract.addMiddleware
test
public function addMiddleware($middleware) { if (!is_callable($middleware) && !is_array($middleware)) { throw new InvalidArgumentException("Middleware must be a valid callable"); } else { $this->middleware[] = $middleware; } }
php
{ "resource": "" }
q265824
StaticApplicationAbstract.createRequestApplication
test
public function createRequestApplication(ServerRequestInterface $request) { $config = Reaction::$config->get('appRequest'); $config = ['request' => $request] + $config; $app = Reaction::create($config); return $app; }
php
{ "resource": "" }
q265825
StaticApplicationAbstract.setAlias
test
public function setAlias($alias, $path) { if (strncmp($alias, '@', 1)) { $alias = '@' . $alias; } $pos = strpos($alias, '/'); $root = $pos === false ? $alias : substr($alias, 0, $pos); if ($path !== null) { $path = strncmp($path, '@', 1) ? rtrim($path, '\\/') : $this->getAlias($path); if (!isset($this->aliases[$root])) { if ($pos === false) { $this->aliases[$root] = $path; } else { $this->aliases[$root] = [$alias => $path]; } } elseif (is_string($this->aliases[$root])) { if ($pos === false) { $this->aliases[$root] = $path; } else { $this->aliases[$root] = [ $alias => $path, $root => $this->aliases[$root], ]; } } else { $this->aliases[$root][$alias] = $path; krsort($this->aliases[$root]); } } elseif (isset($this->aliases[$root])) { if (is_array($this->aliases[$root])) { unset($this->aliases[$root][$alias]); } elseif ($pos === false) { unset($this->aliases[$root]); } } }
php
{ "resource": "" }
q265826
StaticApplicationAbstract.setAliases
test
public function setAliases($aliases) { foreach ($aliases as $alias => $path) { $this->setAlias($alias, $path); } }
php
{ "resource": "" }
q265827
StaticApplicationAbstract.getErrorLogLevel
test
protected function getErrorLogLevel($code) { $levels = [ E_ERROR => ['error', [Console::FG_RED, Console::BOLD]], E_WARNING => ['warning', [Console::FG_YELLOW, Console::BOLD]], E_PARSE => ['parse error', Console::FG_RED], E_NOTICE => ['notice', Console::FG_YELLOW], E_CORE_ERROR => ['core error', Console::FG_RED], E_CORE_WARNING => ['core warning', Console::FG_YELLOW], E_STRICT => ['strict warning', Console::FG_BLUE], ]; foreach ($levels as $mask => $level) { if ($mask & $code) { return $level; } } return ['low error', Console::FG_GREY]; }
php
{ "resource": "" }
q265828
Generator.generate
test
public static function generate($originalClassName, array $methods = null, array $properties = null, $proxyClassName = '', $callAutoload = false) { self::$exposeMethods = false; self::$exposeProperties = false; if ($proxyClassName == '') { $key = md5( $originalClassName . serialize($methods) . serialize($properties) ); if (isset(self::$cache[$key])) { return self::$cache[$key]; } } if (!empty($methods)) { self::$exposeMethods = true; } if (!empty($properties)) { self::$exposeProperties = true; } $proxy = self::generateProxy( $originalClassName, $methods, $properties, $proxyClassName, $callAutoload ); if (isset($key)) { self::$cache[$key] = $proxy; } return $proxy; }
php
{ "resource": "" }
q265829
Generator.getMethodCallParameters
test
public static function getMethodCallParameters($method) { $parameters = array(); foreach ($method->getParameters() as $i => $parameter) { $parameters[] = '$' . $parameter->getName(); } return join(', ', $parameters); }
php
{ "resource": "" }
q265830
Generator.generateProxy
test
protected static function generateProxy($originalClassName, array $methods = null, array $properties = null, $proxyClassName = '', $callAutoload = false) { $templateDir = __DIR__ . DIRECTORY_SEPARATOR . 'Generator' . DIRECTORY_SEPARATOR; $classTemplate = self::createTemplateObject( $templateDir . 'proxied_class.tpl' ); $proxyClassName = self::generateProxyClassName( $originalClassName, $proxyClassName ); if (interface_exists($proxyClassName['fullClassName'], $callAutoload)) { throw new GeneratorException(sprintf( '"%s" is an interface.', $proxyClassName['fullClassName'] ), GeneratorException::IS_INTERFACE); } if (!class_exists($proxyClassName['fullClassName'], $callAutoload)) { throw new GeneratorException(sprintf( 'Class "%s" does not exists.', $proxyClassName['fullClassName'] ), GeneratorException::CLASS_NOT_FOUND); } $class = new \ReflectionClass($proxyClassName['fullClassName']); if ($class->isFinal()) { throw new GeneratorException(sprintf( 'Class "%s" is declared "final". Cannot create proxy.', $proxyClassName['fullClassName'] ), GeneratorException::CLASS_IS_FINAL); } if (!empty($proxyClassName['namespaceName'])) { $prologue = 'namespace ' . $proxyClassName['namespaceName'] . ";\n\n"; } $classTemplate->setVar( array( 'prologue' => isset($prologue) ? $prologue : '', 'class_declaration' => $proxyClassName['proxyClassName'] . ' extends ' . $originalClassName, 'methods' => self::getProxiedMethods($proxyClassName['fullClassName'], $class, $methods), 'properties' => self::getProxiedProperties($proxyClassName['fullClassName'], $class, $properties), ) ); return array( 'code' => $classTemplate->render(), 'proxyClassName' => $proxyClassName['proxyClassName'], 'namespaceName' => $proxyClassName['namespaceName'] ); }
php
{ "resource": "" }
q265831
Generator.getProxiedProperties
test
protected static function getProxiedProperties($fullClassName, \ReflectionClass $class, array $properties = null) { $proxiedProperties = ''; $templateDir = __DIR__ . DIRECTORY_SEPARATOR . 'Generator' . DIRECTORY_SEPARATOR; $proxyProperties = $class->getProperties(\ReflectionMethod::IS_PROTECTED | \ReflectionMethod::IS_PRIVATE); if (empty($properties)) { foreach ($proxyProperties as $property) { $proxiedProperties .= self::generateProxiedPropertyDefinition($templateDir, $property, $class); } } else { foreach ($properties as $propertyName) { if ($class->hasProperty($propertyName)) { $property = $class->getProperty($propertyName); $proxiedProperties .= self::generateProxiedPropertyDefinition($templateDir, $property, $class); continue; } throw new GeneratorException( sprintf( 'Class "%s" has no protected or private property "%s".', $fullClassName, $propertyName ), GeneratorException::NO_PROTECTED_OR_PRIVATE_PROPERTY_DEFINED ); } } return $proxiedProperties; }
php
{ "resource": "" }
q265832
Generator.getProxiedMethods
test
protected static function getProxiedMethods($fullClassName, \ReflectionClass $class, array $methods = null) { $proxyMethods = array(); $proxiedMethods = ''; $templateDir = __DIR__ . DIRECTORY_SEPARATOR . 'Generator' . DIRECTORY_SEPARATOR; if (is_array($methods) && count($methods) > 0) { foreach ($methods as $methodName) { if ($class->hasMethod($methodName)) { $method = $class->getMethod($methodName); if (self::canProxyMethod($method)) { $proxyMethods[] = $method; continue; } throw new GeneratorException( sprintf('Can not proxy method "%s" of class "%s".', $methodName, $fullClassName), GeneratorException::CANNOT_PROXY_METHOD ); } throw new GeneratorException( sprintf('Class "%s" has no protected method "%s".', $fullClassName, $methodName), GeneratorException::NO_PROTECTED_METHOD_DEFINED ); } } else { $proxyMethods = self::canProxyMethods($class->getMethods(\ReflectionMethod::IS_PROTECTED)); if (empty($proxyMethods ) && self::$exposeProperties === false) { throw new GeneratorException( sprintf('Class "%s" has no protected methods.', $fullClassName), GeneratorException::NO_PROTECTED_METHOD_DEFINED ); } } foreach ($proxyMethods as $method) { $proxiedMethods .= self::generateProxiedMethodDefinition($templateDir, $method); } return $proxiedMethods; }
php
{ "resource": "" }
q265833
Generator.generateProxyClassName
test
protected static function generateProxyClassName($originalClassName, $proxyClassName) { $classNameParts = explode('\\', $originalClassName); $namespaceName = ''; $fullClassName = $originalClassName; if (count($classNameParts) > 1) { $originalClassName = array_pop($classNameParts); $namespaceName = implode('\\', $classNameParts); $fullClassName = $namespaceName . '\\' . $originalClassName; // eval does identifies namespaces with leading backslash as constant. $namespaceName = (0 === stripos($namespaceName, '\\') ? substr($namespaceName, 1) : $namespaceName); } if ($proxyClassName == '') { do { $proxyClassName = 'Proxy_' . $originalClassName . '_' . substr(md5(microtime()), 0, 8); } while (class_exists($proxyClassName, false)); } return array( 'proxyClassName' => $proxyClassName, 'className' => $originalClassName, 'fullClassName' => $fullClassName, 'namespaceName' => $namespaceName ); }
php
{ "resource": "" }
q265834
Generator.getArgumentDeclaration
test
protected static function getArgumentDeclaration(\ReflectionMethod $method) { $declarations = array(); $parameters = explode(', ', self::getMethodParameters($method)); foreach ($parameters as $parameter) { if (0 < strpos(trim($parameter), ' $') && false === strpos($parameter, 'array')) { $declarations[] = '\\' . $parameter; continue; } $declarations[] = $parameter; } return implode(', ', $declarations); }
php
{ "resource": "" }
q265835
Generator.canProxyMethod
test
protected static function canProxyMethod(\ReflectionMethod $method) { if ($method->isConstructor() || $method->isFinal() || $method->isStatic() || isset(self::$blacklistedMethodNames[$method->getName()]) ) { return false; } elseif ($method->isProtected()) { return true; } return false; }
php
{ "resource": "" }
q265836
Generator.canProxyMethods
test
protected static function canProxyMethods(array $methods) { $proxyMethods = array(); foreach ($methods as $method) { if (self::canProxyMethod($method)) { $proxyMethods[] = $method; } } return $proxyMethods; }
php
{ "resource": "" }
q265837
Generator.traverseStructure
test
protected static function traverseStructure($iterator) { $children = ''; while ($iterator->valid()) { if ($iterator->hasChildren()) { $current = 'array (' . self::traverseStructure($iterator->getChildren()) . '), '; } else { $current = "'" . $iterator->current() . "', "; } $key = $iterator->key(); if (is_numeric($key)) { $children .= $key . " => " . $current; } else { $children .= "'" . $key . "' => " . $current; } $iterator->next(); } return $children; }
php
{ "resource": "" }
q265838
Generator.getMethodParameters
test
public static function getMethodParameters($method, $forCall = FALSE) { $parameters = array(); foreach ($method->getParameters() as $i => $parameter) { $name = '$' . $parameter->getName(); /* Note: PHP extensions may use empty names for reference arguments * or "..." for methods taking a variable number of arguments. */ if ($name === '$' || $name === '$...') { $name = '$arg' . $i; } $default = ''; $reference = ''; $typeHint = ''; if (!$forCall) { if ($parameter->isArray()) { $typeHint = 'array '; } else if (version_compare(PHP_VERSION, '5.4.0', '>=') && $parameter->isCallable()) { $typeHint = 'callable '; } else { try { $class = $parameter->getClass(); } catch (\ReflectionException $e) { $class = FALSE; } if ($class) { $typeHint = $class->getName() . ' '; } } if ($parameter->isDefaultValueAvailable()) { $value = $parameter->getDefaultValue(); $default = ' = ' . var_export($value, TRUE); } else if ($parameter->isOptional()) { $default = ' = null'; } if ($parameter->isPassedByReference()) { $reference = '&'; } } $parameters[] = $typeHint . $reference . $name . $default; } return join(', ', $parameters); }
php
{ "resource": "" }
q265839
CreatePackagistHook.create
test
public function create(string $repoName) { $this->getGithubAuthentication()->authenticate(); $this->getHooksApi()->create($this->getGithubUsername(), $repoName, [ 'name' => 'packagist', 'config' => [ 'user' => $this->getPackagistUser(), 'token' => $this->getPackagistApiToken() ] ]); }
php
{ "resource": "" }
q265840
DbMessageSource.loadMessages
test
protected function loadMessages($category, $language) { if ($this->enableCaching) { $cacheKey = [ __CLASS__, $category, $language, ]; return $this->cache ->get($cacheKey) ->then(function($data) { return $data !== null ? $data : Reaction\Promise\reject(null); })->otherwise(function() use ($category, $language, $cacheKey) { $messages = []; return $this->loadMessagesFromDb($category, $language) ->then(function($messagesDb) use (&$messages, $cacheKey) { $messages = $messagesDb; return $this->cache->set($cacheKey, $messagesDb, $this->cachingDuration); })->then(function() use (&$messages) { return $messages; }); }); } return $this->loadMessagesFromDb($category, $language); }
php
{ "resource": "" }
q265841
Valkyrja.setup
test
public function setup(array $config = null, bool $force = false): void { // If the application was already setup, no need to do it again if (self::$setup && false === $force) { return; } // Avoid re-setting up the app later self::$setup = true; // Set the app static self::$app = $this; // Ensure the env has been set self::setEnv(); // If the VALKYRJA_START constant hasn't already been set if (! \defined('VALKYRJA_START')) { // Set a global constant for when the framework started \define('VALKYRJA_START', microtime(true)); } // Bootstrap debug capabilities $this->bootstrapConfig($config); // Bootstrap debug capabilities $this->bootstrapDebug(); // Bootstrap core functionality $this->bootstrapCore(); // Bootstrap the container $this->bootstrapContainer(); // Bootstrap setup $this->bootstrapSetup(); // Bootstrap the timezone $this->bootstrapTimezone(); }
php
{ "resource": "" }
q265842
Valkyrja.bootstrapConfig
test
protected function bootstrapConfig(array $config = null): void { $cacheFilePath = Directory::cachePath('config.php'); // If we should use the config cache file if (is_file($cacheFilePath)) { // Get the config from the cache file's contents self::$config = require $cacheFilePath; return; } $config = $config ?? []; $configFilePath = Directory::configPath('config.php'); $configFilePath = is_file($configFilePath) ? $configFilePath : __DIR__ . '/Config/config.php'; $defaultConfigs = require $configFilePath; self::$config = array_replace_recursive($defaultConfigs, $config); /** @var \Valkyrja\Support\Providers\Provider[] $providers */ $providers = self::$config['providers']; foreach ($providers as $provider) { // Config providers are NOT deferred and will not follow the // deferred value $provider::publish($this); } }
php
{ "resource": "" }
q265843
Valkyrja.bootstrapCore
test
protected function bootstrapCore(): void { // The events class to use from the config $eventsImpl = self::$config['app']['events']; // The container class to use from the config $containerImpl = self::$config['app']['container']; // The dispatcher class to use from the config $dispatcherImpl = self::$config['app']['dispatcher']; // Set the events to a new instance of the events implementation self::$events = new $eventsImpl($this); // If the events implementation specified does not adhere to the events // contract if (! self::$events instanceof Events) { throw new InvalidEventsImplementation( 'Invalid Events implementation' ); } // Set the container to a new instance of the container implementation self::$container = new $containerImpl($this); // If the container implementation specified does not adhere to the // container contract if (! self::$container instanceof Container) { throw new InvalidContainerImplementation( 'Invalid Container implementation' ); } // Set the dispatcher to a new instance of the dispatcher implementation self::$dispatcher = new $dispatcherImpl($this); // If the dispatcher implementation specified does not adhere to the // dispatcher contract if (! self::$dispatcher instanceof Dispatcher) { throw new InvalidDispatcherImplementation( 'Invalid Dispatcher implementation' ); } }
php
{ "resource": "" }
q265844
Valkyrja.bootstrapContainer
test
protected function bootstrapContainer(): void { // Set the application instance in the container self::$container->singleton(Application::class, $this); // Set the events instance in the container self::$container->singleton('env', self::$env); // Set the events instance in the container self::$container->singleton('config', self::$config); // Set the container instance in the container self::$container->singleton(Container::class, self::$container); // Set the dispatcher instance in the dispatcher self::$container->singleton(Dispatcher::class, self::$dispatcher); // Set the events instance in the container self::$container->singleton(Events::class, self::$events); }
php
{ "resource": "" }
q265845
Valkyrja.env
test
public static function env(string $variable = null, $default = null) { // If there was no variable requested if (null === $variable) { // Return the env class return static::getEnv(); } // If the env has this variable defined and the variable isn't null if ( \defined(static::getEnv() . '::' . $variable) && null !== $env = \constant(static::getEnv() . '::' . $variable) ) { // Return the variable return $env; } // Otherwise return the default return $default; }
php
{ "resource": "" }
q265846
Valkyrja.setEnv
test
public static function setEnv(string $env = null): void { // Set the env class to use self::$env = $env ?? self::$env ?? Env::class; }
php
{ "resource": "" }
q265847
Valkyrja.config
test
public function config(string $key = null, $default = null) { // If no key was specified if (null === $key) { // Return all the entire config return self::$config; } // Explode the keys on period $keys = explode('.', $key); // Set the config to return $config = self::$config; // Iterate through the keys foreach ($keys as $configItem) { // Trying to get the item from the config // or load the default $config = $config[$configItem] ?? $default; // If the item was not found, might as well return out from here // instead of continuing to iterate through the remaining keys if ($default === $config) { return $default; } } // do while($current !== $default); // Return the found config return $config; }
php
{ "resource": "" }
q265848
Valkyrja.abort
test
public function abort( int $statusCode = StatusCode::NOT_FOUND, string $message = '', array $headers = [], int $code = 0, Response $response = null ): void { throw new HttpException($statusCode, $message, null, $headers, $code, $response); }
php
{ "resource": "" }
q265849
Valkyrja.redirectTo
test
public function redirectTo(string $uri = null, int $statusCode = StatusCode::FOUND, array $headers = []): void { throw new HttpRedirectException($statusCode, $uri, null, $headers, 0); }
php
{ "resource": "" }
q265850
Valkyrja.response
test
public function response(string $content = '', int $statusCode = StatusCode::OK, array $headers = []): Response { /** @var Response $response */ $response = $this->container()->getSingleton(Response::class); if (\func_num_args() === 0) { return $response; } return $response->create($content, $statusCode, $headers); }
php
{ "resource": "" }
q265851
Valkyrja.redirectRoute
test
public function redirectRoute( string $route, array $parameters = [], int $statusCode = StatusCode::FOUND, array $headers = [] ): RedirectResponse { // Get the uri from the router using the route and parameters $uri = $this->router()->routeUrl($route, $parameters); return $this->redirect($uri, $statusCode, $headers); }
php
{ "resource": "" }
q265852
Valkyrja.view
test
public function view(string $template = '', array $variables = []): View { /** @var \Valkyrja\View\View $view */ $view = $this->container()->getSingleton(View::class); if (\func_num_args() === 0) { return $view; } return $view->make($template, $variables); }
php
{ "resource": "" }
q265853
Config.get
test
public function get($key) { if(!$this->exists($key)) { return false; } return array_get($this->items, $key); }
php
{ "resource": "" }
q265854
Schema.validateKey
test
public function validateKey(string $key) { if (false === isset($this->definitions[$key])) { throw new \InvalidArgumentException(sprintf( 'Descriptor "%s" not a permitted descriptor key. Did you make a typo? Permitted descriptors: "%s"', $key, implode('", "', array_keys($this->definitions)) )); } }
php
{ "resource": "" }
q265855
Schema.validate
test
public function validate(string $key, DescriptorInterface $descriptor) { $this->validateKey($key); $definition = $this->definitions[$key]; if (get_class($descriptor) !== $definition->getClass()) { throw new \InvalidArgumentException(sprintf( 'Descriptor with key "%s" must be of class "%s", got "%s"', $key, $definition->getClass(), get_class($descriptor) )); } }
php
{ "resource": "" }
q265856
CacheInvalidator.getCacheInvalidationSettings
test
public function getCacheInvalidationSettings() { if($this->cacheInvalidationSettings == null) { $this->cacheInvalidationSettings = '[]'; } return json_decode($this->cacheInvalidationSettings, true); }
php
{ "resource": "" }
q265857
CacheInvalidator.setCacheInvalidationSettings
test
public function setCacheInvalidationSettings($settings) { $this->cacheInvalidationSettings = is_string($settings) ? $settings : json_encode($settings, JSON_PRETTY_PRINT); return $this; }
php
{ "resource": "" }
q265858
Logger.init
test
protected function init(array $user_options = array(), $logname = null) { $app_config = CarteBlanche::getConfig('log', array(), true); $app_config['directory'] = CarteBlanche::getFullPath('log_dir'); $user_config = CarteBlanche::getConfig('log', array()); if (!empty($user_config)) { $config = array_merge($app_config, $user_config, $user_options); } else { $config = array_merge($app_config, $user_options); } parent::init($config, $logname); }
php
{ "resource": "" }
q265859
Logger.getFilePath
test
protected function getFilePath($level = 100) { $mode = CarteBlanche::getKernel()->getMode(); return DirectoryHelper::slashDirname($this->directory) .$this->getFileName($level) .($mode!='prod' ? '_'.$mode : '' ) .'.'.trim($this->logfile_extension, '.'); }
php
{ "resource": "" }
q265860
Password.verify
test
public function verify($password, $hash) { $verify = password_verify($password, $hash); if (true === $verify && $this->isRehashIfNeeded() && $this->needsRehash($hash)) { $newHash = $this->create($password); $verify = [ 'verify' => true, 'hash' => $newHash, ]; } return $verify; }
php
{ "resource": "" }
q265861
Zend_Filter_RealPath.setExists
test
public function setExists($exists) { if ($exists instanceof Zend_Config) { $exists = $exists->toArray(); } if (is_array($exists)) { if (isset($exists['exists'])) { $exists = (boolean) $exists['exists']; } } $this->_exists = (boolean) $exists; return $this; }
php
{ "resource": "" }
q265862
Progress.renderProgress
test
protected function renderProgress() { if (empty($this->bars)) { $config = ['percent' => $this->percent, 'animated' => $this->animated, 'striped' => $this->striped]; return $this->renderBar($config, $this->label, $this->barOptions); } $bars = []; foreach ($this->bars as $bar) { $label = ArrayHelper::getValue($bar, 'label', ''); if (!isset($bar['percent'])) { throw new InvalidConfigException("The 'percent' option is required."); } $options = ArrayHelper::getValue($bar, 'options', []); $bars[] = $this->renderBar($bar, $label, $options); } return implode("\n", $bars); }
php
{ "resource": "" }
q265863
Progress.renderBar
test
protected function renderBar($config = [], $label, $options = []) { $percent = ArrayHelper::getValue($config, 'percent', 0); $animated = ArrayHelper::getValue($config, 'animated', false); $striped = ArrayHelper::getValue($config, 'striped', false) || $animated; $percentFixed = number_format($percent, 2, '.', ''); $defaultOptions = [ 'role' => 'progressbar', 'aria-valuenow' => $percent, 'aria-valuemin' => 0, 'aria-valuemax' => 100, 'style' => "width:{$percentFixed}%", ]; $options = array_merge($defaultOptions, $options); Html::addCssClass($options, ['widget' => 'progress-bar']); if ($animated) { Html::addCssClass($options, ['animated' => 'progress-bar-animated']); } if ($striped) { Html::addCssClass($options, ['striped' => 'progress-bar-striped']); } $out = $this->htmlHlp->beginTag('div', $options); $out .= $label; $out .= $this->htmlHlp->tag('span', \Reaction::t('rct', '{percent}% Complete', ['percent' => $percent]), [ 'class' => 'sr-only' ]); $out .= Html::endTag('div'); return $out; }
php
{ "resource": "" }
q265864
jSoapCoordinator.processSoap
test
public function processSoap(){ $this->wsdl = new jWSDL($this->request->params['module'], $this->request->params['action']); $this->soapServer = $this->getSoapServer($this->wsdl); $this->soapServer->setclass('jSoapHandler', $this); $this->soapServer->handle($this->request->soapMsg); }
php
{ "resource": "" }
q265865
jSoapCoordinator.getSoapServer
test
public function getSoapServer($wsdl = null){ if(is_null($this->soapServer)){ if(is_null($wsdl)){ $this->soapServer = new SoapServer(null, array('soap_version' => SOAP_1_1, 'encoding' => jApp::config()->charset, 'uri' => $_SERVER['PHP_SELF'])); }else{ $this->soapServer = new SoapServer($wsdl->getWSDLFilePath(), array('soap_version' => SOAP_1_1, 'encoding' => jApp::config()->charset)); } } return $this->soapServer; }
php
{ "resource": "" }
q265866
TaggedEntityListener.onFlush
test
public function onFlush(OnFlushEventArgs $eventArgs) { $em = $eventArgs->getEntityManager(); $uow = $em->getUnitOfWork(); foreach ($uow->getScheduledEntityInsertions() as $entity) { $this->invalidateEntity($entity); } foreach ($uow->getScheduledEntityUpdates() as $entity) { $this->invalidateEntity($entity); } foreach ($uow->getScheduledEntityDeletions() as $entity) { $this->invalidateEntity($entity); } /** @var \Doctrine\Common\Collections\ArrayCollection $col */ foreach ($uow->getScheduledCollectionUpdates() as $col) { foreach ($col as $entity) { $this->invalidateEntity($entity); } } foreach ($uow->getScheduledCollectionDeletions() as $col) { foreach ($col as $entity) { $this->invalidateEntity($entity); } } }
php
{ "resource": "" }
q265867
TaggedEntityListener.postFlush
test
public function postFlush() { $this->eventDispatcher->dispatch( HttpCacheEvents::INVALIDATE_TAG, new HttpCacheEvent($this->tagsToInvalidate) ); $this->reset(); }
php
{ "resource": "" }
q265868
TaggedEntityListener.invalidateEntity
test
private function invalidateEntity($entity) { if ($entity instanceof TaggedEntityInterface) { $this->addTagToInvalidate($entity::getEntityTagPrefix()); if (null !== $entity->getId()) { $this->addTagToInvalidate($entity->getEntityTag()); } } elseif ($entity instanceof TranslationInterface) { $translatable = $entity->getTranslatable(); $this->invalidateEntity($translatable); } }
php
{ "resource": "" }
q265869
TaggedEntityListener.addTagToInvalidate
test
private function addTagToInvalidate($tag) { if (0 < strlen($tag) && !in_array($tag, $this->tagsToInvalidate)) { $this->tagsToInvalidate[] = $tag; } }
php
{ "resource": "" }
q265870
BaseUser.choiceSexe
test
public static function choiceSexe() { return array('Sexe.choice.' . self::SEXE_MISS => self::SEXE_MISS, 'Sexe.choice.' . self::SEXE_MRS => self::SEXE_MRS, 'Sexe.choice.' . self::SEXE_MR => self::SEXE_MR); }
php
{ "resource": "" }
q265871
Zend_Filter_Callback.setCallback
test
public function setCallback($callback, $options = null) { if (!is_callable($callback)) { throw new Zend_Filter_Exception('Callback can not be accessed'); } $this->_callback = $callback; $this->setOptions($options); return $this; }
php
{ "resource": "" }
q265872
Zend_Filter_Callback.filter
test
public function filter($value) { $options = array(); if ($this->_options !== null) { if (!is_array($this->_options)) { $options = array($this->_options); } else { $options = $this->_options; } } array_unshift($options, $value); return call_user_func_array($this->_callback, $options); }
php
{ "resource": "" }
q265873
Zend_Cache_Backend_WinCache.getFillingPercentage
test
public function getFillingPercentage() { $mem = wincache_ucache_meminfo(); $memSize = $mem['memory_total']; $memUsed = $memSize - $mem['memory_free']; if ($memSize == 0) { Zend_Cache::throwException('can\'t get WinCache memory size'); } if ($memUsed > $memSize) { return 100; } return ((int) (100. * ($memUsed / $memSize))); }
php
{ "resource": "" }
q265874
SeobilityBehavior.getAllSeobility
test
public function getAllSeobility($force = false) { $this->_seo = (array)($force ? [] : $this->_seo) + Seo::findAll($this->owner); return ArrayHelper::toArray($this->_seo, ['inblank\seobility\models\Seo' => ['title', 'keywords', 'description']]); }
php
{ "resource": "" }
q265875
SeobilityBehavior.setSeobility
test
public function setSeobility($values, $condition = 0) { $condition = (int)$condition; if (!array_key_exists($condition, $this->_seo)) { $this->_seo[$condition] = Seo::find($this->owner, $condition); } $this->_seo[$condition]->setAttributes($values); }
php
{ "resource": "" }
q265876
SeobilityBehavior.getSeobility
test
public function getSeobility($condition = 0, $defaultIfNotFound = true, $defaultCondition = 0) { $condition = (int)$condition; if (!array_key_exists($condition, $this->_seo)) { $this->_seo[$condition] = Seo::find($this->owner, $condition); if ($this->_seo[$condition]->getIsNewRecord() && $defaultIfNotFound) { $this->getSeobility((int)$defaultCondition, false); } } return $this->_seo[$condition]->getAttributes(['title', 'keywords', 'description']); }
php
{ "resource": "" }
q265877
ToBool.convert
test
function convert(): bool { if (!is_string($this->value)) { $this->result = $this->value; } else { switch (strtolower($this->value)) { case '1': case 'true': case 'on': case 'yes': case 'y': $this->result = true; default: $this->result = false; } } return $this->result; }
php
{ "resource": "" }
q265878
Circle.getOrdinateByAbscissa
test
public function getOrdinateByAbscissa($x) { $o = $this->getPointO(); return (sqrt(pow($this->getRadius(), 2) - pow(($x - $o->getAbscissa()), 2)) + $o->getOrdinate()); }
php
{ "resource": "" }
q265879
Circle.getAbscissaByOrdinate
test
public function getAbscissaByOrdinate($y) { $o = $this->getPointO(); return (sqrt(pow($this->getRadius(), 2) - pow(($y - $o->getOrdinate()), 2)) + $o->getAbscissa()); }
php
{ "resource": "" }
q265880
OwpPostmark.attachment
test
public function attachment($name, $content, $content_type) { $this->data['Attachments'][$this->attachment_count]['Name'] = $name; $this->data['Attachments'][$this->attachment_count]['ContentType'] = $content_type; // Check if our content is already base64 encoded or not if(! base64_decode($content, true)) $this->data['Attachments'][$this->attachment_count]['Content'] = base64_encode($content); else $this->data['Attachments'][$this->attachment_count]['Content'] = $content; // Up our attachment counter $this->attachment_count++; return $this; }
php
{ "resource": "" }
q265881
Mail_mimePart.encode
test
function encode($boundary=null) { $encoded =& $this->_encoded; if (count($this->_subparts)) { $boundary = $boundary ? $boundary : '=_' . md5(rand() . microtime()); $eol = $this->_eol; $this->_headers['Content-Type'] .= ";$eol boundary=\"$boundary\""; $encoded['body'] = ''; for ($i = 0; $i < count($this->_subparts); $i++) { $encoded['body'] .= '--' . $boundary . $eol; $tmp = $this->_subparts[$i]->encode(); if ($this->_isError($tmp)) { return $tmp; } foreach ($tmp['headers'] as $key => $value) { $encoded['body'] .= $key . ': ' . $value . $eol; } $encoded['body'] .= $eol . $tmp['body'] . $eol; } $encoded['body'] .= '--' . $boundary . '--' . $eol; } else if ($this->_body) { $encoded['body'] = $this->_getEncodedData($this->_body, $this->_encoding); } else if ($this->_body_file) { // Temporarily reset magic_quotes_runtime for file reads and writes if ($magic_quote_setting = get_magic_quotes_runtime()) { @ini_set('magic_quotes_runtime', 0); } $body = $this->_getEncodedDataFromFile($this->_body_file, $this->_encoding); if ($magic_quote_setting) { @ini_set('magic_quotes_runtime', $magic_quote_setting); } if ($this->_isError($body)) { return $body; } $encoded['body'] = $body; } else { $encoded['body'] = ''; } // Add headers to $encoded $encoded['headers'] =& $this->_headers; return $encoded; }
php
{ "resource": "" }
q265882
Mail_mimePart.encodeToFile
test
function encodeToFile($filename, $boundary=null, $skip_head=false) { if (file_exists($filename) && !is_writable($filename)) { $err = $this->_raiseError('File is not writeable: ' . $filename); return $err; } if (!($fh = fopen($filename, 'ab'))) { $err = $this->_raiseError('Unable to open file: ' . $filename); return $err; } // Temporarily reset magic_quotes_runtime for file reads and writes if ($magic_quote_setting = get_magic_quotes_runtime()) { @ini_set('magic_quotes_runtime', 0); } $res = $this->_encodePartToFile($fh, $boundary, $skip_head); fclose($fh); if ($magic_quote_setting) { @ini_set('magic_quotes_runtime', $magic_quote_setting); } return $this->_isError($res) ? $res : $this->_headers; }
php
{ "resource": "" }
q265883
Mail_mimePart._encodePartToFile
test
function _encodePartToFile($fh, $boundary=null, $skip_head=false) { $eol = $this->_eol; if (count($this->_subparts)) { $boundary = $boundary ? $boundary : '=_' . md5(rand() . microtime()); $this->_headers['Content-Type'] .= ";$eol boundary=\"$boundary\""; } if (!$skip_head) { foreach ($this->_headers as $key => $value) { fwrite($fh, $key . ': ' . $value . $eol); } $f_eol = $eol; } else { $f_eol = ''; } if (count($this->_subparts)) { for ($i = 0; $i < count($this->_subparts); $i++) { fwrite($fh, $f_eol . '--' . $boundary . $eol); $res = $this->_subparts[$i]->_encodePartToFile($fh); if ($this->_isError($res)) { return $res; } $f_eol = $eol; } fwrite($fh, $eol . '--' . $boundary . '--' . $eol); } else if ($this->_body) { fwrite($fh, $f_eol . $this->_getEncodedData($this->_body, $this->_encoding)); } else if ($this->_body_file) { fwrite($fh, $f_eol); $res = $this->_getEncodedDataFromFile( $this->_body_file, $this->_encoding, $fh ); if ($this->_isError($res)) { return $res; } } return true; }
php
{ "resource": "" }
q265884
Mail_mimePart.&
test
function &addSubpart($body, $params) { $this->_subparts[] = $part = new Mail_mimePart($body, $params); return $part; }
php
{ "resource": "" }
q265885
Mail_mimePart._quotedPrintableEncode
test
function _quotedPrintableEncode($input , $line_max = 76) { $eol = $this->_eol; /* // imap_8bit() is extremely fast, but doesn't handle properly some characters if (function_exists('imap_8bit') && $line_max == 76) { $input = preg_replace('/\r?\n/', "\r\n", $input); $input = imap_8bit($input); if ($eol != "\r\n") { $input = str_replace("\r\n", $eol, $input); } return $input; } */ $lines = preg_split("/\r?\n/", $input); $escape = '='; $output = ''; while (list($idx, $line) = each($lines)) { $newline = ''; $i = 0; while (isset($line[$i])) { $char = $line[$i]; $dec = ord($char); $i++; if (($dec == 32) && (!isset($line[$i]))) { // convert space at eol only $char = '=20'; } elseif ($dec == 9 && isset($line[$i])) { ; // Do nothing if a TAB is not on eol } elseif (($dec == 61) || ($dec < 32) || ($dec > 126)) { $char = $escape . sprintf('%02X', $dec); } elseif (($dec == 46) && (($newline == '') || ((strlen($newline) + strlen("=2E")) >= $line_max)) ) { // Bug #9722: convert full-stop at bol, // some Windows servers need this, won't break anything (cipri) // Bug #11731: full-stop at bol also needs to be encoded // if this line would push us over the line_max limit. $char = '=2E'; } // Note, when changing this line, also change the ($dec == 46) // check line, as it mimics this line due to Bug #11731 // EOL is not counted if ((strlen($newline) + strlen($char)) >= $line_max) { // soft line break; " =\r\n" is okay $output .= $newline . $escape . $eol; $newline = ''; } $newline .= $char; } // end of for $output .= $newline . $eol; unset($lines[$idx]); } // Don't want last crlf $output = substr($output, 0, -1 * strlen($eol)); return $output; }
php
{ "resource": "" }
q265886
Mail_mimePart._buildHeaderParam
test
function _buildHeaderParam($name, $value, $charset=null, $language=null, $encoding=null, $maxLength=75 ) { // RFC 2045: // value needs encoding if contains non-ASCII chars or is longer than 78 chars if (!preg_match('#[^\x20-\x7E]#', $value)) { $token_regexp = '#([^\x21\x23-\x27\x2A\x2B\x2D' . '\x2E\x30-\x39\x41-\x5A\x5E-\x7E])#'; if (!preg_match($token_regexp, $value)) { // token if (strlen($name) + strlen($value) + 3 <= $maxLength) { return " {$name}={$value}"; } } else { // quoted-string $quoted = addcslashes($value, '\\"'); if (strlen($name) + strlen($quoted) + 5 <= $maxLength) { return " {$name}=\"{$quoted}\""; } } } // RFC2047: use quoted-printable/base64 encoding if ($encoding == 'quoted-printable' || $encoding == 'base64') { return $this->_buildRFC2047Param($name, $value, $charset, $encoding); } // RFC2231: $encValue = preg_replace_callback( '/([^\x21\x23\x24\x26\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E-\x7E])/', array($this, '_encodeReplaceCallback'), $value ); $value = "$charset'$language'$encValue"; $header = " {$name}*={$value}"; if (strlen($header) <= $maxLength) { return $header; } $preLength = strlen(" {$name}*0*="); $maxLength = max(16, $maxLength - $preLength - 3); $maxLengthReg = "|(.{0,$maxLength}[^\%][^\%])|"; $headers = array(); $headCount = 0; while ($value) { $matches = array(); $found = preg_match($maxLengthReg, $value, $matches); if ($found) { $headers[] = " {$name}*{$headCount}*={$matches[0]}"; $value = substr($value, strlen($matches[0])); } else { $headers[] = " {$name}*{$headCount}*={$value}"; $value = ''; } $headCount++; } $headers = implode(';' . $this->_eol, $headers); return $headers; }
php
{ "resource": "" }
q265887
Mail_mimePart._buildRFC2047Param
test
function _buildRFC2047Param($name, $value, $charset, $encoding='quoted-printable', $maxLength=76 ) { // WARNING: RFC 2047 says: "An 'encoded-word' MUST NOT be used in // parameter of a MIME Content-Type or Content-Disposition field", // but... it's supported by many clients/servers $quoted = ''; if ($encoding == 'base64') { $value = base64_encode($value); $prefix = '=?' . $charset . '?B?'; $suffix = '?='; // 2 x SPACE, 2 x '"', '=', ';' $add_len = strlen($prefix . $suffix) + strlen($name) + 6; $len = $add_len + strlen($value); while ($len > $maxLength) { // We can cut base64-encoded string every 4 characters $real_len = floor(($maxLength - $add_len) / 4) * 4; $_quote = substr($value, 0, $real_len); $value = substr($value, $real_len); $quoted .= $prefix . $_quote . $suffix . $this->_eol . ' '; $add_len = strlen($prefix . $suffix) + 4; // 2 x SPACE, '"', ';' $len = strlen($value) + $add_len; } $quoted .= $prefix . $value . $suffix; } else { // quoted-printable $value = $this->encodeQP($value); $prefix = '=?' . $charset . '?Q?'; $suffix = '?='; // 2 x SPACE, 2 x '"', '=', ';' $add_len = strlen($prefix . $suffix) + strlen($name) + 6; $len = $add_len + strlen($value); while ($len > $maxLength) { $length = $maxLength - $add_len; // don't break any encoded letters if (preg_match("/^(.{0,$length}[^\=][^\=])/", $value, $matches)) { $_quote = $matches[1]; } $quoted .= $prefix . $_quote . $suffix . $this->_eol . ' '; $value = substr($value, strlen($_quote)); $add_len = strlen($prefix . $suffix) + 4; // 2 x SPACE, '"', ';' $len = strlen($value) + $add_len; } $quoted .= $prefix . $value . $suffix; } return " {$name}=\"{$quoted}\""; }
php
{ "resource": "" }
q265888
Mail_mimePart._explodeQuotedString
test
function _explodeQuotedString($delimiter, $string) { $result = array(); $strlen = strlen($string); for ($q=$p=$i=0; $i < $strlen; $i++) { if ($string[$i] == "\"" && (empty($string[$i-1]) || $string[$i-1] != "\\") ) { $q = $q ? false : true; } else if (!$q && preg_match("/$delimiter/", $string[$i])) { $result[] = substr($string, $p, $i - $p); $p = $i + 1; } } $result[] = substr($string, $p); return $result; }
php
{ "resource": "" }
q265889
Mail_mimePart.encodeHeaderValue
test
function encodeHeaderValue($value, $charset, $encoding, $prefix_len=0, $eol="\r\n") { // #17311: Use multibyte aware method (requires mbstring extension) if ($result = Mail_mimePart::encodeMB($value, $charset, $encoding, $prefix_len, $eol)) { return $result; } // Generate the header using the specified params and dynamicly // determine the maximum length of such strings. // 75 is the value specified in the RFC. $encoding = $encoding == 'base64' ? 'B' : 'Q'; $prefix = '=?' . $charset . '?' . $encoding .'?'; $suffix = '?='; $maxLength = 75 - strlen($prefix . $suffix); $maxLength1stLine = $maxLength - $prefix_len; if ($encoding == 'B') { // Base64 encode the entire string $value = base64_encode($value); // We can cut base64 every 4 characters, so the real max // we can get must be rounded down. $maxLength = $maxLength - ($maxLength % 4); $maxLength1stLine = $maxLength1stLine - ($maxLength1stLine % 4); $cutpoint = $maxLength1stLine; $output = ''; while ($value) { // Split translated string at every $maxLength $part = substr($value, 0, $cutpoint); $value = substr($value, $cutpoint); $cutpoint = $maxLength; // RFC 2047 specifies that any split header should // be separated by a CRLF SPACE. if ($output) { $output .= $eol . ' '; } $output .= $prefix . $part . $suffix; } $value = $output; } else { // quoted-printable encoding has been selected $value = Mail_mimePart::encodeQP($value); // This regexp will break QP-encoded text at every $maxLength // but will not break any encoded letters. $reg1st = "|(.{0,$maxLength1stLine}[^\=][^\=])|"; $reg2nd = "|(.{0,$maxLength}[^\=][^\=])|"; if (strlen($value) > $maxLength1stLine) { // Begin with the regexp for the first line. $reg = $reg1st; $output = ''; while ($value) { // Split translated string at every $maxLength // But make sure not to break any translated chars. $found = preg_match($reg, $value, $matches); // After this first line, we need to use a different // regexp for the first line. $reg = $reg2nd; // Save the found part and encapsulate it in the // prefix & suffix. Then remove the part from the // $value_out variable. if ($found) { $part = $matches[0]; $len = strlen($matches[0]); $value = substr($value, $len); } else { $part = $value; $value = ''; } // RFC 2047 specifies that any split header should // be separated by a CRLF SPACE if ($output) { $output .= $eol . ' '; } $output .= $prefix . $part . $suffix; } $value = $output; } else { $value = $prefix . $value . $suffix; } } return $value; }
php
{ "resource": "" }
q265890
Mail_mimePart.encodeMB
test
function encodeMB($str, $charset, $encoding, $prefix_len=0, $eol="\r\n") { if (!function_exists('mb_substr') || !function_exists('mb_strlen')) { return; } $encoding = $encoding == 'base64' ? 'B' : 'Q'; // 75 is the value specified in the RFC $prefix = '=?' . $charset . '?'.$encoding.'?'; $suffix = '?='; $maxLength = 75 - strlen($prefix . $suffix); // A multi-octet character may not be split across adjacent encoded-words // So, we'll loop over each character // mb_stlen() with wrong charset will generate a warning here and return null $length = mb_strlen($str, $charset); $result = ''; $line_length = $prefix_len; if ($encoding == 'B') { // base64 $start = 0; $prev = ''; for ($i=1; $i<=$length; $i++) { // See #17311 $chunk = mb_substr($str, $start, $i-$start, $charset); $chunk = base64_encode($chunk); $chunk_len = strlen($chunk); if ($line_length + $chunk_len == $maxLength || $i == $length) { if ($result) { $result .= "\n"; } $result .= $chunk; $line_length = 0; $start = $i; } else if ($line_length + $chunk_len > $maxLength) { if ($result) { $result .= "\n"; } if ($prev) { $result .= $prev; } $line_length = 0; $start = $i - 1; } else { $prev = $chunk; } } } else { // quoted-printable // see encodeQP() $regexp = '/([\x22-\x29\x2C\x2E\x3A-\x40\x5B-\x60\x7B-\x7E\x80-\xFF])/'; for ($i=0; $i<=$length; $i++) { $char = mb_substr($str, $i, 1, $charset); // RFC recommends underline (instead of =20) in place of the space // that's one of the reasons why we're not using iconv_mime_encode() if ($char == ' ') { $char = '_'; $char_len = 1; } else { $char = preg_replace_callback( $regexp, array('Mail_mimePart', '_qpReplaceCallback'), $char ); $char_len = strlen($char); } if ($line_length + $char_len > $maxLength) { if ($result) { $result .= "\n"; } $line_length = 0; } $result .= $char; $line_length += $char_len; } } if ($result) { $result = $prefix .str_replace("\n", $suffix.$eol.' '.$prefix, $result).$suffix; } return $result; }
php
{ "resource": "" }
q265891
AdminController.getMessages
test
public function getMessages() { $table = new AdminMessages(Message::query()); $table->with(['recipient', 'sender']); if (mustard_loaded('feedback')) { $table->with(['recipient.feedbackReceived', 'sender.feedbackReceived']); } return view('mustard::admin.messages', [ 'table' => $table, 'messages' => $table->paginate(), ]); }
php
{ "resource": "" }
q265892
FilePointer.getLine
test
public function getLine() { return (feof($this->fp)) ? false : fgets($this->fp, $this->lineReadLength); }
php
{ "resource": "" }
q265893
Dropdown.renderItems
test
protected function renderItems($items, $options = []) { $lines = []; foreach ($items as $item) { if (is_string($item)) { if ($item === static::DIVIDER) { $lines[] = $this->renderDivider(); } else { $lines[] = $item; } continue; } if (isset($item['visible']) && !$item['visible']) { continue; } if (!array_key_exists('label', $item)) { throw new InvalidConfigException("The 'label' option is required."); } $encodeLabel = isset($item['encode']) ? $item['encode'] : $this->encodeLabels; $label = $encodeLabel ? $this->htmlHlp->encode($item['label']) : $item['label']; $itemOptions = ArrayHelper::getValue($item, 'options', []); $linkOptions = ArrayHelper::getValue($item, 'linkOptions', []); $itemOptions = ArrayHelper::merge($itemOptions, $linkOptions); Html::addCssClass($itemOptions, ['widget' => 'dropdown-item']); $url = array_key_exists('url', $item) ? $item['url'] : null; if ($url === null) { Html::addCssClass($itemOptions, ['widget' => 'dropdown-header']); $content = $this->renderHeader($label); } else { $content = $this->htmlHlp->a($label, $url, $itemOptions); } $lines[] = $content; } return $this->htmlHlp->tag('div', implode("\n", $lines), $options); }
php
{ "resource": "" }
q265894
Pff2Annotations.doBefore
test
public function doBefore() { $class_name = get_class($this->_controller); $this->classAnnotations = $this->reader->getClassAnnotations($class_name); $this->methodAnnotations = $this->reader->getMethodAnnotations($class_name, $this->_controller->getAction()); }
php
{ "resource": "" }
q265895
Zend_Cache_Core.setOption
test
public function setOption($name, $value) { if (!is_string($name)) { Zend_Cache::throwException("Incorrect option name!"); } $name = strtolower($name); if (array_key_exists($name, $this->_options)) { // This is a Core option $this->_setOption($name, $value); return; } if (array_key_exists($name, $this->_specificOptions)) { // This a specic option of this frontend $this->_specificOptions[$name] = $value; return; } }
php
{ "resource": "" }
q265896
Inflector.slug
test
public function slug($string, $replacement = '-', $lowercase = true) { return $this->proxy(__FUNCTION__, [$string, $replacement, $lowercase]); }
php
{ "resource": "" }
q265897
Inflector.sentence
test
public function sentence(array $words, $twoWordsConnector = null, $lastWordConnector = null, $connector = ', ') { return $this->proxy(__FUNCTION__, [$words, $twoWordsConnector, $lastWordConnector, $connector]); }
php
{ "resource": "" }
q265898
Gallery.extractGalleryArray
test
private function extractGalleryArray($data) { if ($data->stat == 'fail') { return; } $photoset = &$data->photoset; $photo = $this->newPhoto(); $gallery = []; $gallery['id'] = $photoset->id; $gallery['title'] = $photoset->title->_content; $gallery['description'] = $photoset->description->_content; $gallery['photos'] = $photo->all($photoset->id); $gallery['created'] = (string) $photoset->date_create; $gallery['url'] = 'https://www.flickr.com/photos/'; $gallery['url'] .= $photoset->owner; $gallery['url'] .= '/sets/'; $gallery['url'] .= $photoset->id; $gallery['size'] = $photoset->count_photos; $gallery['user_id'] = $photoset->owner; $gallery['thumbnail'] = $photoset->primary; $gallery['views'] = $photoset->count_views; return $gallery; }
php
{ "resource": "" }
q265899
AbstractAdapter.isValid
test
public function isValid($session) { return ($this->getModifiedValue($session)->getTimestamp() + $this->getLifetimeValue($session)) > time(); }
php
{ "resource": "" }