_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q252100
Container.cacheMarkers
validation
protected function cacheMarkers(string $marker): void { $this->marked[$marker] = []; foreach ($this->definitions as $definition) { foreach ((array) $definition->markers as $m) { if ($m instanceof $marker) { $this->marked[$marker][] = [ $definition, $m ]; } } } }
php
{ "resource": "" }
q252101
Container.createObject
validation
protected function createObject(string $typeName, ?bool $nullable = false, ?bool $checkCycles = true, ?bool $treatAsNotFound = true): ?object { if ($checkCycles) { $this->underConstruction[$typeName] = true; } try { if (!isset($this->typeCache[$typeName])) { if (\class_exists($typeName) || \interface_exists($typeName, false)) { $this->typeCache[$typeName] = new \ReflectionClass($typeName); } else { $this->typeCache[$typeName] = false; } } if ($this->typeCache[$typeName] === false) { if ($nullable) { return null; } if ($treatAsNotFound) { throw new NotFoundException(\sprintf('Cannot load type: %s', $typeName)); } throw new ContainerException(\sprintf('Cannot load type: %s', $typeName)); } if (!$this->typeCache[$typeName]->isInstantiable()) { if ($nullable) { return null; } throw new NotFoundException(\sprintf('Type is not instantiable: %s', $typeName)); } if (isset($this->constructorCache[$typeName])) { $con = $this->constructorCache[$typeName]; } else { $con = $this->constructorCache[$typeName] = $this->typeCache[$typeName]->getConstructor() ?: false; } return ($con === false) ? new $typeName() : new $typeName(...$this->populateArguments($con, null, $typeName)); } finally { if ($checkCycles) { unset($this->underConstruction[$typeName]); } } }
php
{ "resource": "" }
q252102
Container.createObjectUsingFactory
validation
protected function createObjectUsingFactory(string $typeName, Factory $factory, ?bool $nullable = false): ?object { $this->underConstruction[$typeName] = true; try { // Assemble arguments and scope config objects to the bound type: $object = ($factory->callback)(...$this->populateArguments($factory->getReflection(), null, $typeName)); if (!$object instanceof $typeName) { if ($object === null && $nullable) { return null; } $type = \is_object($object) ? \get_class($object) : \gettype($object); throw new ContainerException(\sprintf('Factory must return an instance of %s, returned value is %s', $typeName, $type)); } } finally { unset($this->underConstruction[$typeName]); } return $object; }
php
{ "resource": "" }
q252103
Hasher.getHashes
validation
public function getHashes() { if (empty($this->hashes)) { $this->generateHashes(); } return json_encode($this->hashes, \sndsgd\Json::HUMAN); }
php
{ "resource": "" }
q252104
Hasher.createIterator
validation
protected function createIterator() { $options = \RecursiveDirectoryIterator::SKIP_DOTS; $iterator = new \RecursiveDirectoryIterator($this->dir, $options); $options = \RecursiveIteratorIterator::SELF_FIRST; return new \RecursiveIteratorIterator($iterator, $options); }
php
{ "resource": "" }
q252105
Hasher.generateHashes
validation
protected function generateHashes(): array { $dirLength = strlen($this->dir); foreach ($this->createIterator() as $file) { if (!$file->isFile()) { continue; } $realpath = $file->getRealPath(); $path = $file->getPath().DIRECTORY_SEPARATOR.$file->getFilename(); # skip aliases if ($realpath !== $path) { continue; } # remove the relative directory from the file path $path = substr($realpath, $dirLength); # map hashes by a lowercase version of the path # this should prevent issues caused by case sensitive filesystems $lowerPath = strtolower($path); if (isset($this->hashes[$lowerPath])) { $message = "duplicate file encountered: $path ($lowerPath)"; throw new \RuntimeException($message); } $this->hashes[$lowerPath] = sha1_file($realpath); } ksort($this->hashes); return $this->hashes; }
php
{ "resource": "" }
q252106
BaseInstanceWrapperComponent.setInstProperty
validation
protected function setInstProperty($inst, $propertyName, $mappingDefinition, $propertyValue = null) { if ($mappingDefinition === false) { return false; // Do not even attempt to set this property } if (func_num_args() <= 3) { $propertyValue = $this->$propertyName; } if ($mappingDefinition === true || is_string($mappingDefinition)) { $instPropertyName = $mappingDefinition === true ? $propertyName : $mappingDefinition; $setInstPropertyMethod = 'setInstProperty' . ucfirst($instPropertyName); if (method_exists($this, $setInstPropertyMethod)) { $this->$setInstPropertyMethod($propertyValue, $inst); return; } else { $instSetterMethod = 'set' . ucfirst($instPropertyName); if (method_exists($inst, $instSetterMethod)) { $inst->$instSetterMethod($propertyValue); return; } else { $inst->$instPropertyName = $propertyValue; return; } } } elseif (is_array($mappingDefinition)) { if (reset($mappingDefinition) === null) { $mappingDefinition[0] = $inst; call_user_func_array($mappingDefinition, [$propertyValue]); return; } elseif (reset($mappingDefinition) === $this) { call_user_func_array($mappingDefinition, [$propertyValue, $inst]); return; } } throw new \yii\base\ErrorException('Could not set property ' . $propertyName . ' in wrapped object'); }
php
{ "resource": "" }
q252107
BaseInstanceWrapperComponent.createNewInst
validation
protected function createNewInst() { $classReflection = new \ReflectionClass($this->instClass); if ($this->constructorArgs === null) { return $classReflection->newInstance(); } else { return $classReflection->newInstanceArgs($this->concstructorArgs); } }
php
{ "resource": "" }
q252108
IdentityModel.getList
validation
public function getList(): IDataSource { $columns = array_map(function ($item) { return $this->tableName[0] . '.' . $item; }, $this->columns); return $this->connection->select($columns)->from($this->tableIdentity)->as($this->tableName[0]); }
php
{ "resource": "" }
q252109
IdentityModel.getById
validation
public function getById(int $id) { /** @noinspection PhpUndefinedMethodInspection */ return $this->getList() ->where([$this->tableName[0] . '.' . self::COLUMN_ID => $id]) ->fetch(); }
php
{ "resource": "" }
q252110
IdentityModel.getByEmail
validation
public function getByEmail(string $email) { // get by id and active must by true /** @noinspection PhpUndefinedMethodInspection */ return $this->getList() ->where([$this->tableName[0] . '.email' => $email, $this->tableName[0] . '.active' => true]) ->fetch(); }
php
{ "resource": "" }
q252111
IdentityModel.verifyHash
validation
public function verifyHash(string $password, string $hash): bool { return Passwords::verify($password, $hash); }
php
{ "resource": "" }
q252112
IdentityModel.existLogin
validation
public function existLogin(string $login): int { return (int) $this->connection->select(self::COLUMN_ID) ->from($this->tableIdentity) ->where(['login' => $login]) ->fetchSingle(); }
php
{ "resource": "" }
q252113
IdentityModel.existEmail
validation
public function existEmail(string $email): int { return (int) $this->connection->select(self::COLUMN_ID) ->from($this->tableIdentity) ->where(['email' => $email]) ->fetchSingle(); }
php
{ "resource": "" }
q252114
IdentityModel.cleanUser
validation
public function cleanUser(string $validate = null): int { $result = 0; if ($validate) { $validateTo = new DateTime; $validateTo->modify($validate); /** @noinspection PhpUndefinedMethodInspection */ $list = $this->getList() ->where([ $this->tableName[0] . '.active' => false, $this->tableName[0] . '.added IS NOT NULL', [$this->tableName[0] . '.added<=%dt', $validateTo], ]); foreach ($list as $item) { if ($this->delete($item[self::COLUMN_ID])) { $result++; } } } return $result; }
php
{ "resource": "" }
q252115
IdentityModel.getEncodeHash
validation
public function getEncodeHash(int $id, string $slug, string $linkValidate = null): string { return base64_encode(uniqid(($linkValidate ? strtotime($linkValidate) : self::NO_TIME) . self::TIME_SEPARATOR, true) . self::PART_SEPARATOR . $this->getHash($id . $slug) . self::ID_SEPARATOR . $id); }
php
{ "resource": "" }
q252116
IdentityModel.getDecodeHash
validation
public function getDecodeHash(string $hash): array { $decode = base64_decode($hash); list($part1, $part2) = explode(self::PART_SEPARATOR, $decode); $p1 = explode(self::TIME_SEPARATOR, $part1); list($linkValidate,) = $p1; // get validate int $id = null; $verifyHash = null; $dateNow = new DateTime(); $dateValidate = $dateNow; if ($linkValidate == self::NO_TIME) { // parameter $linkValidate is null -> generate now $linkValidate = $dateNow->getTimestamp(); } $dateValidate->setTimestamp((int) $linkValidate); // convert validate int do datetime if ($dateValidate >= $dateNow) { // check expiration $p2 = explode(self::ID_SEPARATOR, $part2); $verifyHash = implode('.', array_slice($p2, 0, -1)); // regenerate hash $id = $p2[count($p2) - 1]; // get id from last part } else { throw new IdentityException('Activate link is expired!'); } return ['id' => $id, 'verifyHash' => $verifyHash, 'expired' => (int) $linkValidate]; }
php
{ "resource": "" }
q252117
IdentityModel.processApprove
validation
public function processApprove(string $hash): bool { $decode = $this->getDecodeHash($hash); $id = (int) $decode['id']; $verifyHash = $decode['verifyHash']; $item = $this->getById($id); // load row from db if ($item && $id == $item['id']) { // not null result if (!$item['active']) { if ($this->verifyHash($item['id'] . $item['login'], $verifyHash)) { // check hash and password return $this->update($item['id'], ['active' => true]); // final activate user } else { throw new IdentityException('Invalid hash!'); } } else { // basic check expire link (after click), next check is only active status not datetime! - execute update only if not active throw new IdentityException('User is already approve!'); } } else { throw new IdentityException('User does not exist!'); } }
php
{ "resource": "" }
q252118
IdentityModel.isValidForgotten
validation
public function isValidForgotten(string $hash): bool { $decode = $this->getDecodeHash($hash); $id = (int) $decode['id']; $verifyHash = $decode['verifyHash']; $item = $this->getById($id); // load row from db if ($item && $id == $item['id']) { // not null result // check hash and password return $this->verifyHash($item['id'] . $item['login'], $verifyHash); } return false; }
php
{ "resource": "" }
q252119
IdentityModel.processForgotten
validation
public function processForgotten(string $hash, string $password): bool { $decode = $this->getDecodeHash($hash); $id = (int) $decode['id']; $verifyHash = $decode['verifyHash']; $item = $this->getById($id); // load row from db if ($item && $id == $item['id']) { // not null result $values['hash'] = $this->getHash($password); // auto hash password if ($this->verifyHash($item['id'] . $item['login'], $verifyHash)) { // check hash and password return $this->update($item['id'], $values); // final save user } else { throw new IdentityException('Invalid hash!'); } } else { throw new IdentityException('User does not exist!'); } }
php
{ "resource": "" }
q252120
ErrorHandler.convertExceptionToArray
validation
protected function convertExceptionToArray($exception) { if (!YII_DEBUG && !$exception instanceof UserException && !$exception instanceof HttpException) { $exception = new HttpException(500, 'There was an error at the server.'); } $array = [ 'name' => ($exception instanceof Exception || $exception instanceof ErrorException) ? $exception->getName() : 'Exception', 'message' => $exception->getMessage(), 'code' => $exception->getCode(), ]; if ($exception instanceof HttpException) { $array['status'] = $exception->statusCode; } if (YII_DEBUG) { $array['type'] = get_class($exception); if (!$exception instanceof UserException) { $array['file'] = $exception->getFile(); $array['line'] = $exception->getLine(); $array['stack-trace'] = explode("\n", $exception->getTraceAsString()); if ($exception instanceof \yii\db\Exception) { $array['error-info'] = $exception->errorInfo; } } } if (($prev = $exception->getPrevious()) !== null) { $array['previous'] = $this->convertExceptionToArray($prev); } return $array; }
php
{ "resource": "" }
q252121
ErrorHandler.renderPreviousExceptions
validation
public function renderPreviousExceptions($exception) { if (($previous = $exception->getPrevious()) !== null) { return $this->renderFile($this->previousExceptionView, ['exception' => $previous]); } else { return ''; } }
php
{ "resource": "" }
q252122
PathConfig.checkPaths
validation
public function checkPaths() { if ($this->path_checked) return true; foreach (array('root', 'webroot') as $type) { $path = $this->$type; if (!file_exists($path) || !is_dir($path)) throw new IOException("Path '$type' does not exist: " . $path); if (!is_readable($path)) throw new PermissionError($path, "Path '$type' cannot be read"); } if (!is_dir($this->config) || is_readable($this->config)) $this->config = null; foreach (array('var', 'cache', 'log', 'uploads') as $write_dir) { $path = $this->$write_dir; if (!is_dir($path)) { $dn = dirname($path); if (!file_exists($path) && $dn === $this->var) { // The parent directory is var/ and must be writeable as // this was checked earlier in this loop. Path::mkdir($path); } else { if (file_exists($path)) throw new IOException("Path '$write_dir' exists but is not a directory: " . $path); $this->$write_dir = null; continue; } } if (!is_writable($path)) { try { // We can try to fix permissions if we own the file Path::makeWritable($path); } catch (PermissionError $e) { $this->$write_dir = null; if ($this->cli) WF::debug("Failed to get write access to: %s", $e->getMessage()); } } } $this->path_checked = true; return true; }
php
{ "resource": "" }
q252123
EventDispatcherCollection.aggregateTernaryValues
validation
protected function aggregateTernaryValues(array $values) { if (in_array(false, $values, true)) { return false; } elseif (in_array(true, $values, true)) { return true; } else { return null; } }
php
{ "resource": "" }
q252124
ErrorStreamClient.reportException
validation
public function reportException(\Exception $ex) { $report = new ErrorStreamReport(); $report->error_group = $ex->getMessage().':'.$ex->getLine(); $report->line_number = $ex->getLine(); $report->file_name = $ex->getFile(); $report->message = $ex->getMessage(); $report->stack_trace = $ex->getTraceAsString(); $report->severity = 3; return $this->report($report); }
php
{ "resource": "" }
q252125
ErrorStreamClient.report
validation
public function report(ErrorStreamReport $report) { $report->tags = $this->tags; $report->context = $this->context; return $this->makeRequest($report); }
php
{ "resource": "" }
q252126
ErrorStreamClient.makeRequest
validation
protected function makeRequest($data) { $url = 'https://www.errorstream.com/api/1.0/errors/create?'.http_build_query(['api_token' => $this->api_token, 'project_token' => $this->project_token]); try { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); curl_close($ch); return $result; } catch (\Exception $ex){ return $ex->getMessage(); } }
php
{ "resource": "" }
q252127
AuthSession.startSession
validation
protected function startSession(Request $request, $sessionId) { return tap($this->getSession($sessionId), function ($session) use ($request) { $session->setRequestOnHandler($request); $session->start(); }); }
php
{ "resource": "" }
q252128
AuthSession.getSession
validation
public function getSession($sessionId) { return tap($this->manager->driver(), function ($session) use ($sessionId) { $session->setId($sessionId); }); }
php
{ "resource": "" }
q252129
CLI.addOption
validation
public function addOption($short, $long, $arg, $description) { $this->parameters[] = array( $short, $long, $arg, $description ); return $this; }
php
{ "resource": "" }
q252130
CLI.parse
validation
public function parse() { list($opt_str, $long_opts, $mapping) = $this->getOptString(); $opts = \getopt($opt_str, $long_opts); $options = $this->mapOptions($opts, $mapping); return new Dictionary($options); }
php
{ "resource": "" }
q252131
CLI.input
validation
public static function input($prompt, $default = null) { $ret = false; while (!$ret) { if ($prompt) { echo $prompt; if ($default) echo " (" . $default . ")"; echo ": "; } $ret = trim(fgets(STDIN)); if (!$ret && $default !== null) return $default; } return trim($ret); }
php
{ "resource": "" }
q252132
CLI.syntax
validation
public function syntax($error = "Please specify valid options") { $ostr = (!$error) ? STDOUT : STDERR; if (is_string($error)) fprintf($ostr, "Error: %s\n", $error); fprintf($ostr, "Syntax: php " . $_SERVER['argv'][0] . " <options> <action>\n\n"); fprintf($ostr, "Options: \n"); $max_opt_length = 0; $max_arg_length = 0; // Sort the parameters alphabetically $params = $this->parameters; usort($params, function ($a, $b) { $lo = !empty($a[0]) ? $a[0] : $a[1]; $ro = !empty($b[0]) ? $b[0] : $b[1]; return strcmp($lo, $ro); }); foreach ($params as $param) { $max_opt_length = max(strlen($param[1]) + 3, $max_opt_length); $max_arg_length = max(strlen($param[2]) + 3, $max_arg_length); } foreach ($this->parameters as $param) { fprintf($ostr, " "); $so = $param[0] ? "-" . $param[0] : ""; $lo = $param[1] ? "--" . $param[1] : ""; $arg = $param[2] ? '<' . $param[2] . '>' : ""; $pstr = sprintf("%-2s %-" . $max_opt_length . "s %-" . $max_arg_length . "s ", $so, $lo, $arg); $indent = strlen($pstr) + 4; fprintf($ostr, $pstr); self::formatText($indent, self::MAX_LINE_LENGTH, $param[3], $ostr); } exit($error === false ? 0 : 1); }
php
{ "resource": "" }
q252133
IntType.isPrime
validation
public function isPrime() { if ($this->value < 2) { return false; } if ($this->value === 2) { return true; } if ($this->isEven()) { return false; } for ($i = 3; $i <= ceil(sqrt($this->value)); $i = $i + 2) { if ($this->value % $i == 0) { return false; } } return true; }
php
{ "resource": "" }
q252134
UriCollection.add
validation
public function add($name, UriInterface $uri) { unset($this->uris[$name]); $this->uris[$name] = $uri; }
php
{ "resource": "" }
q252135
UriCollection.get
validation
public function get($name) { return isset($this->uris[$name]) ? $this->uris[$name] : null; }
php
{ "resource": "" }
q252136
UriCollection.addCollection
validation
public function addCollection(UriCollection $collection) { // we need to remove all uris with the same names first because just replacing them // would not place the new uri at the end of the merged array foreach ($collection->all() as $name => $uri) { unset($this->uris[$name]); $this->uris[$name] = $uri; } $this->resources = array_merge($this->resources, $collection->getResources()); }
php
{ "resource": "" }
q252137
UriCollection.setHost
validation
public function setHost($host) { foreach ($this->uris as $name => $uri) { $this->add($name, $uri->withHost($host)); } }
php
{ "resource": "" }
q252138
UriCollection.setScheme
validation
public function setScheme($scheme) { foreach ($this->uris as $name => $uri) { $this->add($name, $uri->withScheme($scheme)); } }
php
{ "resource": "" }
q252139
Entity.getScheme
validation
public function getScheme(): array { if (null === $this->scheme) { $raw = $this->medoo->query('DESCRIBE '.$this->getTable())->fetchAll(); $this->scheme = []; foreach ($raw as $field) { $this->scheme[$field['Field']] = $field; } } return $this->scheme; }
php
{ "resource": "" }
q252140
Entity.save
validation
public function save(bool $validate = true): self { if ($validate && $this->validate()) { throw new Exception('Entity '.$this->__getEntityName().' data is not valid'); } /** * Remove fields that not exists in DB table scheme, * to avoid thrown exceptions on saving garbadge fields. */ $scheme = \array_keys($this->getScheme()); foreach ($this->data as $key => $value) { if (!\in_array($key, $scheme, true)) { unset($this->data[$key]); } } if ($this->getId()) { $this->medoo->update($this->getTable(), $this->data, ['id' => $this->getId()]); } else { $this->medoo->insert($this->getTable(), $this->data); $this->setId($this->medoo->id()); } $this->sentry->breadcrumbs->record([ 'message' => 'Entity '.$this->__getEntityName().'::save()', 'data' => ['query' => $this->medoo->last()], 'category' => 'Database', 'level' => 'info', ]); return $this; }
php
{ "resource": "" }
q252141
Entity.validate
validation
public function validate(string $method = 'save'): array { $errors = []; foreach ($this->getValidators()[$method] ?? [] as $field => $validator) { try { $validator->setName($field)->assert($this->get($field)); } catch (NestedValidationException $e) { $errors[$field] = $e->getMessages(); } } return $errors; }
php
{ "resource": "" }
q252142
Entity.loadAll
validation
public function loadAll(array $where = [], bool $assoc = false, array $fields = null): Collection { $allData = $this->medoo->select($this->getTable(), $fields ? $fields : '*', $where); $this->sentry->breadcrumbs->record([ 'message' => 'Entity '.$this->__getEntityName().'::loadAll('.\print_r($where, true).', '.$assoc.', '.\print_r($fields, true).')', 'data' => ['query' => $this->medoo->last()], 'category' => 'Database', 'level' => 'info', ]); $items = []; foreach ($allData as $data) { $items[] = ($assoc) ? $data : $this->container['entity']($this->__getEntityName())->setData($data); } return new Collection($items); }
php
{ "resource": "" }
q252143
Entity.loadRelation
validation
public function loadRelation(string $name) { if (!isset($this->relationObjects[$name]) || empty($this->relationObjects[$name])) { $relation = $this->getRelations()[$name]; if (!$relation || !$relation['entity'] || !$this->get($relation['key'] ?? 'id')) { return null; } $entity = $this->entity($relation['entity']); $type = $relation['type'] ?? 'has_one'; $key = $relation['key'] ?? ('has_one' === $type ? $this->__getEntityName().'_id' : 'id'); $foreignKey = $relation['foreign_key'] ?? ('has_one' === $type ? 'id' : $this->__getEntityName().'_id'); $assoc = $relation['assoc'] ?? false; $this->relationObjects[$name] = ('has_one' === $type) ? $entity->load($this->get($key), $foreignKey) : $entity->loadAll([$foreignKey => $this->get($key)], $assoc); } return $this->relationObjects[$name] ?? null; }
php
{ "resource": "" }
q252144
Entity.delete
validation
public function delete(): bool { return (bool) $this->medoo->delete($this->getTable(), ['id' => $this->getId()]); }
php
{ "resource": "" }
q252145
DirEntity.isEmpty
validation
public function isEmpty() { if ($this->test(\sndsgd\Fs::EXISTS | \sndsgd\Fs::READABLE) === false) { throw new \RuntimeException( "failed to determine if a directory is empty; ".$this->getError() ); } return count(scandir($this->path)) === 2; }
php
{ "resource": "" }
q252146
DirEntity.getList
validation
public function getList($asStrings = false) { $list = scandir($this->path); if ($asStrings === true) { return array_diff($list, [".", ".."]); } $ret = []; foreach ($list as $name) { if ($name === "." || $name === "..") { continue; } $path = $this->path.DIRECTORY_SEPARATOR.$name; $ret[] = (is_dir($path)) ? new static($path) : new FileEntity($path); } return $ret; }
php
{ "resource": "" }
q252147
DirEntity.remove
validation
public function remove(): bool { if ($this->test(\sndsgd\Fs::EXISTS | \sndsgd\Fs::READABLE | \sndsgd\Fs::WRITABLE) === false) { $this->error = "failed to remove directory; {$this->error}"; return false; } foreach ($this->getList() as $entity) { if ($entity->remove() === false) { $this->error = $entity->getError(); return false; } } if (@rmdir($this->path) === false) { $this->setError("failed to remove directory '{$this->path}'"); return false; } return true; }
php
{ "resource": "" }
q252148
QueryParams.get
validation
public static function get(array $server): array { $params = []; if (isset($server['QUERY_STRING'])) { $query = ltrim($server['QUERY_STRING'], '?'); foreach (explode('&', $query) as $pair) { if ($pair) { list($name, $value) = self::normalize( array_map('urldecode', explode('=', $pair, 2)) ); $params[$name][] = $value; } } } return $params ? array_map(function ($v) { return count($v) === 1 ? $v[0] : $v; }, $params) : $params; }
php
{ "resource": "" }
q252149
Binding.instance
validation
public function instance(object $object): Binding { if (!$object instanceof $this->definition->typeName) { throw new \InvalidArgumentException(\sprintf('%s is not an instance of %s', \get_class($object), $this->definition->typeName)); } $this->definition->instantiator = new Instance($object); return $this; }
php
{ "resource": "" }
q252150
Binding.inject
validation
public function inject(string ...$methods): Binding { if ($this->definition->injects === null) { $this->definition->injects = \array_fill_keys($methods, true); } else { foreach ($methods as $f) { $this->definition->injects[$f] = true; } } return $this; }
php
{ "resource": "" }
q252151
Binding.decorate
validation
public function decorate(callable $decorator): Binding { if (empty($this->definition->decorators)) { $this->definition->decorators = []; } $this->definition->decorators[] = new Decorator($decorator); return $this; }
php
{ "resource": "" }
q252152
Binding.marked
validation
public function marked(Marker ...$markers): Binding { if (empty($this->definition->markers)) { $this->definition->markers = []; } foreach ($markers as $marker) { $types = $marker->getAllowedTyes(); if (empty($types)) { $this->definition->markers[] = $marker; continue; } foreach ($types as $type) { if ($this->definition->typeName == $type || \is_subclass_of($this->definition->typeName, $type)) { $this->definition->markers[] = $marker; continue 2; } } throw new \RuntimeException(\vsprintf('Type %s cannot be marked with %s, allowed types are [ %s ]', [ $this->definition->typeName, \get_class($marker), \implode(', ', $types) ])); } return $this; }
php
{ "resource": "" }
q252153
InputOutputTiming.convertDateTimeToUtcTimeZone
validation
public function convertDateTimeToUtcTimeZone($inStrictIso8601DtTm) { $tmpDateTimeIn = $this->convertTimeFromFormatSafely($inStrictIso8601DtTm); $tmpDateTimeIn->setTimezone(new \DateTimeZone('UTC')); return $tmpDateTimeIn->format('Y-m-d H:i:s'); }
php
{ "resource": "" }
q252154
AppRunner.setVariable
validation
public function setVariable(string $name, $value, bool $as_instance = true) { $this->variables[$name] = $value; if (is_object($value)) $this->instances[get_class($value)] = $value; return $this; }
php
{ "resource": "" }
q252155
AppRunner.execute
validation
public function execute() { try { // No output should be produced by apps directly, so buffer // everything, and log afterwards $this->output_buffer_level = ob_get_level(); ob_start(); $response = $this->doExecute(); if ( (is_object($response) && !($response instanceof Response)) || (is_string($response) && class_exists($response)) ) { $response = $this->reflect($response); } if ($response instanceof Response) throw $response; throw new HTTPError(500, "App did not produce any response"); } catch (Response $response) { self::$logger->debug("Response type {0} returned from controller: {1}", [get_class($response), $this->app]); throw $response; } catch (Throwable $e) { self::$logger->debug("While executing controller: {0}", [$this->app]); self::$logger->notice( "Unexpected exception of type {0} thrown while processing request: {1}", [get_class($e), $e] ); throw $e; } finally { $this->logScriptOutput(); } }
php
{ "resource": "" }
q252156
AppRunner.findController
validation
protected function findController($object) { // Get the next URL argument $urlargs = $this->arguments; $arg = $urlargs->shift(); // Store it as controller name $controller = $arg; // Strip any suffix if (($pos = strpos($controller, '.')) !== false) $controller = substr($controller, 0, $pos); // Check if the method exists if (!method_exists($object, $controller)) { // Fall back to an index method if (method_exists($object, "index")) { if ($controller !== null) $urlargs->unshift($arg); $controller = "index"; } else throw new HTTPError(404, "Unknown controller: " . $controller); } return $controller; }
php
{ "resource": "" }
q252157
AppRunner.logScriptOutput
validation
private function logScriptOutput() { $output_buffers = array(); $ob_cnt = 0; while (ob_get_level() > $this->output_buffer_level) { $output = trim(ob_get_contents()); ++$ob_cnt; ob_end_clean(); if (!empty($output)) { $lines = explode("\n", $output); foreach ($lines as $n => $line) self::$logger->debug("Script output: {0}/{1}: {2}", [$ob_cnt, $n + 1, $line]); } } }
php
{ "resource": "" }
q252158
MelisCmsPageHistoricRecentUserActivityPlugin.isCmsActive
validation
private function isCmsActive() { $melisCms = 'MelisCms'; $moduleSvc = $this->getServiceLocator()->get('ModulesService'); $modules = $moduleSvc->getActiveModules(); if(in_array($melisCms, $modules)) { return true; } return false; }
php
{ "resource": "" }
q252159
Db.getUserEntity
validation
public function getUserEntity($identity, $credential) { $credential = $this->preProcessCredential($credential); $userObject = NULL; // Cycle through the configured identity sources and test each $fields = $this->getOptions()->getAuthIdentityFields(); while ( !is_object($userObject) && count($fields) > 0 ) { $mode = array_shift($fields); switch ($mode) { case 'username': $userObject = $this->getMapper()->findByUsername($identity); break; case 'email': $userObject = $this->getMapper()->findByEmail($identity); break; } } if(!$userObject) { return null; } $bcrypt = new Bcrypt(); $bcrypt->setCost($this->getOptions()->getPasswordCost()); if (!$bcrypt->verify($credential, $userObject->getPassword())) { return null; } return $userObject; }
php
{ "resource": "" }
q252160
StopWords.getArray
validation
public static function getArray($language) { $fileName = __DIR__ . '/stop-words/' . $language . '.txt'; if (file_exists($fileName)) { return array_map('trim', file($fileName)); } return []; }
php
{ "resource": "" }
q252161
StopWords.getString
validation
public static function getString($language, $separator = ',') { $fileName = __DIR__ . '/stop-words/' . $language . '.txt'; if (file_exists($fileName)) { return implode($separator, array_map('trim', file($fileName))); } return ''; }
php
{ "resource": "" }
q252162
Table.setHeaders
validation
public function setHeaders(array $headers) { $columnNumber = 0; foreach ($headers as $header) { $this->updateWidth($columnNumber, $this->length($header)); if (!in_array($header, $this->headers)) { $this->headers[] = $header; } $columnNumber++; } }
php
{ "resource": "" }
q252163
Table.setRows
validation
public function setRows(array $rows) { foreach ($rows as $row) { $columnNumber = 0; if (!is_array($row)) { $row = [$row]; } foreach ($row as $column => $value) { $this->updateWidth($columnNumber, $this->length($column)); $this->updateWidth($columnNumber, $this->length($value)); if (!in_array($column, $this->columns)) { $this->columns[] = $column; } $columnNumber++; } $this->rows[] = $row; } }
php
{ "resource": "" }
q252164
Table.render
validation
public function render() { $output = []; // Top. if (count($this->rows) > 0) { $output[] = $this->renderLine(); } // Headers. if (count($this->columns) > 0) { $line = []; $line[] = $this->charVertical; $columnNumber = 0; foreach ($this->columns as $index => $column) { $title = $column; if (isset($this->headers[$index])) { $title = $this->headers[$index]; } $line[] = $this->renderCell($columnNumber, $title, ' ', 'info'); $line[] = $this->charVertical; $columnNumber++; } $output[] = implode('', $line); } // Body. if (count($this->rows) > 0) { // Middle. $output[] = $this->renderLine(); // Rows. foreach ($this->rows as $row) { $output[] = $this->renderRow($row); } // Footer $output[] = $this->renderLine(); } return implode("\n", $output); }
php
{ "resource": "" }
q252165
Table.renderLine
validation
private function renderLine() { $output = []; $output[] = $this->charCross; if (count($this->columns) > 0) { for ($columnNumber = 0; $columnNumber < count($this->columns); $columnNumber++) { $output[] = $this->renderCell($columnNumber, $this->charHorizontal, $this->charHorizontal); $output[] = $this->charCross; } } return implode('', $output); }
php
{ "resource": "" }
q252166
Table.renderRow
validation
private function renderRow(array $row) { $output = []; $output[] = $this->charVertical; $columnNumber = 0; foreach ($row as $column => $value) { $output[] = $this->renderCell($columnNumber, $value, ' '); $output[] = $this->charVertical; $columnNumber++; } return implode('', $output); }
php
{ "resource": "" }
q252167
Table.renderCell
validation
private function renderCell($columnNumber, $value, $filler, $style = '') { $output = []; $width = $this->getWidth($columnNumber); $output[] = $filler; while ($this->length($value) < $width) { $value .= $filler; } $output[] = Style::applyStyle($value, $style); $output[] = $filler; return implode('', $output); }
php
{ "resource": "" }
q252168
Table.updateWidth
validation
private function updateWidth($columnNumber, $width) { if ($width > $this->getWidth($columnNumber)) { $this->widths[$columnNumber] = $width; } }
php
{ "resource": "" }
q252169
DAL.executeInstruction
validation
public function executeInstruction(string $strSQL, ?array $parans = null) : bool { $this->dbPreparedStatment = $this->dbConnection->prepare($strSQL); $this->pdoLastError = null; if($parans !== null) { foreach($parans as $key => $value) { $val = $value; // Trata dados de tipos especiais if(is_bool($value) === true) { if($value === true) { $val = 1; } else { $val = 0; } } else if(is_a($value, "\DateTime") === true) { $val = $value->format("Y-m-d H:i:s"); } $this->dbPreparedStatment->bindValue(":" . $key, $val); } } try { $this->dbPreparedStatment->execute(); } catch (\Exception $ex) { $this->pdoLastError = $ex->getMessage(); } return $this->isExecuted(); }
php
{ "resource": "" }
q252170
DAL.getCountOf
validation
public function getCountOf(string $strSQL, ?array $parans = null) : int { $r = $this->getDataColumn($strSQL, $parans, "int"); return (($r === null) ? 0 : $r); }
php
{ "resource": "" }
q252171
DAL.countRowsFrom
validation
public function countRowsFrom(string $tableName, string $pkName) : int { $strSQL = "SELECT COUNT($pkName) as count FROM $tableName;"; return $this->getCountOf($strSQL); }
php
{ "resource": "" }
q252172
DAL.countRowsWith
validation
function countRowsWith(string $tablename, string $colName, $colValue) : int { $strSQL = "SELECT COUNT($colName) as count FROM $tablename WHERE $colName=:$colName;"; return $this->getCountOf($strSQL, ["$colName" => $colValue]); }
php
{ "resource": "" }
q252173
DAL.hasRowsWith
validation
public function hasRowsWith(string $tablename, string $colName, $colValue) : bool { return ($this->countRowsWith($tablename, $colName, $colValue) > 0); }
php
{ "resource": "" }
q252174
UriGenerator.resolveParams
validation
protected function resolveParams(UriInfo $info, array $params) { $uri = $info->getUri(); if(false === strpos($uri, '{')) { return $info; } $ctx = NULL; $result = ''; foreach(preg_split("'(\\{[^\\}]+\\})'", $uri, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) as $part) { if('{' != substr($part, 0, 1)) { $result .= $part; continue; } $placeholder = substr($part, 1, -1); if('*' == substr($placeholder, -1)) { $placeholder = substr($placeholder, 0, -1); $multi = true; } else { $multi = false; } switch(substr($placeholder, 0, 1)) { case '.': $placeholder = substr($placeholder, 1); $prefix = '.'; $join = $multi ? '.' : ','; break; case '/': $placeholder = substr($placeholder, 1); $prefix = '/'; $join = $multi ? '/' : ','; break; default: $prefix = ''; $join = ','; } if(false === strpos($placeholder, '.')) { $value = array_key_exists($placeholder, $params) ? $params[$placeholder] : $this; } else { if($ctx === NULL) { $ctx = $this->factory->createContext($params); } $value = $ctx->resolveValue(explode('.', $placeholder), $this); } if($value === $this) { $result .= $part; } elseif(is_array($value) || $value instanceof \Traversable) { $i = 0; foreach($value as $val) { $result .= (($i++ == 0) ? $prefix : $join) . Uri::encode($val, true); } } else { $result .= $prefix . Uri::encode($value, true); } } return new UriInfo($result, $info->getRouteName(), $info->getMethods(), $info->getHandler()); }
php
{ "resource": "" }
q252175
AuthDataDriver.is_php
validation
protected function is_php($version) { static $_is_php; $version = (string)$version; if (!isset($_is_php[$version])) { $_is_php[$version] = version_compare(PHP_VERSION, $version, '>='); } return $_is_php[$version]; }
php
{ "resource": "" }
q252176
ResettingController.checkEmailAction
validation
public function checkEmailAction() { $session = $this->get('session'); $email = $session->get(static::SESSION_EMAIL); $session->remove(static::SESSION_EMAIL); if (empty($email)) { return new RedirectResponse($this->get('router')->generate('miky_app_customer_resetting_request')); } return $this->render('MikyUserBundle:Frontend/Resetting:checkEmail.html.twig', array( 'email' => $email, )); }
php
{ "resource": "" }
q252177
ResettingController.authenticateUser
validation
protected function authenticateUser(CustomerInterface $user, Response $response) { try { $this->get('fos_user.security.login_manager')->loginUser( $this->getParameter('fos_user.firewall_name'), $user, $response); } catch (AccountStatusException $ex) { // We simply do not authenticate users which do not pass the user // checker (not enabled, expired, etc.). } }
php
{ "resource": "" }
q252178
ResettingController.getObfuscatedEmail
validation
protected function getObfuscatedEmail(CustomerInterface $user) { $email = $user->getEmail(); if (false !== $pos = strpos($email, '@')) { $email = '...' . substr($email, $pos); } return $email; }
php
{ "resource": "" }
q252179
LogParser.populateEntries
validation
private static function populateEntries($heading, $data, $key) { foreach (LogLevels::all() as $level) { if (self::hasLogLevel($heading[$key], $level)) { self::$parsed[] = [ 'level' => $level, 'header' => $heading[$key], 'stack' => $data[$key], ]; } } }
php
{ "resource": "" }
q252180
Keeper.get
validation
public function get($key) { if (!($time = $this->driver->get($key))) { if ($key == self::LAST_UPDATE_KEY) { $time = $this->reset(); } else { $time = $this->get(self::LAST_UPDATE_KEY); } } return $time; }
php
{ "resource": "" }
q252181
Keeper.getResponse
validation
public function getResponse($params = [], $lifetime = -1, Response $response = null) { if (!$response) { $response = new Response(); } if (!$this->enable) { return $response; } return $this->configurator->configure($response, $this->getMax($params), $lifetime); }
php
{ "resource": "" }
q252182
Keeper.getModifiedResponse
validation
public function getModifiedResponse(Request $request, $params = [], $lifetime = -1, Response $response = null) { $response = $this->getResponse($params, $lifetime, $response); if ($response->isNotModified($request)) { throw new NotModifiedException($response); } return $response; }
php
{ "resource": "" }
q252183
Keeper.reset
validation
private function reset() { $time = new \DateTime(); $this->driver->set(self::LAST_UPDATE_KEY, $time); return $time; }
php
{ "resource": "" }
q252184
FixedBitNotation.encode
validation
public function encode($rawString) { // Unpack string into an array of bytes $bytes = unpack('C*', $rawString); $byteCount = count($bytes); $encodedString = ''; $byte = array_shift($bytes); $bitsRead = 0; $chars = $this->chars; $bitsPerCharacter = $this->bitsPerCharacter; $rightPadFinalBits = $this->rightPadFinalBits; $padFinalGroup = $this->padFinalGroup; $padCharacter = $this->padCharacter; // Generate encoded output; // each loop produces one encoded character for ($c = 0; $c < $byteCount * 8 / $bitsPerCharacter; ++$c) { // Get the bits needed for this encoded character if ($bitsRead + $bitsPerCharacter > 8) { // Not enough bits remain in this byte for the current // character // Save the remaining bits before getting the next byte $oldBitCount = 8 - $bitsRead; $oldBits = $byte ^ ($byte >> $oldBitCount << $oldBitCount); $newBitCount = $bitsPerCharacter - $oldBitCount; if (!$bytes) { // Last bits; match final character and exit loop if ($rightPadFinalBits) { $oldBits <<= $newBitCount; } $encodedString .= $chars[$oldBits]; if ($padFinalGroup) { // Array of the lowest common multiples of // $bitsPerCharacter and 8, divided by 8 $lcmMap = array(1 => 1, 2 => 1, 3 => 3, 4 => 1, 5 => 5, 6 => 3, 7 => 7, 8 => 1); $bytesPerGroup = $lcmMap[$bitsPerCharacter]; $pads = $bytesPerGroup * 8 / $bitsPerCharacter - ceil((strlen($rawString) % $bytesPerGroup) * 8 / $bitsPerCharacter); $encodedString .= str_repeat($padCharacter[0], $pads); } break; } // Get next byte $byte = array_shift($bytes); $bitsRead = 0; } else { $oldBitCount = 0; $newBitCount = $bitsPerCharacter; } // Read only the needed bits from this byte $bits = $byte >> 8 - ($bitsRead + ($newBitCount)); $bits ^= $bits >> $newBitCount << $newBitCount; $bitsRead += $newBitCount; if ($oldBitCount) { // Bits come from seperate bytes, add $oldBits to $bits $bits = ($oldBits << $newBitCount) | $bits; } $encodedString .= $chars[$bits]; } return $encodedString; }
php
{ "resource": "" }
q252185
PrerenderListener.onPrerenderPre
validation
public function onPrerenderPre(PrerenderEvent $events) { $cache = $this->getServiceLocator()->get($this->moduleOptions->getCacheKey()); return $cache->getItem($this->getCacheEntryKey($events->getRequest())); }
php
{ "resource": "" }
q252186
PrerenderListener.onPrerenderPost
validation
public function onPrerenderPost(PrerenderEvent $events) { $cache = $this->getServiceLocator()->get($this->moduleOptions->getCacheKey()); $response = $events->getResponse(); $key = $this->getCacheEntryKey($events->getRequest()); $cache->setItem($key, $events->getResponse()); return $this; }
php
{ "resource": "" }
q252187
Request.post
validation
public function post($name = null, $defaultValue = null) { if ($name === null) { return $this->getBodyParams(); } else { return $this->getBodyParam($name, $defaultValue); } }
php
{ "resource": "" }
q252188
Request.getAcceptableContentTypes
validation
public function getAcceptableContentTypes() { if ($this->_contentTypes === null) { if (isset($_SERVER['HTTP_ACCEPT'])) { $this->_contentTypes = $this->parseAcceptHeader($_SERVER['HTTP_ACCEPT']); } else { $this->_contentTypes = []; } } return $this->_contentTypes; }
php
{ "resource": "" }
q252189
Request.getCsrfToken
validation
public function getCsrfToken($regenerate = false) { if ($this->_csrfToken === null || $regenerate) { if ($regenerate || ($token = $this->loadCsrfToken()) === null) { $token = $this->generateCsrfToken(); } // the mask doesn't need to be very random $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-.'; $mask = substr(str_shuffle(str_repeat($chars, 5)), 0, static::CSRF_MASK_LENGTH); // The + sign may be decoded as blank space later, which will fail the validation $this->_csrfToken = str_replace('+', '.', base64_encode($mask . $this->xorTokens($token, $mask))); } return $this->_csrfToken; }
php
{ "resource": "" }
q252190
Request.loadCsrfToken
validation
protected function loadCsrfToken() { if ($this->enableCsrfCookie) { return $this->getCookies()->getValue($this->csrfParam); } else { return Yii::$app->getSession()->get($this->csrfParam); } }
php
{ "resource": "" }
q252191
Request.xorTokens
validation
private function xorTokens($token1, $token2) { $n1 = StringHelper::byteLength($token1); $n2 = StringHelper::byteLength($token2); if ($n1 > $n2) { $token2 = str_pad($token2, $n1, $token2); } elseif ($n1 < $n2) { $token1 = str_pad($token1, $n2, $n1 === 0 ? ' ' : $token1); } return $token1 ^ $token2; }
php
{ "resource": "" }
q252192
Request.validateCsrfTokenInternal
validation
private function validateCsrfTokenInternal($token, $trueToken) { $token = base64_decode(str_replace('.', '+', $token)); $n = StringHelper::byteLength($token); if ($n <= static::CSRF_MASK_LENGTH) { return false; } $mask = StringHelper::byteSubstr($token, 0, static::CSRF_MASK_LENGTH); $token = StringHelper::byteSubstr($token, static::CSRF_MASK_LENGTH, $n - static::CSRF_MASK_LENGTH); $token = $this->xorTokens($mask, $token); return $token === $trueToken; }
php
{ "resource": "" }
q252193
MessageHelper.write
validation
protected function write(Response $response, $body): Response { $response->getBody()->write((string) $body); return $response; }
php
{ "resource": "" }
q252194
MessageHelper.ifModSince
validation
protected function ifModSince(Request $request, Response $response, int $timestamp): Response { $ifModSince = $request->getHeaderLine('If-Modified-Since'); if ($ifModSince && $timestamp <= strtotime($ifModSince)) { return $response->withStatus(304, "Not Modified"); } return $response; }
php
{ "resource": "" }
q252195
MessageHelper.ifNoneMatch
validation
protected function ifNoneMatch(Request $request, Response $response, string $etag): Response { $ifNoneMatch = $request->getHeaderLine('If-None-Match'); if ($ifNoneMatch && $etag === $ifNoneMatch) { return $response->withStatus(304, "Not Modified"); } return $response; }
php
{ "resource": "" }
q252196
MessageHelper.redirect
validation
protected function redirect(Response $response, int $code, string $url): Response { return $response->withStatus($code)->withHeader('Location', $url); }
php
{ "resource": "" }
q252197
BeforeAfterTrait.dealWithParam
validation
protected function dealWithParam( /*# string */ $clause, array $values )/*# : string */ { array_shift($values); array_shift($values); // replacement $pat = $rep = []; foreach ($values as $val) { $pat[] = '/\?/'; $rep[] = $this->getBuilder()->generatePlaceholder($val); } return preg_replace($pat, $rep, $clause, 1); }
php
{ "resource": "" }
q252198
Mover.iLikeToMoveItMoveItBack
validation
public function iLikeToMoveItMoveItBack() { $moveCommand = $this->popCommandFromList(); $moveCommand->reverseFromToDirs(); $this->direction = self::DIRECTION_BACK; $this->init($moveCommand); $this->processFiles(); }
php
{ "resource": "" }
q252199
Mover.processFiles
validation
private function processFiles() { foreach ($this->currentCommand->getFilesToMove() as $fileToMove) { if ($fileToMove instanceof \SplFileInfo) { $this->processSplFileInfo($fileToMove); } else { $this->processArray($fileToMove); } } }
php
{ "resource": "" }