_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q251700
CommandBenchmark.finish
validation
public function finish($outputStat = true) { if ($outputStat === true) { $this->output->writeln(''); $this->output->writeln(sprintf('<info>Job finished in %.2f s</info>', microtime(true) - $this->start)); $this->output->writeln(sprintf('<info>Memory usage: %.2f MB</info>', memory_get_peak_usage() >> 20)); } else { $end = microtime(true); return [ 'start' => $this->start, 'finish' => $end, 'duration' => $end - $this->start, 'memory_peak' => memory_get_peak_usage() >> 20, ]; } }
php
{ "resource": "" }
q251701
DiffItemFactory.create
validation
public static function create($type) { switch ($type) { case ActionTypes::CREATE: return new CreateDiffItem(); case ActionTypes::UPDATE: return new UpdateDiffItem(); case ActionTypes::DELETE: return new DeleteDiffItem(); default: throw new \InvalidArgumentException("Invalid type {$type}"); } }
php
{ "resource": "" }
q251702
ReleazTemplate.initialize
validation
public function initialize($filePath, $params) { copy(__DIR__ . '/../../../recipe/releaz.php', $filePath); // Copy the deploy file. $exampleFile = $this->getExamplePath(); // Get the path of the example file. $projectFile = dirname($filePath) . '/' . $this->getExample(); // The location of the project file. copy($exampleFile, $projectFile); // Copy content. $this->setParamsInExample($projectFile, $params); // Insert the params }
php
{ "resource": "" }
q251703
MysqlStorageManager.getTableName
validation
public function getTableName($shopId = null) { $tableName = parent::getTableName(); if ($shopId === null) { $shopId = $this->getActiveShopId(); } if (!$this->isShopValid($shopId)) { throw new InvalidArgumentException("Shop id \"{$shopId}\" is invalid."); } $tableName .= '_' . $shopId; try { SqlValidator::validateTableName($tableName); } catch (InvalidArgumentException $e) { throw new InvalidArgumentException("Shop id \"{$shopId}\" is invalid.", 0, $e); } return $tableName; }
php
{ "resource": "" }
q251704
MysqlStorageManager.bindParams
validation
private function bindParams($statement, $params) { foreach ($params as $param) { $statement->bindValue($param[0], $param[1], $param[2]); } }
php
{ "resource": "" }
q251705
MysqlStorageManager.deductionForDeletion
validation
private function deductionForDeletion($connection, $tableName, $documentType, $documentId, $shopId) { $sql = sprintf( "SELECT `id` FROM {$tableName} WHERE `type` != 'D' AND `document_type` = :documentType AND `document_id` = :documentId AND `status` = :status AND `id` < :id" ); $statement = $connection->prepare($sql); $statement->execute( [ 'documentType' => $documentType, 'documentId' => $documentId, 'status' => self::STATUS_NEW, 'id' => $connection->lastInsertId(), ] ); $entries = $statement->fetchAll(); foreach ($entries as $entry) { $this->removeRecord($entry['id'], [$shopId]); } }
php
{ "resource": "" }
q251706
MysqlStorageManager.isShopValid
validation
public function isShopValid($shopId) { $shops = $this->getContainer()->getParameter('ongr_connections.shops'); foreach ($shops as $meta) { if ($meta['shop_id'] === $shopId) { return true; } } return false; }
php
{ "resource": "" }
q251707
AbstractImportModifyEventListener.onModify
validation
public function onModify(ItemPipelineEvent $event) { $item = $event->getItem(); if ($item instanceof ImportItem) { $this->modify($item, $event); } elseif ($item instanceof SyncExecuteItem) { $syncStorageData = $item->getSyncStorageData(); if ($syncStorageData['type'] !== ActionTypes::DELETE) { $this->modify($item, $event); } else { ItemSkipper::skip($event, 'Delete item with id = ' . $syncStorageData['id']); } } else { $this->log('The type of provided item is not ImportItem or SyncExecuteItem.', LogLevel::ERROR); } }
php
{ "resource": "" }
q251708
RecipientFactory.createSimpleAnonymousRecipient
validation
public static function createSimpleAnonymousRecipient($emailAddress, $countryCode) { return (new Recipient())->setHash(self::getEmailAddressHash($emailAddress)) ->setCountry($countryCode) ->setProvider(self::getDomainFromEmail($emailAddress)); }
php
{ "resource": "" }
q251709
Uom.getConversionFactor
validation
public static function getConversionFactor(Uom $from, Uom $to) { // Check to see if we need to do a conversion if ($from->isSameValueAs($to)) { return new Fraction(1); } if (!isset(static::$conversions)) { static::$conversions = json_decode( utf8_encode( file_get_contents(__DIR__.'/conversions.json') ), true ); } // First lets see if we have a conversion for the from to to if (isset(static::$conversions[$from->getName()][$to->getName()])) { $numeratorDenominatorPair = static::$conversions[$from->getName()][$to->getName()]; // I guess we didn't find one, try the inverse } elseif (isset(static::$conversions[$to->getName()][$from->getName()])) { // We found the inverse, set the conversion values appropriately $numeratorDenominatorPair = array_reverse(static::$conversions[$to->getName()][$from->getName()]); } else { // no conversion found. throw an exception throw new ConversionNotSetException($from->getName(), $to->getName()); } // Is the conversion set up correctly if (count($numeratorDenominatorPair) == 2) { return new Fraction( $numeratorDenominatorPair[0], $numeratorDenominatorPair[1] ); } else { // Guess it wasn't throw new BadConversionException(); } }
php
{ "resource": "" }
q251710
NcipClient.post
validation
public function post(Request $request) { $this->emit('message.send', array($request->xml())); $response = $this->connector->post($request); $this->emit('message.recv', array($response)); try { return $this->parseXml($response); } catch (InvalidXMLException $e) { throw new InvalidNcipResponseException( 'Invalid response received from the NCIP service "' . $this->connector->url . '": ' . $response ); } }
php
{ "resource": "" }
q251711
NcipClient.lookupUser
validation
public function lookupUser($user_id) { $request = new UserRequest($user_id); $this->emit('request.user', array($user_id)); $response = $this->post($request); return new UserResponse($response); }
php
{ "resource": "" }
q251712
NcipClient.checkOutItem
validation
public function checkOutItem($user_id, $item_id) { $request = new CheckOutRequest($this->connector->agency_id, $user_id, $item_id); $this->emit('request.checkout', array($user_id, $item_id)); $response = $this->post($request); return new CheckOutResponse($response); }
php
{ "resource": "" }
q251713
NcipClient.checkInItem
validation
public function checkInItem($item_id) { $request = new CheckInRequest($this->connector->agency_id, $item_id); $this->emit('request.checkin', array($item_id)); $response = $this->post($request); return new CheckInResponse($response); }
php
{ "resource": "" }
q251714
NcipClient.renewItem
validation
public function renewItem($user_id, $item_id) { $request = new RenewRequest($user_id, $item_id); $this->emit('request.renew', array($user_id, $item_id)); $response = $this->post($request); return new RenewResponse($response); }
php
{ "resource": "" }
q251715
NcipClient.lookupItem
validation
public function lookupItem($item_id) { $request = new ItemRequest($item_id); $this->emit('request.item', array($item_id)); $response = $this->post($request); return new ItemResponse($response); }
php
{ "resource": "" }
q251716
Stk2kEventChannelAdapter.listen
validation
public function listen(string $event, callable $callback) : EventChannelInterface { $this->channel->listen($event, $callback); return $this; }
php
{ "resource": "" }
q251717
Stk2kEventChannelAdapter.push
validation
public function push(string $event, $event_args = null) : EventChannelInterface { try{ $this->channel->push($event, $event_args); } catch(EventSourceIsNotPushableException $e) { throw new EventStreamException('Event is not pushable.'); } return $this; }
php
{ "resource": "" }
q251718
DisplaysExceptions.displayExceptions
validation
protected function displayExceptions(Exception $e) { $this->display[] = 'Cerbero\Auth\Exceptions\DisplayException'; foreach ($this->display as $exception) { if($e instanceof $exception) { return back()->withInput()->withError($e->getMessage()); } } }
php
{ "resource": "" }
q251719
DoctrineExtractor.resolveItemAction
validation
protected function resolveItemAction(AbstractDiffItem $item) { if ($item instanceof CreateDiffItem) { $action = ActionTypes::CREATE; return $action; } elseif ($item instanceof DeleteDiffItem) { $action = ActionTypes::DELETE; return $action; } elseif ($item instanceof UpdateDiffItem) { $action = ActionTypes::UPDATE; return $action; } else { throw new \InvalidArgumentException('Unsupported diff item type. Got: ' . get_class($item)); } }
php
{ "resource": "" }
q251720
DoctrineExtractor.inlineContext
validation
protected function inlineContext($selectQuery, $itemRow) { $selectQuery = str_replace(['OLD.', 'NEW.'], '__ctx__', $selectQuery); $prefixedKeys = array_map( function ($key) { return '__ctx__' . $key; }, array_keys($itemRow) ); $connection = $this->getConnection(); $escapedValues = array_map( function ($value) use ($connection) { return $connection->quote($value); }, array_values($itemRow) ); $sql = str_replace($prefixedKeys, $escapedValues, $selectQuery); return $sql; }
php
{ "resource": "" }
q251721
DoctrineExtractor.isTrackedFieldModified
validation
private function isTrackedFieldModified(AbstractDiffItem $item, ExtractionDescriptorInterface $relation) { if (!$item instanceof UpdateDiffItem) { throw new \InvalidArgumentException('Wrong diff item type. Got: ' . get_class($item)); } $trackedFields = $relation->getUpdateFields(); if (empty($trackedFields)) { return true; } $itemRow = $item->getItem(); $oldItemRow = $item->getOldItem(); foreach (array_keys($trackedFields) as $key) { if (array_key_exists($key, $itemRow) && $itemRow[$key] !== $oldItemRow[$key]) { return true; } } return false; }
php
{ "resource": "" }
q251722
SyncExecuteSourceEventListener.getDocuments
validation
public function getDocuments() { return new SyncStorageImportIterator( [ 'sync_storage' => $this->getSyncStorage(), 'shop_id' => $this->getShopId(), 'document_type' => $this->getDocumentType(), ], $this->getElasticsearchManager()->getRepository($this->getDocumentClass()), $this->getDoctrineManager(), $this->getEntityClass() ); }
php
{ "resource": "" }
q251723
AuraSessionAdapter.getBucket
validation
public function getBucket(string $name) : SessionBucketInterface { $segment = $this->session->getSegment($name); if (!$segment) { return null; } return new AuraSessionBucketAdapter($segment); }
php
{ "resource": "" }
q251724
PayloadFactory.createSoftBounce
validation
public static function createSoftBounce( $recipientEmailAddress, $listExternalId, $recipientExternalId = null, $ipAddress = '127.0.0.1' ) { if ($recipientExternalId == null) { $recipientExternalId = rand(1, 99999); } return (new Payload())->setIpAddress($ipAddress) ->setAction(Type::SOFT_BOUNCE) ->setCampaignId(rand(1, 99999)) ->setListExternalId($listExternalId) ->setReason(Type::REASON_SYSTEM_AUTOMATIC) ->setRecipientEmailAddress($recipientEmailAddress) ->setHash(md5($recipientEmailAddress)) ->setRecipientExternalId($recipientExternalId) ->setTriggerDate(new \DateTime()) ->setType(Type::SOFT_BOUNCE); }
php
{ "resource": "" }
q251725
PayloadFactory.createSpamComplaint
validation
public static function createSpamComplaint( $recipientEmailAddress, $listExternalId, $recipientExternalId = null, $ipAddress = '127.0.0.1' ) { if ($recipientExternalId == null) { $recipientExternalId = rand(1, 99999); } return (new Payload())->setIpAddress($ipAddress) ->setAction(Type::SPAM_COMPLAINT) ->setCampaignId(rand(1, 99999)) ->setListExternalId($listExternalId) ->setReason(Type::REASON_USER_REQUEST) ->setRecipientEmailAddress($recipientEmailAddress) ->setHash(md5($recipientEmailAddress)) ->setRecipientExternalId($recipientExternalId) ->setTriggerDate(new \DateTime()) ->setType(Type::SPAM_COMPLAINT); }
php
{ "resource": "" }
q251726
BinlogDecorator.getTableMapping
validation
protected function getTableMapping($table) { if (array_key_exists($table, $this->mappings)) { return $this->mappings[$table]; } $mapping = $this->retrieveMapping($table); if (empty($mapping)) { throw new \UnderflowException("Table with name {$table} not found."); } $this->mappings[$table] = $mapping; return $mapping; }
php
{ "resource": "" }
q251727
BinlogDecorator.retrieveMapping
validation
protected function retrieveMapping($table) { $result = $this->connection->fetchAll( 'SELECT COLUMN_NAME, ORDINAL_POSITION FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ?', [$table] ); if (empty($result)) { return false; } $columns = []; foreach ($result as $column) { $columns[$column['ORDINAL_POSITION']] = $column['COLUMN_NAME']; } return $columns; }
php
{ "resource": "" }
q251728
BinlogDecorator.applyMapping
validation
public function applyMapping($params, $mapping) { $newParams = []; foreach ($params as $key => $value) { $newParams[$mapping[$key]] = $value; } return $newParams; }
php
{ "resource": "" }
q251729
Passthru.run
validation
public function run(\de\codenamephp\platform\cli\command\iCommand $command) { if($this->getDirectory() !== '' && is_dir($this->getDirectory())) { $currentDir = getcwd(); chdir($this->getDirectory()); } $returnValue = $this->getActualPassthru()->run($command); if(isset($currentDir)) { chdir($currentDir); } return $returnValue; }
php
{ "resource": "" }
q251730
UnbufferedConnectionHelper.unbufferConnection
validation
public static function unbufferConnection(Connection $connection) { /** @var PDOConnection $wrappedConnection */ $wrappedConnection = $connection->getWrappedConnection(); if (!$wrappedConnection instanceof PDOConnection) { throw new InvalidArgumentException('unbufferConection can only be used with pdo_mysql Doctrine driver.'); } if ($wrappedConnection->getAttribute(PDO::ATTR_DRIVER_NAME) != 'mysql') { throw new InvalidArgumentException( 'unbufferConection can only be used with PDO mysql driver, got "' . $wrappedConnection->getAttribute(PDO::ATTR_DRIVER_NAME) . '" instead.' ); } if ($connection->isConnected()) { $connection->close(); } $connection->getWrappedConnection()->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false); $connection->connect(); }
php
{ "resource": "" }
q251731
Number.neg
validation
public function neg() { if ($this->value === null) { return new FloatType($this->value); } return new FloatType($this->value * -1); }
php
{ "resource": "" }
q251732
Number.add
validation
public function add($value) { $value = Cast::Float($value); if ($this->value === null) { return new FloatType($this->value); } return new FloatType($this->value + $value); }
php
{ "resource": "" }
q251733
Number.sub
validation
public function sub($value) { $value = Cast::Float($value); if ($this->value === null) { return new FloatType($this->value); } return new FloatType($this->value - $value); }
php
{ "resource": "" }
q251734
Number.mul
validation
public function mul($value) { $value = Cast::Float($value); if ($this->value === null) { return new FloatType($this->value); } return new FloatType($this->value * $value); }
php
{ "resource": "" }
q251735
Number.div
validation
public function div($value) { $value = Cast::Float($value); if ($value == 0) { throw new InvalidArgumentException('Division by zero'); } if ($this->value === null) { return new FloatType($this->value); } return new FloatType($this->value / $value); }
php
{ "resource": "" }
q251736
Number.mod
validation
public function mod($value) { $value = Cast::Float($value); if ($value == 0) { throw new InvalidArgumentException('Division by zero'); } if ($this->value === null) { return new FloatType($this->value); } return new FloatType($this->value % $value); }
php
{ "resource": "" }
q251737
Number.exp
validation
public function exp($value) { $value = Cast::Float($value); if ($this->value === null) { return new FloatType($this->value); } return new FloatType(pow($this->value, $value)); }
php
{ "resource": "" }
q251738
Number.sqrt
validation
public function sqrt() { if ($this->value === null) { return new FloatType($this->value); } return new FloatType(sqrt($this->value)); }
php
{ "resource": "" }
q251739
Number.root
validation
public function root($value) { $value = Cast::Float($value); if ($this->value === null) { return new FloatType($this->value); } return new FloatType(pow($this->value, 1 / $value)); }
php
{ "resource": "" }
q251740
Number.gte
validation
public function gte($value) { $value = Cast::Float($value); if ($this->value !== null && $this->value >= $value) { return true; } return false; }
php
{ "resource": "" }
q251741
Number.lte
validation
public function lte($value) { $value = Cast::Float($value); if ($this->value !== null && $this->value <= $value) { return true; } return false; }
php
{ "resource": "" }
q251742
ActiveField.autoComplete
validation
public function autoComplete($data) { static $counter = 0; $this->inputOptions['class'] .= ' typeahead typeahead-' . (++$counter); foreach ($data as &$item) { $item = ['word' => $item]; } $this->form->getView()->registerJs("yii.gii.autocomplete($counter, " . Json::htmlEncode($data) . ");"); return $this; }
php
{ "resource": "" }
q251743
ParameterSetter.setParameters
validation
public function setParameters($subject, ParameterBagInterface $parameters) { if (!is_object($subject)) { throw new InvalidSubjectException($subject); } if ($subject instanceof ParameterBagAwareInterface) { $subject->setParameters($parameters); } else { foreach ($parameters as $key => $value) { $this->setParameter($subject, $key, $value); } } }
php
{ "resource": "" }
q251744
ParameterSetter.setParameter
validation
private function setParameter($subject, string $key, $value) { $setter = 'set' . $this->snakeToCamelCase($key); if (is_callable([$subject, $setter])) { call_user_func([$subject, $setter], $value); } }
php
{ "resource": "" }
q251745
UtilitiesServiceProvider.registerLogLevels
validation
private function registerLogLevels() { $this->app->singleton(Contracts\Utilities\LogLevels::class, function ($app) { /** * @var \Illuminate\Config\Repository * @var \Illuminate\Translation\Translator $translator */ $translator = $app['translator']; return new Utilities\LogLevels($translator, 'en'); }); $this->app->singleton('arcanedev.log-viewer.levels', Contracts\Utilities\LogLevels::class); }
php
{ "resource": "" }
q251746
UtilitiesServiceProvider.registerStyler
validation
private function registerStyler() { $this->app->singleton(Contracts\Utilities\LogStyler::class, Utilities\LogStyler::class); $this->app->singleton('arcanedev.log-viewer.styler', Contracts\Utilities\LogStyler::class); }
php
{ "resource": "" }
q251747
UtilitiesServiceProvider.registerLogMenu
validation
private function registerLogMenu() { $this->app->singleton(Contracts\Utilities\LogMenu::class, Utilities\LogMenu::class); $this->app->singleton('arcanedev.log-viewer.menu', Contracts\Utilities\LogMenu::class); }
php
{ "resource": "" }
q251748
UtilitiesServiceProvider.registerFilesystem
validation
private function registerFilesystem() { $this->app->singleton(Contracts\Utilities\Filesystem::class, function ($app) { /** * @var \Illuminate\Config\Repository * @var \Illuminate\Filesystem\Filesystem $files */ $files = $app['files']; $filesystem = new Utilities\Filesystem($files, storage_path('logs')); $filesystem->setPattern( Utilities\Filesystem::PATTERN_PREFIX, Utilities\Filesystem::PATTERN_DATE, Utilities\Filesystem::PATTERN_EXTENSION ); return $filesystem; }); $this->app->singleton('arcanedev.log-viewer.filesystem', Contracts\Utilities\Filesystem::class); }
php
{ "resource": "" }
q251749
UtilitiesServiceProvider.registerChecker
validation
private function registerChecker() { $this->app->singleton(Contracts\Utilities\LogChecker::class, Utilities\LogChecker::class); $this->app->singleton('arcanedev.log-viewer.checker', Contracts\Utilities\LogChecker::class); }
php
{ "resource": "" }
q251750
EventManager.attach
validation
public function attach(\SplObserver $observer, $eventName = Null, $function = Null, $order = Null) { $newEventAttach = new \stdClass(); $newEventAttach->observer = $observer; $newEventAttach->function = $function; $newEventAttach->eventName = $eventName; $newEventAttach->order = $order; $this->_observers->attach($newEventAttach); }
php
{ "resource": "" }
q251751
EventManager.detach
validation
public function detach(\SplObserver $observer) { foreach ($this->_observers as $observerItem) { if ($observerItem->observer === $observer) { $this->_observers->detach($observerItem); } } }
php
{ "resource": "" }
q251752
EventManager.notify
validation
public function notify() { $observersToNotify = array(); //Check which observers must be update foreach ($this->_observers as $observer) { if ($this->checkIfObserverMustBeUpdate($observer)) { //Add the observers in array to be order for priority $observersToNotify[] = $observer; } } //Order the list of observers usort($observersToNotify, array($this,'orderObserversForPriority')); //Update the observers foreach ($observersToNotify as $observer) { try { $this->updateObserverState($observer); } catch (\Exception $e) { if ((int)$e->getCode()===600) { //Stop propagation break 1; } } } }
php
{ "resource": "" }
q251753
EventManager.orderObserversForPriority
validation
private function orderObserversForPriority($a, $b) { if($a->order > $b->order) { return +1; } elseif ($a->order == $b->order) { return 0; } return -1; }
php
{ "resource": "" }
q251754
EventManager.checkIfObserverMustBeUpdate
validation
private function checkIfObserverMustBeUpdate (\StdClass $observer) { if ($observer->eventName == $this->event->name) { return true; } return false; }
php
{ "resource": "" }
q251755
EventManager.updateObserverState
validation
private function updateObserverState(\StdClass $observer) { $this->event->function = $observer->function; $observerObject = $observer->observer; $observerObject->update($this); }
php
{ "resource": "" }
q251756
TagcacheAdapter.inc
validation
public function inc($key, $expire = 0) { $this->getLock($key); $this->set($key,(int) $this->get($key)+1); $this->releaseLock($key); return true; }
php
{ "resource": "" }
q251757
ProductPhotoCollectionToArrayTransformer.createPhotosCollection
validation
protected function createPhotosCollection(Product $product, $values) { $photos = new ArrayCollection(); $identifiers = $this->getMediaIdentifiers($values); $hierarchy = 0; foreach ($identifiers as $id) { $media = $this->getMediaById($id); $photo = $this->getProductPhoto($media, $product, $values); $photo->setHierarchy($hierarchy++); if (!$photos->contains($photo)) { $photos->add($photo); } } return $photos; }
php
{ "resource": "" }
q251758
ProductPhotoCollectionToArrayTransformer.getMediaIdentifiers
validation
private function getMediaIdentifiers($values) { $identifiers = []; foreach ($values as $key => $id) { if (is_int($key)) { $identifiers[] = $id; } } return $identifiers; }
php
{ "resource": "" }
q251759
ProductPhotoCollectionToArrayTransformer.getProductPhoto
validation
protected function getProductPhoto(MediaInterface $media, ProductInterface $modelData, $values) { $mainPhoto = $this->isMainPhoto($media, $values['main']); $productPhoto = new ProductPhoto(); $productPhoto->setPhoto($media); $productPhoto->setMainPhoto($mainPhoto); $productPhoto->setProduct($modelData); if ($mainPhoto) { $modelData->setPhoto($media); } return $productPhoto; }
php
{ "resource": "" }
q251760
TransportUtil.getBrowserUserAgentGenerated
validation
public static function getBrowserUserAgentGenerated() { static $ua; if (isset($ua)) { return $ua; } $year = abs(@date('Y')); if ($year <= 2017) { return $ua = self::DEFAULT_USER_AGENT; } $user_agent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:[version].0) Gecko/20100101 Firefox/[version].0'; $month = abs(@date('m')); $version = 51; $currentYear = ($year-2017); $currentVersion = is_int($month/2) ? $month/2 : abs($month/2 + 0.5); $version += $currentYear + $currentVersion; return $ua = str_replace('[version]', $version, $user_agent); }
php
{ "resource": "" }
q251761
TableConstraintTrait.constraint
validation
public function constraint(/*# string */ $string) { if (!isset($this->tbl_constraint['other'])) { $this->tbl_constraint['other'] = []; } $this->tbl_constraint['other'][] = $string; return $this; }
php
{ "resource": "" }
q251762
TableConstraintTrait.buildTblConst
validation
protected function buildTblConst()/*# : array */ { $result = $this->buildCol(); // primary if (isset($this->tbl_constraint['primary'])) { $p = $this->tbl_constraint['primary']; $result[] = 'PRIMARY KEY (' . join(', ', $this->quoteIndex($p[0])) . ')' . (empty($p[1]) ? '' : " $p[1]"); } // unique if (isset($this->tbl_constraint['unique'])) { foreach ($this->tbl_constraint['unique'] as $uniq) { $result[] = 'UNIQUE (' . join(', ', $this->quoteIndex($uniq[0])) . ')' . (empty($uniq[1]) ? '' : " $uniq[1]"); } } // other constraints if (isset($this->tbl_constraint['other'])) { foreach ($this->tbl_constraint['other'] as $const) { $result[] = $const; } } return $result; }
php
{ "resource": "" }
q251763
TableConstraintTrait.quoteIndex
validation
protected function quoteIndex(array $cols)/*# : array */ { $q = []; foreach ($cols as $col) { $q[] = $this->quoteLeading($col); } return $q; }
php
{ "resource": "" }
q251764
CrudController.getDepDropParents
validation
protected function getDepDropParents($post = 'depdrop_parents') { $parents = Yii::$app->request->post($post); $filteredParents = []; foreach ($parents as $key => $parent) { if (is_numeric($parent)) { $filteredParents[$key] = $parent; } else { return []; } } return $filteredParents; }
php
{ "resource": "" }
q251765
UnsetDataCapableTrait._unsetData
validation
protected function _unsetData($key) { $store = $this->_getDataStore(); try { $this->_containerUnset($store, $key); } catch (InvalidArgumentException $e) { throw $this->_createOutOfRangeException($this->__('Invalid store'), null, $e, $store); } catch (OutOfRangeException $e) { throw $this->_createInvalidArgumentException($this->__('Invalid key'), null, $e, $key); } }
php
{ "resource": "" }
q251766
FormTrait.setFieldValue
validation
public function setFieldValue($field, $value) { $type = $this->getFieldFormType($field); switch ($type) { case 'select': return $this->selectOptionForm($field, $value); case 'checkbox': case 'checkboxGroup': return $this->checkOptionForm($field); default: return $this->fillFieldForm($field, $value); } }
php
{ "resource": "" }
q251767
FormTrait.setFieldFromData
validation
public function setFieldFromData($name) { $value = $this->getFieldFormData($name); return $this->setFieldValue($name, $value); }
php
{ "resource": "" }
q251768
IpAddress.getValue
validation
public function getValue() { static $ip = null; if ( is_null( $ip ) ) { $ip = $this->getIpAddressFromProxy(); // direct IP address if ( isset( $_SERVER[ 'REMOTE_ADDR' ] ) ) { $ip = $_SERVER[ 'REMOTE_ADDR' ]; } } return $ip; }
php
{ "resource": "" }
q251769
IpAddress.getIpAddressFromProxy
validation
protected function getIpAddressFromProxy() { if ( !$this->useProxy || (isset( $_SERVER[ 'REMOTE_ADDR' ] ) && !in_array( $_SERVER[ 'REMOTE_ADDR' ], $this->trustedProxies )) ) { return false; } $header = $this->proxyHeader; if ( !isset( $_SERVER[ $header ] ) || empty( $_SERVER[ $header ] ) ) { return false; } // Extract IPs $ips = explode( ',', $_SERVER[ $header ] ); // trim, so we can compare against trusted proxies properly $ips = array_map( 'trim', $ips ); // remove trusted proxy IPs $ips = array_diff( $ips, $this->trustedProxies ); // Any left? if ( empty( $ips ) ) { return false; } // Since we've removed any known, trusted proxy servers, the right-most // address represents the first IP we do not know about -- i.e., we do // not know if it is a proxy server, or a client. As such, we treat it // as the originating IP. // @see http://en.wikipedia.org/wiki/X-Forwarded-For $ip = array_pop( $ips ); return $ip; }
php
{ "resource": "" }
q251770
IpAddress.normalizeProxyHeader
validation
protected function normalizeProxyHeader( $header ) { $header = strtoupper( $header ); $header = str_replace( '-', '_', $header ); if ( 0 !== strpos( $header, 'HTTP_' ) ) { $header = 'HTTP_' . $header; } return $header; }
php
{ "resource": "" }
q251771
Collection.toJson
validation
public function toJson($prettyPrint = false) { $options = 0; if ($prettyPrint) { $options += JSON_PRETTY_PRINT; } return json_encode($this->items, $options); }
php
{ "resource": "" }
q251772
Collection.count
validation
public function count() { if (is_array($this->items) && $this->items !== null) { return count($this->items); } return 0; }
php
{ "resource": "" }
q251773
Collection.valid
validation
public function valid() { if ($this->items === null) { return false; } $key = key($this->items); return ($key !== null && $key !== false); }
php
{ "resource": "" }
q251774
Collection.last
validation
public function last() { if (is_array($this->items) && count($this->items) > 0) { return end($this->items); } return null; }
php
{ "resource": "" }
q251775
AccessRule.allows
validation
public function allows($action, $user, $request) { if ($this->matchAction($action) && $this->matchRole($user) && $this->matchIP($request->getUserIP()) && $this->matchVerb($request->getMethod()) && $this->matchController($action->controller) && $this->matchCustom($action) ) { return $this->allow ? true : false; } else { return null; } }
php
{ "resource": "" }
q251776
GetDataCapableTrait._getData
validation
protected function _getData($key) { $store = $this->_getDataStore(); try { $result = $this->_containerGet($store, $key); } catch (OutOfRangeException $e) { throw $this->_createInvalidArgumentException($this->__('Invalid key'), null, $e, $key); } return $result; }
php
{ "resource": "" }
q251777
Cors.extractHeaders
validation
public function extractHeaders() { $headers = []; $requestHeaders = array_keys($this->cors); foreach ($requestHeaders as $headerField) { $serverField = $this->headerizeToPhp($headerField); $headerData = isset($_SERVER[$serverField]) ? $_SERVER[$serverField] : null; if ($headerData !== null) { $headers[$headerField] = $headerData; } } return $headers; }
php
{ "resource": "" }
q251778
Cors.prepareHeaders
validation
public function prepareHeaders($requestHeaders) { $responseHeaders = []; // handle Origin if (isset($requestHeaders['Origin'], $this->cors['Origin'])) { if (in_array('*', $this->cors['Origin']) || in_array($requestHeaders['Origin'], $this->cors['Origin'])) { $responseHeaders['Access-Control-Allow-Origin'] = $requestHeaders['Origin']; } } $this->prepareAllowHeaders('Headers', $requestHeaders, $responseHeaders); if (isset($requestHeaders['Access-Control-Request-Method'])) { $responseHeaders['Access-Control-Allow-Methods'] = implode(', ', $this->cors['Access-Control-Request-Method']); } if (isset($this->cors['Access-Control-Allow-Credentials'])) { $responseHeaders['Access-Control-Allow-Credentials'] = $this->cors['Access-Control-Allow-Credentials'] ? 'true' : 'false'; } if (isset($this->cors['Access-Control-Max-Age']) && Yii::$app->getRequest()->getIsOptions()) { $responseHeaders['Access-Control-Max-Age'] = $this->cors['Access-Control-Max-Age']; } if (isset($this->cors['Access-Control-Expose-Headers'])) { $responseHeaders['Access-Control-Expose-Headers'] = implode(', ', $this->cors['Access-Control-Expose-Headers']); } return $responseHeaders; }
php
{ "resource": "" }
q251779
FrameOptionsMiddleware.allowFrom
validation
public static function allowFrom(string $allowFromUrl):self { $middleware = new self(sprintf(self::VALUE_ALLOW_FROM, $allowFromUrl)); if (!filter_var($allowFromUrl, FILTER_VALIDATE_URL)) { throw new MiddlewareException( $middleware, sprintf("'%s' is not a valid URL", $allowFromUrl) ); } return $middleware; }
php
{ "resource": "" }
q251780
SetManyCapableTrait._setMany
validation
protected function _setMany($data) { $data = $this->_normalizeIterable($data); $store = $this->_getDataStore(); try { $this->_containerSetMany($store, $data); } catch (InvalidArgumentException $e) { throw $this->_createOutOfRangeException($this->__('Invalid store'), null, $e, $store); } }
php
{ "resource": "" }
q251781
Common.typeModification
validation
protected function typeModification( /*# string */ $type, array $args )/*# : string */ { // data size if (is_int($args[1])) { $type .= '(' . $args[1]; if (isset($args[2])) { $type .= ',' . $args[2]; } $type .= ')'; // size, zeroFill etc. } elseif (is_array($args[1])) { if (isset($args[1]['size'])) { $type .= '(' . $args[1]['size'] . ')'; } foreach ($args[1] as $key => $val) { if ('size' === $key) { continue; } $type .= ' ' . strtoupper($key); } } else { $type .= $args[1]; } return $type; }
php
{ "resource": "" }
q251782
Configurator.getFiltroConfiguration
validation
public function getFiltroConfiguration($filtroName) { if (!isset($this->config['filtros'][$filtroName])) { throw new \InvalidArgumentException(sprintf('Filtro "%s" is not managed.', $filtroName)); } return $this->config['filtros'][$filtroName]; }
php
{ "resource": "" }
q251783
Dispatcher.createFromApplication
validation
public static function createFromApplication(Application $app) { $dispatch = new static($app->request, $app->resolver, $app->config); $dispatch->setApplication($app); return $dispatch; }
php
{ "resource": "" }
q251784
Dispatcher.setConfig
validation
public function setConfig(Dictionary $config) { $this->config = $config; $this->configureSites(); $this->setVariable('config', $config); return $this; }
php
{ "resource": "" }
q251785
Dispatcher.setSites
validation
public function setSites(array $sites) { $this->sites = array(); foreach ($sites as $site) $this->addSite($site); return $this; }
php
{ "resource": "" }
q251786
Dispatcher.setVirtualHost
validation
public function setVirtualHost(VirtualHost $vhost) { $this->vhost = $vhost; $this->setVariable('vhost', $vhost); return $this; }
php
{ "resource": "" }
q251787
Dispatcher.setRequest
validation
public function setRequest(Request $request) { $this->request = $request; $this->app = null; $this->vhost = null; $this->route = null; $this->setVariable('request', $request); return $this; }
php
{ "resource": "" }
q251788
Dispatcher.setResolver
validation
public function setResolver(Resolver $resolver) { $this->resolver = $resolver; $this->setVariable('resolver', $resolver); return $this; }
php
{ "resource": "" }
q251789
Dispatcher.setTemplate
validation
public function setTemplate(Template $template) { $this->template = $template; $this->setVariable('template', $template); $this->setVariable('tpl', $template); return $this; }
php
{ "resource": "" }
q251790
Dispatcher.setApplication
validation
public function setApplication(Application $app) { $this ->setVariable('app', $app) ->setVariable('path_config', $app->pathConfig) ->setVariable('i18n', $app->i18n); try { $this->setVariable('db', $app->db); } catch (\Wedeto\DB\Exception\ConfigurationException $db) {} return $this; }
php
{ "resource": "" }
q251791
Dispatcher.dispatch
validation
public function dispatch() { $response = null; try { $this->resolveApp(); $this->getTemplate(); $this->request->startSession($this->vhost->getHost(), $this->config); FlashMessage::setStorage($this->request->session); $this->setupLocale(); if ($this->route === null) throw new HTTPError(404, 'Could not resolve ' . $this->url); $app = new AppRunner($this->app, $this->arguments); $app->setVariables($this->variables); $app->setVariable('dispatcher', $this); $app->execute(); } catch (Throwable $e) { if (!($e instanceof Response)) $e = new HTTPError(500, "Exception of type " . get_class($e) . " thrown: " . $e->getMessage(), null, $e); if ($e instanceof HTTPError) $this->prepareErrorResponse($e); $response = $e; } return $response; }
php
{ "resource": "" }
q251792
Dispatcher.determineVirtualHost
validation
public function determineVirtualHost() { // Determine the proper VirtualHost $cfg = $this->config->getSection('site'); $vhost = self::findVirtualHost($this->request->webroot, $this->sites); if ($vhost === null) { $result = $this->handleUnknownHost($this->request->webroot, $this->request->url, $this->sites, $cfg); // Handle according to the outcome if ($result === null) throw new HTTPError(404, "Not found: " . $this->url); if ($result instanceof URL) throw new RedirectRequest($result, 301); if ($result instanceof VirtualHost) { $vhost = $result; $site = $vhost->getSite(); if (isset($this->sites[$site->getName()])) $this->sites[$site->getName()] = $site; } else throw \RuntimeException("Unexpected response from handleUnknownWebsite"); } else { // Check if the VirtualHost we matched wants to redirect somewhere else $target = $vhost->getRedirect($this->request->url); if ($target) throw new RedirectRequest($target, 301); } $this->setVirtualHost($vhost); return $this; }
php
{ "resource": "" }
q251793
Dispatcher.resolveApp
validation
public function resolveApp() { // Determine the correct vhost first $this->determineVirtualHost(); // Resolve the application to start $path = $this->vhost->getPath($this->request->url); $resolved = $this->resolver->resolve("app", $path); if ($resolved !== null) { if ($resolved['ext']) { $mime = new FileType($resolved['ext'], ""); if (!empty($mime)) { $str = $mime->getMimeType() . ";q=1.5," . (string)$this->request->accept; $this->request->setAccept(new Accept($str)); } $this->suffix = $resolved['ext']; } $this->route = $resolved['route']; $this->app = $resolved['path']; $this->arguments = new Dictionary($resolved['remainder']); } else { $this->route = null; $this->app = null; $this->arguments = new Dictionary(); } }
php
{ "resource": "" }
q251794
Dispatcher.findVirtualHost
validation
public static function findVirtualHost(URL $url, array $sites) { foreach ($sites as $site) { $vhost = $site->match($url); if ($vhost !== null) return $vhost; } return null; }
php
{ "resource": "" }
q251795
Dispatcher.handleUnknownHost
validation
public static function handleUnknownHost(URL $webroot, URL $request, array $sites, Dictionary $cfg) { // Determine behaviour on unknown host $on_unknown = strtoupper($cfg->dget('unknown_host_policy', "IGNORE")); $best_matching = self::findBestMatching($webroot, $sites); if ($on_unknown === "ERROR" || ($best_matching === null && $on_unknown === "REDIRECT")) return null; if ($on_unknown === "REDIRECT") { $redir = $best_matching->URL($request->path); return $redir; } // Generate a proper VirtualHost on the fly $url = new URL($webroot); $url->fragment = null; $url->query = null; $lang = $cfg->dget('default_language', 'en'); $vhost = new VirtualHost($url, $lang); // Add the new virtualhost to a site. if ($best_matching === null) { // If no site has been defined, create a new one $site = new Site(); $site->addVirtualHost($vhost); } else $best_matching->getSite()->addVirtualHost($vhost); return $vhost; }
php
{ "resource": "" }
q251796
Dispatcher.findBestMatching
validation
public static function findBestMatching(URL $url, array $sites) { $vhosts = array(); foreach ($sites as $site) foreach ($site->getVirtualHosts() as $vhost) $vhosts[] = $vhost; // Remove query and fragments from the URL in use $my_url = new URL($url); $my_url->set('query', null)->set('fragment', null)->toString(); // Match the visited URL with all vhosts and calcualte their textual similarity $best_percentage = 0; $best_idx = null; foreach ($vhosts as $idx => $vhost) { $host = $vhost->getHost()->toString(); similar_text($my_url, $host, $percentage); if ($best_idx === null || $percentage > $best_percentage) { $best_idx = $idx; $best_percentage = $percentage; } } // Return the best match, or null if none was found. if ($best_idx === null) return null; return $vhosts[$best_idx]; }
php
{ "resource": "" }
q251797
LogMenu.make
validation
public function make(Log $log, $trans = true) { $items = []; $route = 'dashboard.systems.logs.show'; //$this->config('menu.filter-route'); foreach ($log->tree($trans) as $level => $item) { $items[$level] = array_merge($item, [ 'url' => route($route, [$log->date, $level]), 'icon' => $this->styler->icon($level) ?: '', ]); } return $items; }
php
{ "resource": "" }
q251798
Queueable.dispatchNextJobInChain
validation
public function dispatchNextJobInChain() { if (! empty($this->chained)) { new PendingDispatch(tap(unserialize(array_shift($this->chained)), function ($next) { $next->chained = $this->chained; })); } }
php
{ "resource": "" }
q251799
I18nPlugin.createI18n
validation
public function createI18n(array $args) { $i18n = new I18n; I18nShortcut::setInstance($i18n); // Add all module paths to the I18n object $modules = $this->app->resolver->getResolver("language"); $log = \Wedeto\Log\Logger::getLogger(I18nPlugin::class); $search_path = $modules->getSearchPath(); foreach ($search_path as $name => $path) { $i18n->registerTextDomain($name, $path); } // Set a language $site_language = $this->app->config->dget('site', 'default_language', 'en'); $locale = $args['locale'] ?? $site_language; $i18n->setLocale($locale); $this->setupTranslateLog(); return $i18n; }
php
{ "resource": "" }