_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q30800
StringsExtension.truncate
train
public function truncate($text, $length = 15) { if (!$this->isValidLength($text, $length)) return $text; return (\strlen($text) > $length) ? $this->left($text, $length) . '...' : $text; }
php
{ "resource": "" }
q30801
EmbedImagePlugin.embedImage
train
protected function embedImage(\Swift_Message $message, \DOMAttr $node, array &$images): void { if (0 === strpos($node->nodeValue, 'cid:')) { return; } if (isset($images[$node->nodeValue])) { $node->nodeValue = $images[$node->nodeValue]; } else { $...
php
{ "resource": "" }
q30802
FormAbstract.getEntityContainerIterator
train
public function getEntityContainerIterator() { if (is_null($this->entityContainerIterator)) { $this->entityContainerIterator = new Iterator($this->getEntityContainerMap()->getAll()); } return $this->entityContainerIterator; }
php
{ "resource": "" }
q30803
FormAbstract.validateSynchronizerToken
train
protected function validateSynchronizerToken(array $payload=null) { if ($this->configuration->get('csrf_protection')) { if (!is_null($payload) && isset($payload[$this->configuration->get('csrf_parameter')])) { $this->logger->debug('validate synchronizer token', array('name' => $...
php
{ "resource": "" }
q30804
FormAbstract.validate
train
protected function validate() { if (!$this->validator instanceof ValidatorInterface) { return; } $valid = true; if ($this->getEntityContainerMap()->count() > 0) { $entityContainers = $this->getEntityContainerMap()->getAll(); $this->logger->debug(...
php
{ "resource": "" }
q30805
FormAbstract.attachEntityContainer
train
protected function attachEntityContainer(EntityContainerInterface $entityContainer) { $this->getEntityContainerMap()->set($entityContainer->getName(), $entityContainer); // reset entity cached iterator $this->resetEntityIterator(); }
php
{ "resource": "" }
q30806
FormAbstract.attachEntities
train
public function attachEntities(array $entities) { foreach ($entities as $name => $entitie) { $this->attachEntity($entitie, $name); } }
php
{ "resource": "" }
q30807
Post.byId
train
public static function byId( Client $client, int $id ): self { $posts = self::search($client, ['id:' . $id], 1, 1); if (count($posts) === 0) { throw new PostNotFoundException(sprintf( 'Post with ID %d not found', $id )); ...
php
{ "resource": "" }
q30808
Post.fromArray
train
protected static function fromArray( Client $client, array $post ): self { $originalFile = isset($post['file_ext']) ? File::fromArray($post) : null; $tags = Tag::byNames($client, explode(' ', $post['tag_string'])); return new self( $post[...
php
{ "resource": "" }
q30809
Post.getRatingByStringIdentifier
train
protected static function getRatingByStringIdentifier(string $identifier): int { switch ($identifier) { case 's': return PostInterface::RATING_SAFE; case 'q': return PostInterface::RATING_QUESTIONABLE; case 'e': return Pos...
php
{ "resource": "" }
q30810
Post.getStatusByBooleanFlags
train
protected static function getStatusByBooleanFlags( bool $isPending, bool $isDeleted, bool $isBanned ): int { if ($isBanned === true) { return PostInterface::STATUS_DELETED; } if ($isDeleted === true) { return PostInterface::STATUS_DELETED; ...
php
{ "resource": "" }
q30811
Container.generateMetadataHeaders
train
public static function generateMetadataHeaders(array $metadata, $prefix = NULL) { if (empty($prefix)) { $prefix = Container::METADATA_HEADER_PREFIX; } $headers = array(); foreach ($metadata as $key => $val) { $headers[$prefix . $key] = $val; } return $headers; }
php
{ "resource": "" }
q30812
Container.objectUrl
train
public static function objectUrl($base, $oname) { if (strpos($oname, '/') === FALSE) { return $base . '/' . rawurlencode($oname); } $oParts = explode('/', $oname); $buffer = array(); foreach ($oParts as $part) { $buffer[] = rawurlencode($part); } $newname = implode('/', $buffer)...
php
{ "resource": "" }
q30813
Container.extractHeaderAttributes
train
public static function extractHeaderAttributes($headers, $prefix = NULL) { if (empty($prefix)) { $prefix = Container::METADATA_HEADER_PREFIX; } $attributes = array(); $offset = strlen($prefix); foreach ($headers as $header => $value) { $index = strpos($header, $prefix); if ($index...
php
{ "resource": "" }
q30814
Container.newFromJSON
train
public static function newFromJSON($jsonArray, $token, $url) { $container = new Container($jsonArray['name']); $container->baseUrl = $url; $container->url = $url . '/' . rawurlencode($jsonArray['name']); $container->token = $token; // Access to count and bytes is basically controlled. This is is ...
php
{ "resource": "" }
q30815
Container.newFromResponse
train
public static function newFromResponse($name, $response, $token, $url) { $container = new Container($name); $container->bytes = $response->header('X-Container-Bytes-Used', 0); $container->count = $response->header('X-Container-Object-Count', 0); $container->baseUrl = $url; $container->url = $url . '...
php
{ "resource": "" }
q30816
Container.save
train
public function save(Object $obj, $file = NULL) { if (empty($this->token)) { throw new \HPCloud\Exception('Container does not have an auth token.'); } if (empty($this->url)) { throw new \HPCloud\Exception('Container does not have a URL to send data.'); } //$url = $this->url . '/' . raw...
php
{ "resource": "" }
q30817
Container.updateMetadata
train
public function updateMetadata(Object $obj) { //$url = $this->url . '/' . rawurlencode($obj->name()); $url = self::objectUrl($this->url, $obj->name()); $headers = array(); // See if we have any metadata. We post this even if there // is no metadata. $md = $obj->metadata(); if (!empty($md)) ...
php
{ "resource": "" }
q30818
Container.copy
train
public function copy(Object $obj, $newName, $container = NULL) { //$sourceUrl = $obj->url(); // This doesn't work with Object; only with RemoteObject. $sourceUrl = self::objectUrl($this->url, $obj->name()); if (empty($newName)) { throw new \HPCloud\Exception("An object name is required to copy the ob...
php
{ "resource": "" }
q30819
Container.object
train
public function object($name, $requireSSL = TRUE) { $url = self::objectUrl($this->url, $name); $cdn = self::objectUrl($this->cdnUrl, $name); $cdnSsl = self::objectUrl($this->cdnSslUrl, $name); $headers = array(); // Auth token. $headers['X-Auth-Token'] = $this->token; $client = \HPCloud\T...
php
{ "resource": "" }
q30820
Container.proxyObject
train
public function proxyObject($name) { $url = self::objectUrl($this->url, $name); $cdn = self::objectUrl($this->cdnUrl, $name); $cdnSsl = self::objectUrl($this->cdnSslUrl, $name); $headers = array( 'X-Auth-Token' => $this->token, ); $client = \HPCloud\Transport::instance(); if (empty(...
php
{ "resource": "" }
q30821
Container.objects
train
public function objects($limit = NULL, $marker = NULL) { $params = array(); return $this->objectQuery($params, $limit, $marker); }
php
{ "resource": "" }
q30822
Container.objectsWithPrefix
train
public function objectsWithPrefix($prefix, $delimiter = '/', $limit = NULL, $marker = NULL) { $params = array( 'prefix' => $prefix, 'delimiter' => $delimiter, ); return $this->objectQuery($params, $limit, $marker); }
php
{ "resource": "" }
q30823
Container.loadExtraData
train
protected function loadExtraData() { // If URL and token are empty, we are dealing with // a local item that has not been saved, and was not // created with Container::createContainer(). We treat // this as an error condition. if (empty($this->url) || empty($this->token)) { throw new \HPCloud...
php
{ "resource": "" }
q30824
Container.objectQuery
train
protected function objectQuery($params = array(), $limit = NULL, $marker = NULL) { if (isset($limit)) { $params['limit'] = (int) $limit; if (!empty($marker)) { $params['marker'] = (string) $marker; } } // We always want JSON. $params['format'] = 'json'; $query = http_buil...
php
{ "resource": "" }
q30825
Container.delete
train
public function delete($name) { $url = self::objectUrl($this->url, $name); $headers = array( 'X-Auth-Token' => $this->token, ); $client = \HPCloud\Transport::instance(); try { $response = $client->doRequest($url, 'DELETE', $headers); } catch (\HPCloud\Transport\FileNotFoundExce...
php
{ "resource": "" }
q30826
TypeValidator.setType
train
public function setType(?string $type): self { if (!$this->isValidType($type)) { throw new \InvalidArgumentException(\sprintf( "Invalid type '%s'. Must be either NULL, one of %s, or a fully qualified class name or interface", $type, \implode(', ', ...
php
{ "resource": "" }
q30827
TypeValidator.validate
train
public function validate($element): bool { if (!$expectedType = $this->getType()) { return true; } $expectedType = $this->typeMap[$expectedType] ?? $expectedType; $actualType = \gettype($element); if (($actualType === 'object' && $element instanceof $expectedT...
php
{ "resource": "" }
q30828
DynamoDbEventStore.getItemKeyByEventId
train
protected function getItemKeyByEventId(Identifier $eventId, array $context = []): ?array { $tableName = $this->getTableNameForRead($context); $params = [ 'TableName' => $tableName, 'IndexName' => EventStoreTable::GSI_EVENT_ID_NAME, ...
php
{ "resource": "" }
q30829
DynamoDbEventStore.optimisticCheck
train
protected function optimisticCheck(StreamId $streamId, string $expectedEtag, array $context): void { $slice = $this->getStreamSlice($streamId, null, 1, false, true, $context); if (!$slice->count()) { throw new OptimisticCheckFailed( sprintf( 'The Dyna...
php
{ "resource": "" }
q30830
ExceptionHandler.verbose
train
public function verbose($verbose = null) { if ($verbose !== null) { $this->details = (bool) $verbose; } return $this->details; }
php
{ "resource": "" }
q30831
ExceptionHandler.depthLimit
train
public function depthLimit($depthLimit = null) { if($depthLimit !== null) { $this->depthLimit = (int) $depthLimit; } return $this->depthLimit; }
php
{ "resource": "" }
q30832
ExceptionHandler.handlerTerse
train
public function handlerTerse(\Exception $exception) { if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error', true, 500); header('Content-type: text/plain; charset=UTF-8'); } echo sprintf('Bad Moss: %s ( %s at line: %u )', $exception->getMessage(), $except...
php
{ "resource": "" }
q30833
ExceptionHandler.handlerVerbose
train
public function handlerVerbose(\Exception $exception) { if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error', true, 500); header('Content-type: text/html; charset=UTF-8'); } echo sprintf( '<!DOCTYPE html> <html> <head> ...
php
{ "resource": "" }
q30834
ExceptionHandler.lineNumbers
train
public function lineNumbers($lineSeparator, $source, $mark = null) { $count = count(explode($lineSeparator, $source)); $tpl = '<span %s>%u</span>'; $lines = []; for ($i = 0; $i < $count; $i++) { $lines[] = sprintf($tpl, '', $i + 1); } $lines[$mark - 1] =...
php
{ "resource": "" }
q30835
ExceptionHandler.limit
train
public function limit($var, $depth, array &$references = []) { if ($depth > $this->depthLimit) { return '*DEPTH LIMIT*'; } if (is_array($var)) { return $this->limitArray($var, $depth, $references); } if (is_object($var)) { return $this->l...
php
{ "resource": "" }
q30836
ExceptionHandler.limitArray
train
public function limitArray($var, $depth, array &$references) { foreach ($var as &$value) { $value = $this->limit($value, $depth + 1, $references); unset($value); } return $var; }
php
{ "resource": "" }
q30837
ExceptionHandler.limitObject
train
public function limitObject($var, $depth, array &$references) { $hash = spl_object_hash($var); if (in_array($hash, $references)) { return '*RECURSION*'; } $references[] = $hash; $ref = new \ReflectionObject($var); foreach ($ref->getProperties() as $prop)...
php
{ "resource": "" }
q30838
CloneController.copy
train
private function copy() { $source = Yii::getAlias($this->source); if (!file_exists($source) || !is_dir($source)) { throw new ErrorException("Source directory {$this->source} not found"); } $destination = Yii::getAlias($this->destination); if (!$this->replace && is...
php
{ "resource": "" }
q30839
CloneController.replace
train
private function replace() { $destination = Yii::getAlias($this->destination); $destinationModuleName = $this->getDestinationModuleName(); $counter = 0; $files = FileHelper::findFiles($destination); asort($files); foreach ($files as $path) { if (!$this->re...
php
{ "resource": "" }
q30840
Dispatcher.call
train
protected function call($eventName, $subject = null, $message = null) { if (!isset($this->events[$eventName])) { return $subject; } foreach ($this->events[$eventName] as $listener) { if ($this->stop) { break; } $subject = $lis...
php
{ "resource": "" }
q30841
Model.wrap
train
public static function wrap($bean, $modelClass = null) { if (is_array($bean)) { $collection = new Collection($bean); $collection->map(function ($item) use ($modelClass) { if ($modelClass) { return new $modelClass($item); } else { ...
php
{ "resource": "" }
q30842
Model.dispense
train
public static function dispense($num = 1, $alwaysReturnArray = false) { $bean = DB::dispense(static::getTable(), $num, $alwaysReturnArray); $model = static::wrap($bean); return $model; }
php
{ "resource": "" }
q30843
Model.findLike
train
public static function findLike($like = [], $sql = '') { $items = DB::findLike(static::getTable(), $like, $sql); return static::wrap($items); }
php
{ "resource": "" }
q30844
Model.findCollection
train
public static function findCollection($sql = null, $bindings = []) { $collection = DB::findCollection(static::getTable(), $sql, $bindings); return new BeanCollection($collection); }
php
{ "resource": "" }
q30845
Model.save
train
public function save() { //Set Defaults $this->setDefaultProperties(); //Update timestamps $this->updateTimestamps(); //Fire "before" events if (!$this->fireBeforeSaveEvent($this)) { return false; } $updating = $this->exists(); ...
php
{ "resource": "" }
q30846
Model.trash
train
public function trash() { if ($this->fireBeforeTrashEvent($this)) { $result = DB::trash($this->bean); $this->fireAfterTrashEvent($result); return true; } else { return false; } }
php
{ "resource": "" }
q30847
Model.owns
train
public function owns($related, $exclusive = true) { $table = ucfirst($related::getTable()); $column = ($exclusive ? 'x' : '') . "own{$table}List"; $this->bean->$column[] = $related->getBean(); }
php
{ "resource": "" }
q30848
Model.hasMany
train
public function hasMany(Model $related) { $table = ucfirst($related->getTable()); $column = "shared{$table}List"; $this->bean->$column[] = $related->getBean(); }
php
{ "resource": "" }
q30849
Model.getMany
train
public function getMany($relatedClass) { $table = ucfirst($relatedClass::getTable()); $column = "shared{$table}List"; return static::wrap($this->bean->$column, $relatedClass); }
php
{ "resource": "" }
q30850
Model.belongsTo
train
public function belongsTo($related, $foreignKey = '') { if (!$foreignKey && $related instanceof Model) { $column = $related->getTable(); } else { $column = $foreignKey; } if (empty($related)) { unset($this->bean->$column); } elseif ($relat...
php
{ "resource": "" }
q30851
Model.getOwner
train
public function getOwner($relatedClass, $foreignKey = '') { if (!$foreignKey) { $column = $relatedClass::getTable(); } else { $column = $foreignKey; } return static::wrap($this->fetchAs($relatedClass)->$column, $relatedClass); }
php
{ "resource": "" }
q30852
Model.runHandlers
train
private function runHandlers($event, $data = null) { foreach ($this->handlers[$event] as $handler) { if (!is_callable($handler)) { return false; } if (!$handler($data)) { return false; } } return true; }
php
{ "resource": "" }
q30853
Model.addHandler
train
protected function addHandler($event, callable $handler) { if (!isset($this->handlers[$event])) { throw new Exception("No such event '$event'"); } if (!is_callable($handler)) { throw new Exception("Event handlers must be callable"); } $this->handlers...
php
{ "resource": "" }
q30854
Model.removeHandler
train
protected function removeHandler($event, $key) { if ($this->hasHandler($event, $key)) { unset($this->handlers[$event][$key]); } }
php
{ "resource": "" }
q30855
EventHelper.isAttributeChanged
train
public static function isAttributeChanged(Event $event, $attribute) { /** @var ActiveRecord $sender */ $sender = $event->sender; if (!isset($event->changedAttributes)) { return $sender->isAttributeChanged($attribute); } return isset($event->changedAttributes[$attr...
php
{ "resource": "" }
q30856
UpgradeHandler.ensureCorrectColumnType
train
private function ensureCorrectColumnType() { if (!$this->database->tableExists('tl_metamodel_attribute')) { return; } $attributes = $this ->database ->prepare( 'SELECT metamodel.tableName, attribute.colname FROM tl_metamode...
php
{ "resource": "" }
q30857
GendoriaCommandQueueBundle.getContainerExtension
train
public function getContainerExtension() { if (null === $this->extension || false === $this->extension) { $this->extension = new GendoriaCommandQueueExtension(); } return $this->extension; }
php
{ "resource": "" }
q30858
Handler.prepare
train
public function prepare(Exception $exception) { if ($exception instanceof NotFoundHttpException) { return $exception->createsClientError(); } else if ($exception instanceof ServiceUnavailableHttpException) { return $exception->createsServerError(); } return $exception; }
php
{ "resource": "" }
q30859
Session.destroy
train
public function destroy() { unset($this->storage); $_SESSION = []; session_destroy(); $this->startSession(); $this->storage = & $_SESSION; return $this; }
php
{ "resource": "" }
q30860
RelationViaBehavior.getRules
train
protected function getRules() { $result = []; $relationNames = []; foreach ($this->relations as $key => $value) { $relationNames[] = is_array($value) ? $key : $value; } foreach ($this->owner->rules() as $key => $rule) { $attributes = is_array($rule[0]...
php
{ "resource": "" }
q30861
Route.getTargetController
train
public function getTargetController() { $target = $this->getTarget(); if ($target instanceof Closure || !preg_match(Router::TARGET_REGEX, $target)) { return null; } $parts = explode('@', $target); return isset($parts[0]) ? $parts[0] : null; }
php
{ "resource": "" }
q30862
Route.setRouteURI
train
public function setRouteURI($routeURI) { //Add group prefix if any $groupPrefix = implode('/', Router::$groupsProps['prefix']); if ($groupPrefix) { //Remove duplicate forward slashes in prefix $prefixed = trim(preg_replace('/\/+/', '/', $groupPrefix), '/'); ...
php
{ "resource": "" }
q30863
Route.setTarget
train
public function setTarget($target) { //Add to route group if any if (!$target instanceof \Closure) { $groupNamespace = implode('\\', Router::$groupsProps['namespace']); $target = $groupNamespace ? "$groupNamespace\\$target" : $target; } if (!$target instanceo...
php
{ "resource": "" }
q30864
Route.setName
train
public function setName($name) { if ($this->lock) { throw new Exception('Route cannot be modified'); } if (empty($name)) { return $name; } //Add group name if any $groupName = implode('', Router::$groupsProps['name']); $this->name = $...
php
{ "resource": "" }
q30865
Route.setMiddleware
train
public function setMiddleware($middleware) { if ($this->lock) { throw new Exception('Route cannot be modified'); } $curMiddleware = []; if (is_array($middleware)) { $curMiddleware = $middleware; } else { $args = func_get_args(); ...
php
{ "resource": "" }
q30866
Qq.getOpenId
train
public function getOpenId(AccessToken $token) { $request = $this->getAuthenticatedRequest(self::METHOD_GET, $this->domain.'/oauth2.0/me?access_token='.(string)$token); $response = $this->getResponse($request); return isset($response['openid']) ? $response['openid'] : null; }
php
{ "resource": "" }
q30867
Qq.getResourceOwner
train
public function getResourceOwner(AccessToken $token) { $this->openId = $this->getOpenId($token); return parent::getResourceOwner($token); }
php
{ "resource": "" }
q30868
BBCodeHelper.parser
train
public function parser($text) { //Gets all current class methods, except for `parser()` and `remove()` $methods = array_diff(get_child_methods(get_class()), ['parser', 'remove']); //Calls dynamically each method foreach ($methods as $method) { $text = call_user_func([$th...
php
{ "resource": "" }
q30869
BBCodeHelper.youtube
train
public function youtube($text) { return preg_replace_callback($this->pattern['youtube'], function ($matches) { $id = is_url($matches[1]) ? Youtube::getId($matches[1]) : $matches[1]; return $this->Html->youtube($id); }, $text); }
php
{ "resource": "" }
q30870
TwoFactorAuthentication.requestCode
train
public function requestCode($clientRef, $phoneNumber, $optionalArgs = array()) { $requestCode = new RequestCode; $requestCode ->setClientRef($clientRef) ->setPhoneNumber($phoneNumber); if (count($optionalArgs) > 0) { foreach ($optionalArgs as $key => $val...
php
{ "resource": "" }
q30871
TwoFactorAuthentication.validateCode
train
public function validateCode($clientRef, $code) { $response = $this->request('TFA/Validate', array($clientRef, $code)); $serializer = SerializerBuilder::create()->build(); $result = $serializer->deserialize( $response, 'Fortytwo\SDK\TwoFactorAuthentication\Response2F...
php
{ "resource": "" }
q30872
Client.sendRequest
train
public function sendRequest( string $endpoint, array $queryString = [] ) { $headers = [ 'Accept' => 'application/json', ]; if ($this->getApiKey() !== null) { $headers['Authorization'] = base64_encode($this->getApiKey()); } $curl = cur...
php
{ "resource": "" }
q30873
CommandProcessorPass.process
train
public function process(ContainerBuilder $container) { if (!$container->hasDefinition($this->processorFactoryService) && !$container->hasAlias($this->processorFactoryService)) { return; } $dispatcher = $container->findDefinition($this->processorFactoryService); foreach ...
php
{ "resource": "" }
q30874
PageTree.getBlockManagers
train
public function getBlockManagers($slotName) { $slotManager = $this->templateManager->getSlotManager($slotName); if (null === $slotManager) { return array(); } return $slotManager->getBlockManagersCollection()->getBlockManagers(); }
php
{ "resource": "" }
q30875
PageTree.setUp
train
public function setUp(ThemeInterface $theme, TemplateManager $templateManager, PageBlocksInterface $pageBlocks, Template $template = null) { $this->templateManager = $templateManager; $this->pageBlocks = $pageBlocks; $this->theme = $theme; $this->dispatch(PageTreeEvent\PageTreeEvent...
php
{ "resource": "" }
q30876
PageTree.setUpMetaTags
train
protected function setUpMetaTags() { $seo = $this->getSeo(); if (null !== $seo) { $this->metaTitle = $seo->getMetaTitle(); $this->metaDescription = $seo->getMetaDescription(); $this->metaKeywords = $seo->getMetaKeywords(); } }
php
{ "resource": "" }
q30877
AbstractCustomerSubject.hasBeenProcessed
train
public function hasBeenProcessed(array $identifier) { // explode the identifier (we need email + website code) list ($email, $website) = $identifier; // query whether or not the entity ID has already been mapped return isset($this->customerIdentifierEntityIdMapping[$email][$website...
php
{ "resource": "" }
q30878
BlockManagerJsonBlockCollectionBase.manageCollection
train
protected function manageCollection(array $values, $savedValues = null, $blockKey = null) { if (array_key_exists('Content', $values)) { $data = json_decode($values['Content'], true); if (null === $savedValues) { $savedValues = $this->decodeJsonContent($this->alBlock);...
php
{ "resource": "" }
q30879
Includes.add
train
public function add($keys) { foreach ($this->expandKeys((array) $keys) as $key) { if (!$this->has($key)) { $this->keys[] = $key; } } return $this; }
php
{ "resource": "" }
q30880
Includes.remove
train
public function remove($keys) { $keys = (array) $keys; // Cast all the things $this->keys = array_filter($this->keys(), function ($key) use ($keys) { foreach ($keys as $remove) { if (preg_match('/^'.preg_quote($remove, '/').'(\..+)?$/', $key)) { // Key...
php
{ "resource": "" }
q30881
Includes.setParams
train
public function setParams(array $params) { // Is this an associative array? if (!empty($params)) { if (\count(array_filter(array_keys($params), '\is_string')) < 1) { throw new ParseIncludesException('Parameters must be an associative array indexed by key'); } ...
php
{ "resource": "" }
q30882
Includes.paramsFor
train
public function paramsFor(string $key): array { $params = []; if (isset($this->params[$key])) { $params = $this->params[$key]; } return $params; }
php
{ "resource": "" }
q30883
Includes.splice
train
public function splice($parentKey) { // Get all the descendant keys $keys = $this->descendantsOf($parentKey); // Cool, we have a list of keys, now let's get the associated params $params = $this->allParamsFor($keys); // That was hard return new static( $keys, ...
php
{ "resource": "" }
q30884
Includes.allParamsFor
train
public function allParamsFor(array $keys): array { $params = []; foreach ($keys as $key) { if (isset($this->params[$key])) { $params[$key] = $this->params[$key]; } } return $params; }
php
{ "resource": "" }
q30885
User.setRoles
train
public function setRoles(Collection $roles) { $this->roles->clear(); foreach ($roles as $role) { $this->roles[] = $role; } }
php
{ "resource": "" }
q30886
SiteBootstrap.bootstrap
train
public function bootstrap() { $languageRepository = $this->languageManager->getLanguageRepository(); $pageRepository = $this->pageManager->getPageRepository(); $blockRepository = $this->blockManager->getBlockRepository(); $languageRepository->startTransaction(); if ( ! $this...
php
{ "resource": "" }
q30887
SiteBootstrap.removeActiveLanguages
train
protected function removeActiveLanguages(LanguageRepositoryInterface $languageRepository) { try { $languages = $languageRepository->activeLanguages(); foreach ($languages as $language) { $language->delete(); } return true; } catch (\Ex...
php
{ "resource": "" }
q30888
SiteBootstrap.removeActivePages
train
protected function removeActivePages(PageRepositoryInterface $pageRepository) { try { $pages = $pageRepository->activePages(); foreach ($pages as $page) { $page->delete(); } return true; } catch (\Exception $ex) { $this->er...
php
{ "resource": "" }
q30889
CustomFieldValue.getId027Attribute
train
public function getId027Attribute($value) { $type = collect(config('pulsar.dataTypes'))->keyBy('id')[$this->data_type_id_026]->type; if($type == 'array') $value = explode(',', $value); else settype($value, $type); return $value; }
php
{ "resource": "" }
q30890
AddSeoListener.onBeforeAddPageCommit
train
public function onBeforeAddPageCommit(BeforeAddPageCommitEvent $event) { if ($event->isAborted()) { return; } $pageManager = $event->getContentManager(); $pageRepository = $pageManager->getPageRepository(); $values = $event->getValues(); if (!is_array($v...
php
{ "resource": "" }
q30891
Factory.createLogger
train
public function createLogger($name) { // short circuit for cached logger objects if (true === array_key_exists($name, $this->_logger)) { return $this->_logger[$name]; } $loggerConfig = $this->_getLoggerConfig($name); $handlers = $this->createHandlers($logge...
php
{ "resource": "" }
q30892
Game.getFbAppIds
train
public function getFbAppIds() { $apps = array('' => 'Don\'t deploy on Facebook'); $results = $this->getEventManager() ->trigger(__FUNCTION__, $this, array( 'apps' => $apps, )) ->last(); if ($results) { $apps = $results; ...
php
{ "resource": "" }
q30893
AttachedRelationBehavior.beforeValidate
train
public function beforeValidate() { $this->reset(); foreach ($this->relations as $key => $relation) { $data = is_array($relation) ? $relation : []; $relation = is_array($relation) ? $key : $relation; $ruleLoad = FormHelper::loadRelation($this->owner, $relation, Yii...
php
{ "resource": "" }
q30894
AttachedRelationBehavior.getRelationSavingModels
train
public function getRelationSavingModels($relation) { $result = isset($this->savingModels[$relation]) ? $this->savingModels[$relation] : $this->owner->$relation; return is_array($result) && (!$this->owner->getRelation($relation)->multiple) ? reset($result) : $resul...
php
{ "resource": "" }
q30895
Search.getQuery
train
public function getQuery() { $query = $this->database->getSelectQuery()->from($this->table); foreach ($this->join as $join) { if (!is_array($join[2])) { $join[2] = [$join[2]]; } $where = array_shift($join[2]); if (!empty($join[2])) { ...
php
{ "resource": "" }
q30896
Search.getTotal
train
public function getTotal() { $query = $this->getQuery()->select('COUNT(*) as total'); $rows = $this->database->query($query, $this->database->getBinds()); if (!isset($rows[0]['total'])) { return 0; } return $rows[0]['total']; }
php
{ "resource": "" }
q30897
DeleteLanguageBaseListener.onBeforeDeleteLanguageCommit
train
public function onBeforeDeleteLanguageCommit(BeforeDeleteLanguageCommitEvent $event) { if ($event->isAborted()) { return; } $this->languageManager = $event->getContentManager(); $languageRepository = $this->languageManager->getLanguageRepository(); $this->source...
php
{ "resource": "" }
q30898
User.getSecretAttribute
train
public function getSecretAttribute($value) { if ($value == null) $this->update(['secret' => $secret = (new Hashids(Hash::random(20), 15))->encode($this->id)]); return $value ?? $secret; }
php
{ "resource": "" }
q30899
User.getApiKeyAttribute
train
public function getApiKeyAttribute($value) { if ($value == null) $this->update(['api_key' => $key = Hash::random(25)]); return $value ?? $key; }
php
{ "resource": "" }