_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q253200
Collection.splice
validation
public function splice($offset = 0, $length = 0, $replacement = []) { return new static(array_splice($this->elements, $offset, $length, $replacement)); }
php
{ "resource": "" }
q253201
Collection.reduce
validation
public function reduce(Closure $fn, $initial = null) { return array_reduce($this->elements, $fn, $initial); }
php
{ "resource": "" }
q253202
Collection.each
validation
public function each(Closure $fn) { foreach ($this->elements as $key => $element) { if ($fn($element, $key) === false) { return false; } } return true; }
php
{ "resource": "" }
q253203
Connection.parseConfig
validation
private function parseConfig($connection) { $this->debug = false; $allowed_keys = array_keys(get_object_vars($this)); foreach ($connection as $key => $value) { // Check if host has a trailing slash and remove it if ($key === 'host' && substr($value, -1) === '/') { $value = substr($value, 0, -1); } $this->setParam($this->camelCase($key), $value, $allowed_keys); } $this->transactionId = null; $this->query = null; }
php
{ "resource": "" }
q253204
Connection.setParam
validation
private function setParam($key, $value, $allowed_keys) { if (in_array($key, $allowed_keys)) { $this->{$key} = $value; } }
php
{ "resource": "" }
q253205
Connection.checkSource
validation
private function checkSource($connection) { if (gettype($connection)=="string") { $config = include(__DIR__.'/../../../../../clusterpoint.php'); $connection = $config[$connection]; } return $connection; }
php
{ "resource": "" }
q253206
Password.hash
validation
public static function hash($password) { return \Yii::$app->security->generatePasswordHash($password, \Yii::$app->getModule('user')->cost); }
php
{ "resource": "" }
q253207
PageRendererProduction.renderSlots
validation
public function renderSlots(Page $page, array $slots, array $options = array()) { $renderedSlots = array(); $slots = $this->dispatchSlotsEvent(RenderEvents::SLOTS_RENDERING, $page, $slots); foreach ($slots as $slotName => $slot) { if (is_string($slot)) { $renderedSlots[$slotName] = $slot; continue; } if (!$slot instanceof Slot) { continue; } $renderedSlots[$slotName] = implode("", $this->renderSlot($slot)); } $this->mediaFiles = array_unique($this->mediaFiles); return $this->dispatchSlotsEvent(RenderEvents::SLOTS_RENDERED, $page, $renderedSlots); }
php
{ "resource": "" }
q253208
SupervisorProcess.getPidByProgramName
validation
public function getPidByProgramName($name) { $process = new Process(sprintf('supervisorctl pid %s', $name)); $process->run(); return $process->getOutput(); }
php
{ "resource": "" }
q253209
Auth.GetAuthClass
validation
public static function GetAuthClass () { if (self::$authClass === NULL) { if (class_exists(self::AUTH_CLASS_FULL)) { self::$authClass = self::AUTH_CLASS_FULL; } else { self::$authClass = self::AUTH_CLASS_BASIC; } } return self::$authClass; }
php
{ "resource": "" }
q253210
Auth.SetAuthClass
validation
public static function SetAuthClass ($authClass) { $toolClass = \MvcCore\Application::GetInstance()->GetToolClass(); if ($toolClass::CheckClassInterface($authClass, 'MvcCore\Ext\Auths\Basics\IAuth', TRUE, TRUE)) self::$authClass = $authClass; }
php
{ "resource": "" }
q253211
ExpiringLockTrait.extendExpiration
validation
public function extendExpiration() { if (null === $this->ttl) { throw new DomainException('There is no TTL set for this Lock.'); } if (!$this->expiresAt) { $this->expiresAt = new \DateTime(); $this->expiresAt->setTimestamp(time()); } $this->expiresAt->add($this->ttl); }
php
{ "resource": "" }
q253212
Plugin.handleCommand
validation
public function handleCommand(Event $event, Queue $queue) { if ($this->validateParams($event)) { $params = $event->getCustomParams(); $results = array(); $total = 0; $count = $params[0]; $sides = (isset($params[1])) ? $params[1] : $this->defaultDieSides; for ($roll = 1; $roll <= $count; $roll++) { $rollResult = $this->doRoll($sides); $results[] = $rollResult; $total += $rollResult; } $response = $this->generateResponse($event, $total, $results); $this->sendIrcResponseLine($event, $queue, $response); } else { $this->handleCommandHelp($event, $queue); } }
php
{ "resource": "" }
q253213
Plugin.validateParams
validation
protected function validateParams(Event $event) { return ( $this->genericParamValidation($event) && $this->firstParamValidation($event) && $this->secondParamValidation($event) ); }
php
{ "resource": "" }
q253214
Plugin.genericParamValidation
validation
private function genericParamValidation(Event $event) { $params = $event->getCustomParams(); return (count($params) >= 1 && count($params) <= 2); }
php
{ "resource": "" }
q253215
Plugin.firstParamValidation
validation
private function firstParamValidation(Event $event) { $params = $event->getCustomParams(); return (is_numeric($params[0]) && $params[0] > 0 && $params[0] <= $this->maxDieRolls); }
php
{ "resource": "" }
q253216
Plugin.secondParamValidation
validation
private function secondParamValidation(Event $event) { $params = $event->getCustomParams(); return (!isset($params[1]) || (is_numeric($params[1]) && $params[1] >= 1 && $params[1] <= $this->maxDieSides)); }
php
{ "resource": "" }
q253217
Plugin.handleCommandHelp
validation
public function handleCommandHelp(Event $event, Queue $queue) { $this->sendIrcResponse($event, $queue, $this->getHelpLines()); }
php
{ "resource": "" }
q253218
Item.getInterfaceObject
validation
public function getInterfaceObject() { if (is_null($this->_interfaceObject)) { $this->_interfaceObject = DataInterface::find()->where(['system_id' => $this->object->systemId])->one(); if (empty($this->_interfaceObject)) { $this->_interfaceObject = new DataInterface(); $this->_interfaceObject->name = $this->object->name; $this->_interfaceObject->system_id = $this->object->systemId; if (!$this->_interfaceObject->save()) { var_dump($this->_interfaceObject->errors); throw new Exception("Unable to save interface object!"); } } } return $this->_interfaceObject; }
php
{ "resource": "" }
q253219
Transformer.transform
validation
public function transform($message) { if (is_array($message)) { $class = News::class; } else { if (is_string($message)) { $message = new Text(['content' => $message]); } $class = get_class($message); } $handle = 'transform'.substr($class, strlen('EasyWeChat\Message\\')); return method_exists($this, $handle) ? $this->$handle($message) : []; }
php
{ "resource": "" }
q253220
Transformer.transformCard
validation
public function transformCard(AbstractMessage $message) { $type = $message->getType(); return [ 'msgtype' => $type, $type => [ 'card_id' => $message->get('card_id'), ], ]; }
php
{ "resource": "" }
q253221
Stats.query
validation
protected function query($api, $from, $to) { $params = [ 'begin_date' => $from, 'end_date' => $to, ]; return $this->parseJSON('json', [$api, $params]); }
php
{ "resource": "" }
q253222
LockManager.isAccessible
validation
public function isAccessible(AcquirerInterface $acquirer, ResourceInterface $resource) { if (!$resource->isLocked()) { return true; } $lock = $resource->getLock(); if ($lock instanceof ExpiringLockInterface and $this->isLockExpired($lock)) { $this->release($lock); return true; } return $lock->getAcquirer()->getIdentifier() === $acquirer->getIdentifier(); }
php
{ "resource": "" }
q253223
LockManager.acquire
validation
public function acquire(AcquirerInterface $acquirer, ResourceInterface $resource) { if (!$this->isAccessible($acquirer, $resource)) { throw new ResourceLockedException(sprintf('The resource is not accessible. It is locked by "%s".', $resource->getLock()->getAcquirer()->getIdentifier())); } return $this->repository->acquire($acquirer, $resource); }
php
{ "resource": "" }
q253224
BaseCliApplication.getConfig
validation
public function getConfig($name, $default = null) { return array_key_exists($name, $this->settings) ? $this->settings[$name] : $default; }
php
{ "resource": "" }
q253225
BaseCliApplication.boot
validation
public function boot() { if ($this->booted) { return $this; } // If we have pinba, disable it. if (extension_loaded('pinba')) { ini_set('pinba.enabled', false); } // If we have newrelic, disable it. if (extension_loaded('newrelic')) { ini_set('newrelic.enabled', false); } // Set timezone. if (!empty($this->settings['timezone'])) { date_default_timezone_set($this->settings['timezone']); } $this->booted = true; return $this; }
php
{ "resource": "" }
q253226
StringBuffer.scanf
validation
function scanf($format) { $spec_pattern = "/%[+-]?('.)?[-]?(\d)*(\..\d)?[%bcdeEfFgGosuxX]/"; $source = substr($this->data,$this->pos); $result = sscanf($source,$format); if ($result==-1) return; else { $l = 0; foreach ($result as $v) { $l += strlen("".$v); } } $no_patterns_format = preg_replace($spec_pattern,"",$format); //echo "No patterns format : [".$no_patterns_format."] LEN=".strlen($no_patterns_format); $l+=strlen($no_patterns_format); $this->pos+=$l; return $result; }
php
{ "resource": "" }
q253227
StringBuffer.read
validation
function read($length) { $l = $this->pos+$length < strlen($this->data) ? $length : strlen($this->data)-$this->pos; $result = substr($this->data,$this->pos,$l); $this->pos+=$l; return $result; }
php
{ "resource": "" }
q253228
StringBuffer.isEndOfLine
validation
private function isEndOfLine($i) { $ch = $this->data[$i]; if ($this->getLineEndingModeCrlf()) { if ($ch=="\r") { $more_ch = $i + 1 < strlen($this->data); if ($more_ch) { $next_n = $this->data[$i + 1] == "\n"; if ($next_n) return true; } } } else { if ($ch=="\n") return true; } return false; }
php
{ "resource": "" }
q253229
StringBuffer.readLine
validation
function readLine() { $i = $this->pos; $tot_len = strlen($this->data); while ($i<$tot_len && !$this->isEndOfLine($i)) { $i++; } $result = substr($this->data,$this->pos,$i-$this->pos); $i++; //skip first EOL char if ($this->getLineEndingModeCrlf()) $i++; //skip second EOL char if needed $this->pos=$i; //update position return $result; }
php
{ "resource": "" }
q253230
AdminManager.sort
validation
public function sort($entityName, $values) { $values = json_decode($values); for ($i=0; $i<count($values); $i++) { $this->entityManager ->getRepository($entityName) ->createQueryBuilder('e') ->update() ->set('e.order', $i) ->where('e.id = :id') ->setParameter('id', $values[$i]->id) ->getQuery() ->execute(); } }
php
{ "resource": "" }
q253231
AdminManager.toggleFiltrable
validation
public function toggleFiltrable($entityName, $id) { $entity = $this->entityManager->getRepository($entityName)->find($id); if (!$entity) { throw new NotFoundHttpException(); } $entity->toggleFiltrable(); $this->entityManager->persist($entity); $this->entityManager->flush(); return $entity->isFiltrable(); }
php
{ "resource": "" }
q253232
Slug.validateSlug
validation
private function validateSlug(string $sku) { if (strlen($sku) == 0) { throw new SlugException("A Slug cannot be empty"); } // check for white-space $containsWhitespace = preg_match($this->whiteSpacePattern, $sku) == 1; if ($containsWhitespace) { throw new SlugException(sprintf("A Slug cannot contain white space characters: \"%s\"", $sku)); } // check for invalid characters $containsInvalidCharacters = preg_match($this->invalidCharactersPattern, $sku) == 1; if ($containsInvalidCharacters) { throw new SlugException(sprintf("The Slug \"%s\" contains invalid characters. A Slug can only contain the following characters: a-z, 0-9 and -", $sku)); } // check minimum length if (strlen($sku) < $this->minLength) { throw new SlugException(sprintf("The given Slug \"%s\" is too short. The minimum length for a Slug is: %s", $sku, $this->minLength)); } // check maximum length if (strlen($sku) > $this->maxLength) { throw new SlugException(sprintf("The given Slug \"%s\" is too long (%s character). The maximum length for a Slug is: %s", strlen($sku), $sku, $this->maxLength)); } }
php
{ "resource": "" }
q253233
Collection.toArray
validation
public function toArray() { $urls = []; $actions = []; if (count($this->items) < 1) { return parent::toArray(); } $entity = $this->items[0]; if (is_array($entity->load)) { foreach ($entity->load as $k => $load) { $this->load($load); } } $data = parent::toArray(); $actions = $entity->getActions(); if (count($actions) > 0) { foreach ($data as $k => $resource) { if (count($resource) < 2) { continue; } $data[$k] += [ 'actions' => $actions ]; } } $data = $this->normalizeArray($data); return $data; }
php
{ "resource": "" }
q253234
Collection.orderBy
validation
public function orderBy($key, $direction = 'asc') { return $this->sort(function($a, $b) use ($key, $direction) { $valueA = is_object($a) ? $a->{$key} : $a[$key]; $valueB = is_object($b) ? $b->{$key} : $b[$key]; if ($valueA == $valueB) return 0; $result = ($valueA < $valueB) ? -1 : 1; // If the direction is descending, reverse the order. return $direction === 'desc' ? -($result) : $result; }); }
php
{ "resource": "" }
q253235
Stream.pipe
validation
public function pipe($data, $index, $isHeader = false) { $this->lastIndex++; $this->data[$this->lastIndex] = $data; }
php
{ "resource": "" }
q253236
CatalogMapper.getCatalog
validation
public function getCatalog(array $catalogData) { /** @var array $skuIndex A list of all SKUs */ $skuIndex = []; /** @var array $slugIndex A list of all product slugs */ $slugIndex = []; $index = 1; $products = []; foreach ($catalogData as $catalogItem) { try { // convert the product data into a Product model $product = $this->productMapper->getProduct($catalogItem); // check for duplicate SKUs $sku = strtolower($product->getSku()->__toString()); if (array_key_exists($sku, $skuIndex)) { throw new CatalogException(sprintf("Cannot add a second product with the SKU '%s' to the catalog", $sku)); } $skuIndex[$sku] = 1; // check for duplicate Slugs $slug = strtolower($product->getSlug()->__toString()); if (array_key_exists($slug, $slugIndex)) { throw new CatalogException(sprintf("Cannot add a second product with the Slug '%s' to the catalog", $slug)); } $slugIndex[$slug] = 1; // add the product to the catalog $products[] = $product; } catch (\Exception $productException) { throw new CatalogException(sprintf("Cannot convert catalog item %s into a product: %s", $index, $productException->getMessage()), $productException); } $index++; } return new Catalog($products); }
php
{ "resource": "" }
q253237
Generator.doctrine
validation
static public function doctrine($tableName, $field, $length = 16) { do { $generate = self::generate($length); } while (self::doctrineQuery($tableName, $field, $generate)); return $generate; }
php
{ "resource": "" }
q253238
Generator.generateDoctrine2
validation
static public function generateDoctrine2(\Doctrine\ORM\EntityManager $entityManager, $entityName, $field, $length = 16) { do { $generate = self::generate($length); } while (self::doctrine2Query($entityManager, $entityName, $field, $generate)); return $generate; }
php
{ "resource": "" }
q253239
Generator.generatePhalcon
validation
static public function generatePhalcon($modelName, $field, $length = 16) { do { $generate = self::generate($length); } while (self::phalconQuery($modelName, $field, $generate)); return $generate; }
php
{ "resource": "" }
q253240
Generator.phalconQuery
validation
static protected function phalconQuery($modelName, $field, $generate) { $return = \Phalcon\Mvc\Model::query() ->setModelName($modelName) ->where("$field = :value:") ->bind(array('value' => $generate)) ->execute(); return (boolean) $return->count(); }
php
{ "resource": "" }
q253241
Generator.doctrineQuery
validation
static protected function doctrineQuery($tableName, $field, $generate) { return \Doctrine_Query::create() ->select($field) ->from($tableName)->where("$field = ?", $generate) ->execute(array(), \Doctrine_Core::HYDRATE_SINGLE_SCALAR); }
php
{ "resource": "" }
q253242
Generator.doctrine2Query
validation
static protected function doctrine2Query(\Doctrine\ORM\EntityManager $entityManager, $entityName, $field, $generate) { $result = $entityManager->createQueryBuilder() ->select("entity.$field") ->from($entityName, 'entity') ->where("entity.$field = :$field") ->setParameter("$field", $generate) ->getQuery() ->getResult(); return !empty($result); }
php
{ "resource": "" }
q253243
Generator.generate
validation
static public function generate($length = 16, $algorithm = 'sha256') { if (!in_array($algorithm, self::$allowedAlgorithm)) { throw new Exception("Hash algorithm $algorithm doesn't exists!"); } $salt = hash($algorithm, time()); return substr(hash($algorithm, (mt_rand(self::RAND_MIN, self::RAND_MAX) % $length) . $salt . mt_rand(self::RAND_MIN, self::RAND_MAX)), self::CUT_LEN, $length); }
php
{ "resource": "" }
q253244
Sns.getSessionKey
validation
public function getSessionKey($jsCode) { $params = [ 'appid' => $this->config['app_id'], 'secret' => $this->config['secret'], 'js_code' => $jsCode, 'grant_type' => 'authorization_code', ]; return $this->parseJSON('GET', [self::JSCODE_TO_SESSION, $params]); }
php
{ "resource": "" }
q253245
ObjectOperation.objectToArray
validation
public static function objectToArray($mObject) : array { if ( is_object($mObject)) { $mObject = (array) $mObject; } if (is_array($mObject)) { $aNew = array(); foreach($mObject as $sKey => $mValues) { $sKey = preg_replace("/^\\0(.*)\\0/", "", $sKey); $aNew[$sKey] = self::objectToArray($mValues); } } else { $aNew = $mObject; } return $aNew; }
php
{ "resource": "" }
q253246
BlockManagerArchive.archive
validation
public function archive($sourceDir, array $options, $username, $block) { $this->resolveOptions($options); $block = json_decode($block, true); $block["history"] = array(); $this->init($sourceDir, $options, $username); $historyDirName = sprintf('%s/archive/%s', $this->getDirInUse(), $options["blockname"]); $historyFileName = $historyDirName . '/history.json'; if (!is_dir($historyDirName)) { mkdir($historyDirName); } $history = array(); if (file_exists($historyFileName)) { $history = json_decode(file_get_contents($historyFileName), true); } $history = array_merge($history, array($block["history_name"] => $block)); FilesystemTools::writeFile($historyFileName, json_encode($history)); }
php
{ "resource": "" }
q253247
Authority.getAuthorityTree
validation
final public function getAuthorityTree() { $database = $this->database; $statement = $database->select()->from('?authority')->between("lft", '1', '6')->prepare(); $results = $statement->execute(); $right = array(); }
php
{ "resource": "" }
q253248
Authority.getPermissions
validation
final public function getPermissions( $authenticated ) { //$authority = $this; $this->userid = (int) $authenticated->get("user_id"); //Authenticated? if ($authenticated->authenticated && !empty($this->userid)) { //At least we know the user is authenticated $this->setAuthority( AUTHROITY_IMPLIED_AUTHENTICATED ); } }
php
{ "resource": "" }
q253249
MwTranslator.getMessages
validation
public function getMessages( $domain = 'default', $locale = null ) { if( $locale === null ) { $locale = $this->getLocale(); } if( !isset( $this->messages[$domain][$locale] ) ) { $this->loadMessages( $domain, $locale ); } return $this->messages[$domain][$locale]; }
php
{ "resource": "" }
q253250
Breadcrumb.setTitle
validation
public function setTitle(string $title): void { $this->title = $this->translator !== null ? $this->translator->translate($title) : $title; }
php
{ "resource": "" }
q253251
Breadcrumb.addLink
validation
public function addLink(string $name, string $link = null, array $arguments = []): Link { $name = $this->translator !== null ? $this->translator->translate($name) : $name; return $this->addLinkUntranslated($name, $link, $arguments); }
php
{ "resource": "" }
q253252
Configuration.addBlockSection
validation
private function addBlockSection(ArrayNodeDefinition $rootNode) { $rootNode ->fixXmlConfig('block_theme') ->children() ->arrayNode('block_themes') ->prototype('scalar')->end() ->example(['@App/block.html.twig']) ->end() ->end() ; }
php
{ "resource": "" }
q253253
Configuration.addDoctrineSection
validation
private function addDoctrineSection(ArrayNodeDefinition $rootNode) { $rootNode ->children() ->arrayNode('doctrine') ->info('doctrine configuration') ->canBeEnabled() ->children() ->booleanNode('enabled')->defaultTrue()->end() ->end() ->end() ->end() ; }
php
{ "resource": "" }
q253254
AbstractExtendedCompilerFactory.instantiateCompiler
validation
protected function instantiateCompiler(string &$className, &$description): CompilerInterface { if(is_array($description)) { $class = $description[ self::COMPILER_CLASS_KEY ] ?? $className; if(!isset($description[ self::COMPILER_ID_KEY ])) $description[ self::COMPILER_ID_KEY ] = $className; $id = $description[ self::COMPILER_ID_KEY ]; if($args = $description[ self::COMPILER_ARGUMENTS_KEY ] ?? NULL) { return new $class($id, ...array_values($args)); } else { return new $class($id, $description); } } else { // $className is compiler id and $description is class name $instance = new $description($className); $description = [ self::COMPILER_ID_KEY => $className ]; return $instance; } }
php
{ "resource": "" }
q253255
Rest.execute
validation
public static function execute(ConnectionInterface $connection, $forceSimpleUrl = false) { $url = $connection->host.'/'.$connection->accountId.'/'.$connection->db.''.$connection->action.(isset($connection->transactionId) ? '?transaction_id='.$connection->transactionId : ''); if ($forceSimpleUrl){ $url = $connection->host.'/'.$connection->accountId; } if ($connection->debug === true) { echo "URL: ".$url."\r\n"; echo "USER:PWD: ".$connection->username.":".str_repeat('X',strlen($connection->password))."\r\n"; echo "METHOD: ".$connection->method."\r\n"; echo "QUERY: ".(isset($connection->query) ? $connection->query : null)."\r\n"; } $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_USERPWD, $connection->username.":".$connection->password); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $connection->method); curl_setopt($curl, CURLOPT_POSTFIELDS, isset($connection->query) ? $connection->query : null); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: text/plain')); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); $curlResponse = curl_exec($curl); if ($connection->debug === true) { if (curl_error($curl)) { echo "cURL error: ".curl_error($curl)."\r\n"; } echo "RESPONSE: ".$curlResponse."\r\n\r\n"; } curl_close($curl); return ($connection->query==='BEGIN_TRANSACTION') ? json_decode($curlResponse)->transaction_id : ((isset($connection->multiple) && $connection->multiple) ? new Batch($curlResponse, $connection) : new Single($curlResponse, $connection)); }
php
{ "resource": "" }
q253256
MultiExec.assertClient
validation
private function assertClient(ClientInterface $client) { if ($client->getConnection() instanceof AggregateConnectionInterface) { throw new NotSupportedException( 'Cannot initialize a MULTI/EXEC transaction over aggregate connections.' ); } if (!$client->getCommandFactory()->supportsCommands(array('MULTI', 'EXEC', 'DISCARD'))) { throw new NotSupportedException( 'MULTI, EXEC and DISCARD are not supported by the current command factory.' ); } }
php
{ "resource": "" }
q253257
MultiExec.unwatch
validation
public function unwatch() { if (!$this->client->getCommandFactory()->supportsCommand('UNWATCH')) { throw new NotSupportedException( 'UNWATCH is not supported by the current command factory.' ); } $this->state->unflag(MultiExecState::WATCH); $this->__call('UNWATCH', array()); return $this; }
php
{ "resource": "" }
q253258
FileResponseCache.calculateRequestFilename
validation
public function calculateRequestFilename(Request $request) { $string = $request->getUri(); $filename = parse_url($string, PHP_URL_HOST); $filename .= '_'.parse_url($string, PHP_URL_PATH); $headers = $request->getAllHeaders(); ksort($headers); foreach ($headers as $header => $values) { $string .= $header; foreach ($values as $value) { $string .= $value; } } $filename .= '_'.sha1($string); if (strpos($filename, '_') === 0) { //Makes sorting not be crap $filename = substr($filename, 1); } return $this->cacheDirectory.'/'.$filename.'.cache'; }
php
{ "resource": "" }
q253259
LazyQueue.setup
validation
protected function setup(\AMQPQueue $queue) { $queue->declareQueue(); foreach ($this->binds as $exchange => $params) { $queue->bind($exchange, $params['routing_key'], $params['arguments']); } }
php
{ "resource": "" }
q253260
OperationGenerator.addProperties
validation
function addProperties() { $requiredProperties = [ 'api' => '\\'.$this->apiClassname, 'parameters' => 'array', 'response' => '\Amp\Artax\Response', 'originalResponse' => '\Amp\Artax\Response', ]; //TODO - deal with clashes between this and bits of the actual api foreach ($requiredProperties as $propertyName => $typehint) { $propertyGenerator = new PropertyGenerator($propertyName, null); $docBlock = new DocBlockGenerator('@var '.$typehint); $propertyGenerator->setDocBlock($docBlock); $this->classGenerator->addPropertyFromGenerator($propertyGenerator); } //We have to allow access to the last response for crappy APIs //that return information in the response headers. $docBlock = new DocBlockGenerator('Get the last response.'); $body = 'return $this->response;'; $methodGenerator = $this->createMethodGenerator('getResponse', $body, $docBlock, [], '\Amp\Artax\Response'); $this->classGenerator->addMethodFromGenerator($methodGenerator); $docBlock = new DocBlockGenerator('Set the last response. This should only be used by the API class when the operation has been dispatched. Storing the response is required as some APIs store out-of-bound information in the headers e.g. rate-limit info, pagination that is not really part of the operation.'); $body = '$this->response = $response;'; $methodGenerator = $this->createMethodGenerator('setResponse', $body, $docBlock, [['response', 'Amp\Artax\Response']]); $this->classGenerator->addMethodFromGenerator($methodGenerator); }
php
{ "resource": "" }
q253261
OperationGenerator.addSetAPIMethod
validation
function addSetAPIMethod() { $methodGenerator = new MethodGenerator('setAPI'); $methodGenerator->setBody('$this->api = $api;'); $parameterGenerator = new ParameterGenerator('api', $this->apiClassname); $methodGenerator->setParameter($parameterGenerator); $this->classGenerator->addMethodFromGenerator($methodGenerator); }
php
{ "resource": "" }
q253262
OperationGenerator.generateParameterSetBlock
validation
private function generateParameterSetBlock($indent, \ArtaxServiceBuilder\Parameter $operationParameter) { switch ($operationParameter->getLocation()) { case 'absoluteURL': { return $indent.'$url = $value;'.PHP_EOL; break; } case 'postField': { return sprintf( $indent.'$formBody->addField(\'%s\', $value);'.PHP_EOL, $operationParameter->getSentAs() ); } case 'postFile': { return sprintf( $indent.'$formBody->addFileField(\'%s\', $value);'.PHP_EOL, $operationParameter->getSentAs() ); break; } case 'json': { return sprintf( $indent.'$jsonParams[\'%s\'] = $value;'.PHP_EOL, $operationParameter->getSentAs() ); } case ('header'): { return sprintf( $indent.'$request->setHeader(\'%s\', $value);'.PHP_EOL, $operationParameter->getSentAs(), $operationParameter->getName() ); } default: case 'query': { return sprintf( $indent.'$queryParameters[\'%s\'] = $value;'.PHP_EOL, $operationParameter->getSentAs(), $operationParameter->getName() ); } } }
php
{ "resource": "" }
q253263
OperationGenerator.addCheckScopeMethod
validation
function addCheckScopeMethod() { $scopes = $this->operationDefinition->getScopes(); if (count($scopes) == 0) { //TODO - should the method be added anyway? For now, no. return; } $methodGenerator = new MethodGenerator('checkScopeRequirement'); $parameterGenerator = new ParameterGenerator('allowedScopes', 'array'); $methodGenerator->setParameter($parameterGenerator); $body = '//For each of the elements, all of the scopes in that element'.PHP_EOL; $body .= '//must be satisfied'.PHP_EOL; $body .= '$requiredScopesArray = ['.PHP_EOL; foreach ($scopes as $scopeList) { $body .= ' ['; $separator = ''; foreach ($scopeList as $scope) { $body .= sprintf("%s'%s'", $separator, $scope); $separator = ', '; } $body .= ']'.PHP_EOL; } $body .= '];'.PHP_EOL.PHP_EOL; $body .= <<< 'END' foreach($requiredScopesArray as $requiredScopes) { $requirementMet = true; foreach ($requiredScopes as $requiredScope) { if (in_array($requiredScope, $allowedScopes) == false) { $requirementMet = false; break; } } if ($requirementMet == true) { return true; } } return false; END; $methodGenerator->setBody($body); $this->classGenerator->addMethodFromGenerator($methodGenerator); }
php
{ "resource": "" }
q253264
OperationGenerator.addAccessorMethods
validation
function addAccessorMethods() { foreach($this->operationDefinition->getParameters() as $parameter) { $translatedParam = $this->apiGenerator->translateParameter($parameter->getName()); $methodGenerator = new MethodGenerator('set'.ucfirst($translatedParam)); $body = sprintf('$this->parameters[\'%s\'] = $%s;', $parameter->getName(), $translatedParam); $body .= "\n\n"; $body .= 'return $this;'; $tags = []; $docBlockTest = "Set $translatedParam"; $description = trim($parameter->getDescription()); $tags[] = new GenericTag('return', '$this'); $docBlock = new DocBlockGenerator($docBlockTest, $description, $tags); $methodGenerator->setDocBlock($docBlock); $methodGenerator->setBody($body); $parameterGenerator = new ParameterGenerator($translatedParam, $parameter->getType()); $methodGenerator->setParameter($parameterGenerator); $this->classGenerator->addMethodFromGenerator($methodGenerator); } $methodGenerator = new MethodGenerator('getParameters'); $body = 'return $this->parameters;'; $methodGenerator->setBody($body); $this->classGenerator->addMethodFromGenerator($methodGenerator); }
php
{ "resource": "" }
q253265
OperationGenerator.addConstructorMethod
validation
private function addConstructorMethod() { $requiredParameters = $this->operationDefinition->getRequiredParams(); $methodGenerator = new MethodGenerator('__construct'); $defaultParams = $this->operationDefinition->getDefaultParams(); $body = ''; if (count($defaultParams)) { $body = '$defaultParams = ['.PHP_EOL; foreach ($defaultParams as $param) { $body .= sprintf(" '%s' => '%s',", $param->getName(), $param->getDefault()); $body .= PHP_EOL; } $body .= '];'.PHP_EOL; $body .= '$this->setParams($defaultParams);'.PHP_EOL; } $constructorParams = []; $constructorParams[] = new ParameterGenerator('api', $this->apiGenerator->getFQCN()); $body .= '$this->api = $api;'.PHP_EOL; foreach ($requiredParameters as $param) { $normalizedParamName = normalizeParamName($param->getName()); $constructorParams[] = new ParameterGenerator($normalizedParamName, $param->getType()); $body .= sprintf( "\$this->parameters['%s'] = $%s;".PHP_EOL, $param->getName(), $normalizedParamName //$param->getName() ); } $methodGenerator->setParameters($constructorParams); $methodGenerator->setBody($body); $this->classGenerator->addMethodFromGenerator($methodGenerator); }
php
{ "resource": "" }
q253266
OperationGenerator.generateExecuteFragment
validation
private function generateExecuteFragment() { $body = ''; if ($this->operationDefinition->getNeedsSigning()) { $body .= '$request = $this->api->signRequest($request);'.PHP_EOL; } $body .= '$response = $this->api->execute($request, $this);'.PHP_EOL; $body .= '$this->response = $response;'.PHP_EOL; return $body; }
php
{ "resource": "" }
q253267
OperationGenerator.generateExecuteDocBlock
validation
private function generateExecuteDocBlock($methodDescription) { $responseClass = $this->operationDefinition->getResponseClass(); $docBlock = new DocBlockGenerator($methodDescription, null); if ($responseClass) { $tags[] = new GenericTag('return', '\\'.$responseClass); } else { $tags[] = new GenericTag('return', 'mixed'); } $docBlock->setTags($tags); return $docBlock; }
php
{ "resource": "" }
q253268
OperationGenerator.addExecuteMethod
validation
function addExecuteMethod() { $body = $this->generateCreateFragment(); $body .= 'return $this->dispatch($request);'; $docBlock = $this->generateExecuteDocBlock('Execute the operation, returning the parsed response'); $methodGenerator = new MethodGenerator('execute'); $methodGenerator->setBody($body); $methodGenerator->setDocBlock($docBlock); $this->classGenerator->addMethodFromGenerator($methodGenerator); }
php
{ "resource": "" }
q253269
OperationGenerator.addExecuteAsyncMethod
validation
function addExecuteAsyncMethod() { $body = $this->generateCreateFragment(); $body .= 'return $this->dispatchAsync($request, $callable);'; $docBlock = new DocBlockGenerator('Execute the operation asynchronously, passing the parsed response to the callback', null); $tags[] = new GenericTag('return', '\Amp\Promise'); $docBlock->setTags($tags); $callableParamGenerator = new ParameterGenerator('callable', 'callable'); $methodGenerator = new MethodGenerator('executeAsync'); $methodGenerator->setBody($body); $methodGenerator->setDocBlock($docBlock); $methodGenerator->setParameters([$callableParamGenerator]); $this->classGenerator->addMethodFromGenerator($methodGenerator); }
php
{ "resource": "" }
q253270
OperationGenerator.generateParamFilterBlock
validation
function generateParamFilterBlock(\ArtaxServiceBuilder\Parameter $parameter) { $i1 = ' ';//Indent 1 $i2 = ' ';//Indent 1 $text = ''; $text .= sprintf( $i1."case ('%s'): {".PHP_EOL, $parameter->getName() ); foreach ($parameter->getFilters() as $filter) { if (is_array($filter)) { $text .= $i2.'$args = [];'.PHP_EOL; if (isset($filter['args']) == true) { if (is_array($filter['args']) == false) { throw new \ArtaxServiceBuilder\APIBuilderException("Filter args should be an array instead received ".var_export($filter['args'], true ) ); } // Convert complex filters that hold value place holders foreach ($filter['args'] as $data) { if ($data == '@value') { $text .= $i2.'$args[] = $value;'.PHP_EOL; } elseif ($data == '@api') { $text .= $i2."\$args[] = \$this->\$api;".PHP_EOL; } else { //It should be a string $text .= $i2."\$args[] = $data;".PHP_EOL; } } } // $text .= sprintf( // //TODO - we can do better than call_user_func_array // $i2.'$value = call_user_func_array(\'%s\', $args);'.PHP_EOL, // $filter['method'] // ); //hard-code for now 2016-02-28 $text .= sprintf( $i2.'$value = call_user_func_array([$value, \'%s\'], $args);'.PHP_EOL, $filter['method'] ); } else { //TODO - get rid of call_user_func $text .= sprintf( $i2.'call_user_func(\'%s\', $value);'.PHP_EOL, $filter ); } } $text .= $i1.' break;'.PHP_EOL; $text .= $i1.'}'.PHP_EOL; return $text; }
php
{ "resource": "" }
q253271
OperationGenerator.addFilteredParameterMethod
validation
function addFilteredParameterMethod() { $methodGenerator = new MethodGenerator('getFilteredParameter'); $body = 'if (array_key_exists($name, $this->parameters) == false) {'.PHP_EOL; //TODO - make this be the correct type $body .= ' throw new \Exception(\'Parameter \'.$name.\' does not exist.\');'.PHP_EOL; $body .= '}'.PHP_EOL; $body .= ''.PHP_EOL; $body .= '$value = $this->parameters[$name];'.PHP_EOL; $body .= ''.PHP_EOL; $paramFilterBlocks = []; foreach ($this->operationDefinition->getParameters() as $parameter) { $parameterFilters = $parameter->getFilters(); if (count($parameterFilters)) { //Only generate the filter block if a filter actually need to be applied $paramFilterBlocks[] = $this->generateParamFilterBlock($parameter); } } if (count($paramFilterBlocks)) { $body .= 'switch ($name) {'.PHP_EOL; $body .= ''.PHP_EOL; foreach ($paramFilterBlocks as $paramFilterBlock) { $body .= $paramFilterBlock.PHP_EOL; $body .= ''.PHP_EOL; } $body .= ' default:{}'.PHP_EOL; $body .= ''.PHP_EOL; $body .= '}'.PHP_EOL; } $body .= ''.PHP_EOL; $body .= 'return $value;'.PHP_EOL; $methodGenerator->setBody($body); $docBlock = $this->generateExecuteDocBlock('Apply any filters necessary to the parameter'); $parameterGenerator = new ParameterGenerator('name', 'string'); $methodGenerator->setParameter($parameterGenerator); $tag = createParamTag($parameterGenerator, "The name of the parameter to get."); $docBlock->setTag($tag); $methodGenerator->setDocBlock($docBlock); $this->classGenerator->addMethodFromGenerator($methodGenerator); }
php
{ "resource": "" }
q253272
OperationGenerator.addCreateAndExecuteMethod
validation
function addCreateAndExecuteMethod() { $methodGenerator = new MethodGenerator('createAndExecute'); $body = ''; $body .= $this->generateCreateFragment(); $body .= $this->generateExecuteFragment(); $body .= PHP_EOL; $body .= 'return $response;'.PHP_EOL;; $docBlock = new DocBlockGenerator('Create and execute the operation, returning the raw response from the server.', null); $tags[] = new GenericTag('return', '\Amp\Artax\Response'); $docBlock->setTags($tags); $methodGenerator->setBody($body); $methodGenerator->setDocBlock($docBlock); $this->classGenerator->addMethodFromGenerator($methodGenerator); }
php
{ "resource": "" }
q253273
OperationGenerator.addDispatchMethod
validation
function addDispatchMethod() { $methodGenerator = new MethodGenerator('dispatch'); $body = ''; $body .= $this->generateExecuteFragment(); $body .= $this->generateResponseFragment(); $docBlock = $this->generateExecuteDocBlock('Dispatch the request for this operation and process the response. Allows you to modify the request before it is sent.'); $parameter = new ParameterGenerator('request', 'Amp\Artax\Request'); $methodGenerator->setParameter($parameter); $tag = createParamTag($parameter, 'The request to be processed'); $docBlock->setTag($tag); $methodGenerator->setDocBlock($docBlock); $methodGenerator->setBody($body); $this->classGenerator->addMethodFromGenerator($methodGenerator); }
php
{ "resource": "" }
q253274
OperationGenerator.addDispatchAsyncMethod
validation
function addDispatchAsyncMethod() { $methodGenerator = new MethodGenerator('dispatchAsync'); $body = 'return $this->api->executeAsync($request, $this, $callable);'; $docBlock = $this->generateExecuteDocBlock('Dispatch the request for this operation and process the response asynchronously. Allows you to modify the request before it is sent.'); $requestParameter = new ParameterGenerator('request', 'Amp\Artax\Request'); $methodGenerator->setParameter($requestParameter); $tag = createParamTag($requestParameter, 'The request to be processed'); $docBlock->setTag($tag); $callableParameter = new ParameterGenerator('callable', 'callable'); $methodGenerator->setParameter($callableParameter); $callableTag = createParamTag($callableParameter, 'The callable that processes the response'); $docBlock->setTag($callableTag); $methodGenerator->setDocBlock($docBlock); $methodGenerator->setBody($body); $this->classGenerator->addMethodFromGenerator($methodGenerator); }
php
{ "resource": "" }
q253275
OperationGenerator.addProcessResponseMethod
validation
function addProcessResponseMethod() { $methodGenerator = new MethodGenerator('processResponse'); $body = ''; $body .= $this->generateResponseFragment(); $docBlock = $this->generateExecuteDocBlock('Dispatch the request for this operation and process the response. Allows you to modify the request before it is sent.'); $methodGenerator->setDocBlock($docBlock); $methodGenerator->setBody($body); $parameters = []; $parameters[] = new ParameterGenerator('response', 'Amp\Artax\Response'); $methodGenerator->setParameters($parameters); $tag = createParamTag($parameters[0], 'The HTTP response.'); $docBlock->setTag($tag); $this->classGenerator->addMethodFromGenerator($methodGenerator); }
php
{ "resource": "" }
q253276
OperationGenerator.createMethodGenerator
validation
private function createMethodGenerator($methodName, $body, DocBlockGenerator $docBlock, $parameterInfoArray, $returnType = null) { $parameters = []; foreach ($parameterInfoArray as $parameterInfo) { $parameters[] = new ParameterGenerator($parameterInfo[0], $parameterInfo[1]); } $methodGenerator = new MethodGenerator($methodName); $methodGenerator->setParameters($parameters); if ($returnType != null) { if (is_array($returnType)) { $returnType = implode('|', $returnType); } $tags[] = new GenericTag('return', $returnType); $docBlock->setTags($tags); } $methodGenerator->setDocBlock($docBlock); $methodGenerator->setBody($body); return $methodGenerator; }
php
{ "resource": "" }
q253277
OperationGenerator.addTranslateResponseToExceptionMethod
validation
public function addTranslateResponseToExceptionMethod() { $body = 'return $this->api->translateResponseToException($response);'; $docBlock = new DocBlockGenerator('Determine whether the response is an error. Override this method to have a per-operation decision, otherwise the function from the API class will be used.', null); $methodGenerator = $this->createMethodGenerator( 'translateResponseToException', $body, $docBlock, [['response', 'Amp\Artax\Response']], ['null', '\ArtaxServiceBuilder\BadResponseException'] ); $this->classGenerator->addMethodFromGenerator($methodGenerator); }
php
{ "resource": "" }
q253278
OperationGenerator.generate
validation
function generate() { if ($this->namespace) { $fqcn = $this->namespace.'\\'.$this->className; } else { $fqcn = $this->className; } $this->addProperties(); $this->addConstructorMethod(); $this->addSetAPIMethod(); $this->addSetParameterMethod(); $this->addCheckScopeMethod(); $this->addAccessorMethods(); $this->addFilteredParameterMethod(); $this->addCreateRequestMethod(); $this->addCreateAndExecuteMethod(); $this->addCallMethod(); $this->addExecuteMethod(); $this->addExecuteAsyncMethod(); $this->addDispatchMethod(); $this->addDispatchAsyncMethod(); $this->addProcessResponseMethod(); //$this->addIsErrorResponseMethod(); $this->addShouldResponseBeProcessedMethod(); $this->addTranslateResponseToExceptionMethod(); $this->addShouldUseCachedResponseMethod(); $this->addShouldResponseBeCachedMethod(); $this->addSetOriginalResponseMethod(); $this->addGetOriginalResponseMethod(); $this->addGetResultInstantiationInfoMethod(); $this->classGenerator->setImplementedInterfaces(['ArtaxServiceBuilder\Operation']); $this->classGenerator->setFQCN($fqcn); $text = $this->classGenerator->generate(); saveFile($this->outputPath, $fqcn, $text); }
php
{ "resource": "" }
q253279
Native.drop
validation
public function drop($key) { if($this->has($key)) { unset($_SESSION[$this->root][$key]); return true; } return false; }
php
{ "resource": "" }
q253280
Benri_Controller_Response_Http.sendHeaders
validation
public function sendHeaders() { // Only check if we can send headers if we have headers to send if (count($this->_headersRaw) || count($this->_headers) || (200 !== $this->_httpResponseCode)) { $this->canSendHeaders(true); } elseif (200 === $this->_httpResponseCode) { // Haven't changed the response code, and we have no headers return $this; } $httpCodeSent = false; foreach ($this->_headersRaw as $header) { if (!$httpCodeSent && $this->_httpResponseCode) { header($header, true, $this->_httpResponseCode); $httpCodeSent = true; } else { header($header); } } foreach ($this->_headers as $header) { header("{$header['name']}: {$header['value']}", $header['replace']); } if (!$httpCodeSent) { $message = array_key_exists($this->_httpResponseCode, self::$_messages) ? self::$_messages[$this->_httpResponseCode] : 'No Reason Phrase'; header("HTTP/1.1 {$this->_httpResponseCode} {$message}", true); $httpCodeSent = true; } return $this; }
php
{ "resource": "" }
q253281
User.getCurrentUser
validation
public function getCurrentUser(){ // //@TODO Rework the userid, use case, if user id is not provided or is null //Get the authenticated user //Also load some user data from the user database table, some basic info $this->authenticated = false; //Authenticate $authenticate = $this->session->get("handler", "auth"); if (is_a($authenticate, Authenticate::class)) { if ($authenticate->authenticated) { $this->authenticated = true; //Does this actually do anything? $this->authority = $this->session->getAuthority(); return $this->loadObjectByURI($authenticate->get("user_name_id"), [], true); } } //Gets an instance of the session user; return $this; }
php
{ "resource": "" }
q253282
User.getFullName
validation
public function getFullName($first = NULL, $middle = NULL, $last = NULL) { $user_first_name = $this->getPropertyValue("user_first_name"); $user_middle_name = $this->getPropertyValue("user_middle_name"); $user_last_name = $this->getPropertyValue("user_last_name"); $user_full_name = implode(' ', array(empty($user_first_name) ? $first : $user_first_name, empty($user_middle_name) ? $middle : $user_middle_name, empty($user_last_name) ? $last : $user_last_name)); if (!empty($user_full_name)) { return $user_full_name; } }
php
{ "resource": "" }
q253283
User.update
validation
public function update($usernameId, $data = array()) { if (empty($usernameId)) return false; $existing = (array) $this->getPropertyData(); $data = empty($data) ? $existing : array_merge($data, $existing); //Load the username; $profile = $this->loadObjectByURI($usernameId, array_keys($this->getPropertyModel())); $this->setObjectId($profile->getObjectId()); $this->setObjectURI($profile->getObjectURI()); $profileData = $profile->getPropertyData(); $updatedProfile = array_merge($profileData, $data); foreach ($updatedProfile as $property => $value): $this->setPropertyValue($property, $value); endforeach; //$data = $this->getPropertyData(); $this->defineValueGroup("user"); //die; if (!$this->saveObject($this->getPropertyValue("user_name_id"), "user", $this->getObjectId())) { //Null because the system can autogenerate an ID for this attachment $profile->setError("Could not save the profile data"); return false; } return true; }
php
{ "resource": "" }
q253284
User.search
validation
public function search($query, &$results = array()) { if (!empty($query)): $words = explode(' ', $query); foreach ($words as $word) { $_results = $this->setListLookUpConditions("user_first_name", $word, 'OR') ->setListLookUpConditions("user_last_name", $word, 'OR') ->setListLookUpConditions("user_middle_name", $word, 'OR') ->setListLookUpConditions("user_name_id", $word, 'OR'); } $_results = $this->getObjectsList("user"); $rows = $_results->fetchAll(); //Include the members section $members = array( "filterid" => "users", "title" => "People", "results" => array() ); //Loop through fetched attachments; //@TODO might be a better way of doing this, but just trying foreach ($rows as $member) { $photo = empty($member['user_photo']) ? "" : "/system/object/{$member['user_photo']}/resize/170/170"; $members["results"][] = array( "icon" => $photo, //optional "link" => "/member:{$member['user_name_id']}/profile/timeline", "title" => $this->getFullName($member['user_first_name'], $member['user_middle_name'], $member['user_last_name']), //required "description" => "", //required "type" => $member['object_type'], "user_name_id" => $member['user_name_id'] ); } //Add the members section to the result array, only if they have items; if (!empty($members["results"])) $results[] = $members; endif; return true; }
php
{ "resource": "" }
q253285
QuestionPolicy.view
validation
public function view(UserPolicy $user, Question $question) { if ($user->canDo('forum.question.view') && $user->isAdmin()) { return true; } return $question->user_id == user_id() && $question->user_type == user_type(); }
php
{ "resource": "" }
q253286
QuestionPolicy.destroy
validation
public function destroy(UserPolicy $user, Question $question) { return $question->user_id == user_id() && $question->user_type == user_type(); }
php
{ "resource": "" }
q253287
YoutubeService.getThumbnails
validation
public function getThumbnails($videoId, $format = null) { $listResponse = $this->videos->listVideos('snippet', array('id' => $videoId)); if (empty($listResponse)) { throw new \RuntimeException(sprintf('Could not find video with id %s', $videoId)); } $video = $listResponse[0]; $videoSnippet = $video['snippet']; if (is_null($format)) { return $videoSnippet['thumbnails']['data']; } if (!in_array($format, array('default', 'medium', 'high'))) { throw new \InvalidArgumentException(sprintf('Invalid format "%s"', $format)); } return $videoSnippet['thumbnails']['data'][$format]; }
php
{ "resource": "" }
q253288
VerbalExpressions.range
validation
public function range() { $arg_num = func_num_args(); if ($arg_num % 2 != 0) { throw new \InvalidArgumentException("Number of args must be even", 1); } $value = "["; $arg_list = func_get_args(); for ($i = 0; $i < $arg_num;) { $value .= self::sanitize($arg_list[$i++]) . "-" . self::sanitize($arg_list[$i++]); } $value .= "]"; return $this->add($value); }
php
{ "resource": "" }
q253289
FormElement.render
validation
public function render(ElementInterface $element) { $renderer = $this->getView(); if ($element instanceof CkEditor) { /** @noinspection PhpUndefinedMethodInspection */ $plugin = $renderer->plugin('form_ckeditor'); return $plugin($element); } return parent::render($element); }
php
{ "resource": "" }
q253290
Image.showImageInSize
validation
public static function showImageInSize(int $iImageUri, int $iWidth, int $iHeight, bool $bKeepDimension = false) { $aSize = getimagesize($iImageUri); $rActualImage = imagecreatefromjpeg($iImageUri); $ImageChoisie = imagecreatefromjpeg($_FILES['ImageNews']['tmp_name']); $TailleImageChoisie = getimagesize($_FILES['ImageNews']['tmp_name']); $rNewImage = imagecreatetruecolor($iWidth , $iHeight); if ($bKeepDimension === false) { imagecopyresampled($rNewImage, $rActualImage, 0, 0, 0, 0, $iWidth, $iHeight, $aSize[0], $aSize[1]); } else { if ($aSize[0] > $aSize[1]) { $rWhite = imagecolorallocate($rNewImage, 255, 255, 255); imagefilledrectangle($rNewImage, 0, 0, $iWidth, $iHeight, $rWhite); $fCoef = $aSize[1] / $aSize[0]; $iHeight = round($iWidth * $fCoef); $iDestY = round(($iWidth - $iHeight) / 2); $iDestX = 0; } else { $rWhite = imagecolorallocate($rNewImage, 255, 255, 255); imagefilledrectangle($rNewImage, 0, 0, $iWidth, $iHeight, $rWhite); $fCoef = $aSize[0] / $aSize[1]; $iWidth = round($iHeight * $fCoef); $iDestX = round(($iHeight - $iWidth) / 2); $iDestY = 0; } $rWhite = imagecolorallocate($rNewImage, 255, 255, 255); imagefilledrectangle($rNewImage, 0, 0, $iWidth, $iHeight, $rWhite); imagecopyresampled($rNewImage, $rActualImage, $iDestX, $iDestY, 0, 0, $iWidth, $iHeight, $aSize[0], $aSize[1]); } imagedestroy($rActualImage); $NomImageChoisie = explode('.', $rNewImage); $NomImageExploitable = time(); header('Content-Type: image/jpeg'); imagejpeg($rNewImage , null, 100); }
php
{ "resource": "" }
q253291
GuzzleHttp.initClient
validation
public function initClient($headers) { try { $this->request = new Client($headers); } catch (Exception $e) { echo 'Unable to initialise http client because '.$e->getMessage()."\n"; } }
php
{ "resource": "" }
q253292
CreateRendererExceptionCapableTrait._createRendererException
validation
protected function _createRendererException( $message = null, $code = null, RootException $previous = null, RendererInterface $renderer = null ) { return new RendererException($message, $code, $previous, $renderer); }
php
{ "resource": "" }
q253293
Relation.getRelationModelField
validation
public function getRelationModelField() { $field = $this->model->tabularPrefix; if ($this->modelField->relationship->companionRole($this->modelField->modelRole) === 'child') { $field .= 'child_object_id'; } else { $field .= 'parent_object_id'; } return $field; }
php
{ "resource": "" }
q253294
Modules.set
validation
public function set($name, AbstractModule $module) { $this->container[(string) $name] = $module; return $this; }
php
{ "resource": "" }
q253295
Modules.remove
validation
public function remove($name) { if (isset($this->container[$name])) { unset($this->container[$name]); } return $this; }
php
{ "resource": "" }
q253296
Modules.get
validation
public function get($name) { if (! isset($this->container[$name])) { throw new RuntimeException( sprintf( 'Module "%s" is not found', $name ) ); } return $this->container[$name]; }
php
{ "resource": "" }
q253297
DeleteForm.getLabels
validation
public function getLabels() { $labels = []; $labels['delete_object'] = [ 'short' => 'Delete ' . $this->object->objectType->title->getSingular(true), 'long' => 'delete the ' . $this->object->objectType->title->getSingular(false) . ' <em>' . $this->object->descriptor . '</em>', 'past' => $this->object->objectType->title->getSingular(false) . ' <em>' . $this->object->descriptor . '</em> has been deleted', 'options' => ['class' => 'btn-danger'], 'response' => 'home', ]; $labels['archive_object'] = [ 'short' => 'Archive ' . $this->object->objectType->title->getSingular(true), 'long' => 'archive the ' . $this->object->objectType->title->getSingular(false) . ' <em>' . $this->object->descriptor . '</em>', 'past' => $this->object->objectType->title->getSingular(false) . ' <em>' . $this->object->descriptor . '</em> has been archived', 'response' => 'refresh', ]; $labels['unarchive_object'] = [ 'short' => 'Unarchive ' . $this->object->objectType->title->getSingular(true), 'long' => 'unarchive the ' . $this->object->objectType->title->getSingular(false) . ' <em>' . $this->object->descriptor . '</em>', 'past' => $this->object->objectType->title->getSingular(false) . ' <em>' . $this->object->descriptor . '</em> has been unarchived', 'response' => 'refresh', ]; if (isset($this->relationshipWith)) { $labels['delete_relationship'] = [ 'short' => 'Delete Relationship', 'long' => 'delete the relationship between <em>' . $this->object->descriptor . '</em> and <em>' . $this->relationshipWith->descriptor . '</em>', 'past' => 'the relationship between <em>' . $this->object->descriptor . '</em> and <em>' . $this->relationshipWith->descriptor . '</em> has been deleted', 'options' => ['class' => 'btn-warning'], ]; $labels['end_relationship'] = [ 'short' => 'End Relationship', 'long' => 'end the relationship between <em>' . $this->object->descriptor . '</em> and <em>' . $this->relationshipWith->descriptor . '</em>', 'past' => 'the relationship between <em>' . $this->object->descriptor . '</em> and <em>' . $this->relationshipWith->descriptor . '</em> has been ended', ]; } return $labels; }
php
{ "resource": "" }
q253298
DeleteForm.getTarget
validation
public function getTarget() { if (is_null($this->_target) && !empty($this->possibleTargets)) { $this->_target = $this->possibleTargets[0]; } return $this->_target; }
php
{ "resource": "" }
q253299
DeleteForm.getPossibleTargets
validation
public function getPossibleTargets() { if (is_null($this->_possibleTargets)) { $this->_possibleTargets = []; if ($this->canEndRelation()) { $this->_possibleTargets[] = 'end_relationship'; } if ($this->canDeleteRelation()) { $this->_possibleTargets[] = 'delete_relationship'; } if ($this->canArchiveObject()) { if ($this->object->archived) { $this->_possibleTargets[] = 'unarchive_object'; } else { $this->_possibleTargets[] = 'archive_object'; } } if ($this->canDeleteObject()) { $this->_possibleTargets[] = 'delete_object'; } } return $this->_possibleTargets; }
php
{ "resource": "" }