_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q261900
AbstractResource.create
test
protected function create() { if ( !empty( $this->getID() ) ) { throw new \Exception('Object already has an ID, create() not possible'); } if ( !$this->isDirty() ) { return $this; } $url = $this->getURL('create'); $response = $this->getClient()->post( $url, $this->getUnsavedValues(), [ 'expand' => true, ] ); if ( $response->hasError() ) { $this->setError( $response->getError() ); return $this; } $this->clearError(); $this->setRemoteData( $response->getData() ); $this->clearUnsavedValues(); return $this; }
php
{ "resource": "" }
q261901
AbstractResource.update
test
protected function update() { $object_id = $this->getID(); if ( empty($object_id) ) { throw new \Exception('Object has no ID, update() not possible'); } if ( !$this->isDirty() ) { return $this; } $url = $this->getURL( 'update', [ 'object_id' => $object_id, ] ); $response = $this->getClient()->put( $url, $this->getUnsavedValues(), [ 'expand' => true, ] ); if ( $response->hasError() ) { $this->setError( $response->getError() ); return $this; } $this->clearError(); $this->setRemoteData( $response->getData() ); $this->clearUnsavedValues(); return $this; }
php
{ "resource": "" }
q261902
AbstractResource.delete
test
public function delete() { // Delete object in Zammad. $object_id = $this->getID(); if ( !empty($object_id) ) { $url = $this->getURL( 'delete', [ 'object_id' => $object_id, ] ); $response = $this->getClient()->delete( $url, [ 'expand' => true, ] ); if ( $response->hasError() ) { $this->setError( $response->getError() ); return $this; } } // Clear data of this (local) object. $this->clearError(); $this->clearRemoteData(); $this->clearUnsavedValues(); return $this; }
php
{ "resource": "" }
q261903
AbstractResource.getURL
test
protected function getURL( $method_name, array $placeholder_values = [] ) { if ( !array_key_exists( $method_name, $this::URLS ) ) { throw new \RuntimeException( "Method '$method_name' is not supported for " . get_class($this) . ' resource' ); } $url = $this::URLS[$method_name]; foreach ( $placeholder_values as $placeholder => $value ) { $url = preg_replace( "/\{$placeholder\}/", "$value", $url ); } return $url; }
php
{ "resource": "" }
q261904
Tag.get
test
public function get($object_id, $object_type = 'Ticket') { $this->clearError(); $object_id = intval($object_id); if ( empty($object_id) ) { throw new \RuntimeException('Missing object ID'); } $response = $this->getClient()->get( $this->getURL('get'), [ 'object' => $object_type, 'o_id' => $object_id, ] ); if ( $response->hasError() ) { $this->setError( $response->getError() ); } else { $this->clearError(); $this->setRemoteData( $response->getData() ); } return $this; }
php
{ "resource": "" }
q261905
Tag.add
test
public function add($object_id, $tag, $object_type = 'Ticket') { $this->clearError(); $object_id = intval($object_id); if ( empty($object_id) ) { throw new \RuntimeException('Missing object ID'); } if ( empty($tag) ) { throw new \RuntimeException('Missing tag'); } $response = $this->getClient()->get( $this->getURL('add'), [ 'object' => $object_type, 'o_id' => $object_id, 'item' => $tag, ] ); if ( $response->hasError() ) { $this->setError( $response->getError() ); } return $this; }
php
{ "resource": "" }
q261906
Tag.search
test
public function search($search_term, $page = null, $objects_per_page = null) { $this->clearError(); if ( empty($search_term) ) { throw new \RuntimeException('Missing search term'); } $response = $this->getClient()->get( $this->getURL('search'), [ 'term' => $search_term, ] ); if ( $response->hasError() ) { $this->setError( $response->getError() ); } $this->clearError(); // Return array of resource objects if no $object_id was given. // Note: the resource object (this object) used to execute get() will be left empty in this case. $objects = []; foreach ( $response->getData() as $object_data ) { $object = $this->getClient()->resource( get_class($this) ); $object->setRemoteData($object_data); $objects[] = $object; } return $objects; }
php
{ "resource": "" }
q261907
Tag.remove
test
public function remove($object_id, $tag, $object_type = 'Ticket') { $this->clearError(); if ( empty($object_id) ) { throw new \RuntimeException('Missing object ID'); } if ( empty($tag) ) { throw new \RuntimeException('Missing tag'); } // Delete object in Zammad. $response = $this->getClient()->get( $this->getURL('remove'), [ 'object' => $object_type, 'o_id' => $object_id, 'item' => $tag, ] ); if ( $response->hasError() ) { $this->setError( $response->getError() ); return $this; } // Clear data of this (local) object. $this->clearError(); $this->clearRemoteData(); $this->clearUnsavedValues(); return $this; }
php
{ "resource": "" }
q261908
Database.shmTeardown
test
protected function shmTeardown($file) { // verify the shmop extension is loaded if (!extension_loaded('shmop')) { throw new \Exception(__CLASS__ . ": Please make sure your PHP setup has the 'shmop' extension enabled.", self::EXCEPTION_NO_SHMOP); } // Get actual file path $rfile = realpath($file); // If the file cannot be found, except away if (false === $rfile) { throw new \Exception(__CLASS__ . ": Database file '{$file}' does not seem to exist.", self::EXCEPTION_DBFILE_NOT_FOUND); } $shmKey = self::getShmKey($rfile); // Try to open the memory segment for writing $shmId = @shmop_open($shmKey, 'w', 0, 0); if (false === $shmId) { throw new \Exception(__CLASS__ . ": Unable to access shared memory block '{$shmKey}' for writing.", self::EXCEPTION_SHMOP_WRITING_FAILED); } // Delete and close the descriptor shmop_delete($shmId); shmop_close($shmId); }
php
{ "resource": "" }
q261909
Database.readProxyType
test
private function readProxyType($pointer) { if (false === $pointer) { // Deal with invalid IPs $proxyType = self::INVALID_IP_ADDRESS; } elseif (0 === self::$columns[self::PROXY_TYPE][$this->type]) { // If the field is not suported, return accordingly $proxyType = self::FIELD_NOT_SUPPORTED; } else { // Read proxy type $proxyType = $this->readString($pointer + self::$columns[self::PROXY_TYPE][$this->type]); } return $proxyType; }
php
{ "resource": "" }
q261910
LongPoll.getConnectionInfo
test
public function getConnectionInfo($d) { return sprintf(self::URL_CONNECTION_INFO, $d->server, $d->key, $d->ts); }
php
{ "resource": "" }
q261911
LongPoll.doLoop
test
public function doLoop() { $server = $this->getServerData(); $initial = $this->getConnectionInfo($server); $user = new User($this->vk); $userMap = []; $userCache = []; /* * @param $id * @return Model\User */ $fetchData = function ($id) use ($user, &$userMap, &$userCache) { if (!isset($userMap[$id])) { $userMap[$id] = count($userCache); $userCache[] = $user->get($id)->response->get(); } return $userCache[$userMap[$id]]; }; while ($data = $this->guzzle->get($initial)->json(['object' => true])) { $server->ts = $data->ts; $initial = $this->getConnectionInfo($server); foreach ($data->updates as $update) { /* * @var $user Model\User */ switch ($update[0]) { case LP::MESSAGE_ADD: $user = $fetchData($update[3]); if ($update[2] & 2) { continue; } printf("New message from %s '%s'\n", $user->getName(), $update[6]); var_dump($update); break; case LP::MESSAGE_WRITE: $user = $fetchData($update[1]); printf("User %s writing\n", $user->getName()); break; case LP::DATA_ADD: break; case LP::FRIEND_OFFLINE: $user = $fetchData($update[1] * -1); $status = $update[2] == 1 ? 'AFK' : 'Exit'; printf("User %s offline(%s)\n", $user->getName(), $status); break; case LP::FRIEND_ONLINE: $user = $fetchData($update[1] * -1); printf("User %s online\n", $user->getName()); break; default: printf("Unknown event %s {%s}\n", $update[0], implode(',', $update)); break; } } } }
php
{ "resource": "" }
q261912
VkJs.execute
test
public function execute() { $execute = $this->dataString; if ($this->requests) { foreach ($this->requests as $request) { $execute .= ','.$request->dataString; } $execute = '['.$execute.']'; if (!$this->callback && !$this->vk->jsCallback) { $this->vk->jsCallback = true; $oldCallback = $this->vk->callback; $this->callback = function ($data) use (&$oldCallback) { $std = new stdClass(); $std->response = $data; return new Api($std, $oldCallback); }; $this->vk->createAs($this->callback); } } return $this->vk->request('execute', ['code' => sprintf('return %s;', $execute)]); }
php
{ "resource": "" }
q261913
Response.each
test
public function each(Closure $callback) { if (!is_callable($callback)) { return; } $data = []; $this->items ? $data = &$this->items : (!$this->data ?: $data = &$this->data); foreach ($data as $k => $v) { call_user_func_array($callback, [$k, $v]); } }
php
{ "resource": "" }
q261914
Response.get
test
public function get($id = false) { if (!$id) { if (is_array($this->data)) { return $this->data[0]; } elseif (isset($this->items) && $this->items !== false) { return $this->items[0]; } else { return $this->data; } } else { return $this->data[$id]; } }
php
{ "resource": "" }
q261915
Wall.getSource
test
public function getSource($id = 0) { if ($this->copy_history === false) { return false; } if (!isset($this->copy_history[$id])) { return false; } return new self($this->copy_history[0 + $id]); }
php
{ "resource": "" }
q261916
RequestTransaction.fetchData
test
public function fetchData() { if (!$this->guzzle) { $this->guzzle = new \GuzzleHttp\Client(); } $args = $this->args; if ($this->accessToken) { $args['access_token'] = $this->accessToken; } if ((empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off') && false !== $this->noHttpsSecret) { $args['sig'] = md5('/method/'.$this->methodName.'?'.http_build_query($args).$this->noHttpsSecret); } $data = $this->guzzle->post(self::URL_VK_API . $this->methodName, ['form_params' => $args])->getBody(); $data = json_decode($data); $c = new Api($data, $this->callback); return $c; }
php
{ "resource": "" }
q261917
Account.validateRights
test
public function validateRights($permissions, $bitmask = 0) { $valid = 0; if (is_array($bitmask)) { foreach ($bitmask as $bit) { $valid = $this->validateRights($permissions, $bit); } } else { $valid = $permissions & $bitmask; } return $valid; }
php
{ "resource": "" }
q261918
Core.param
test
public function param($key, $value, $defaultValue = false) { if (!$value && $defaultValue) { $value = $defaultValue; } $this->params[$key] = $value; return $this; }
php
{ "resource": "" }
q261919
Core.params
test
public function params(array $data) { foreach ($data as $k => $v) { $this->param($k, $v); } return $this; }
php
{ "resource": "" }
q261920
Core.request
test
public function request($methodName, $args = false) { if (is_array($args)) { $this->params($args); } $this->params = array_merge($this->params, $this->systemArgs()); $d = new RequestTransaction($methodName, $this->params, $this->accessToken, $this->callback, $this->noHttpsSecret); $this->reset(); return $d; }
php
{ "resource": "" }
q261921
Photos.save
test
public function save($data) { $this->vk ->param('album_id', $data->aid) ->param('server', $data->server) ->param('photos_list', $data->photos_list) ->param('hash', $data->hash) ->request('photos.save')->execute(); }
php
{ "resource": "" }
q261922
Auth.startCallback
test
public function startCallback() { if (isset($_GET['code'])) { $token = $this->getToken($_GET['code']); return $token; } elseif (isset($_GET['error'])) { //blah blah } return false; }
php
{ "resource": "" }
q261923
Auth.getToken
test
public function getToken($code) { if (!$this->guzzle) { $this->guzzle = new \GuzzleHttp\Client(); } $uri = sprintf( self::URL_ACCESS_TOKEN, $this->g('client_id'), $this->g('client_secret'), $code, urlencode($this->g('redirect_uri')) ); $data = $this->guzzle->get($uri)->getBody(); $data = json_decode($data); if (isset($data->access_token)) { return new \getjump\Vk\Response\Auth($data->access_token, $data->expires_in, $data->user_id); } elseif (isset($data->error)) { // ERROR PROCESSING } return false; }
php
{ "resource": "" }
q261924
ElasticquentResultCollection.hitsToItems
test
private function hitsToItems($instance) { $items = array(); foreach ($this->hits['hits'] as $hit) { $items[] = $instance->newFromHitBuilder($hit); } return $items; }
php
{ "resource": "" }
q261925
ElasticquentTrait.searchByQuery
test
public static function searchByQuery($query = null, $aggregations = null, $sourceFields = null, $limit = null, $offset = null, $sort = null) { $instance = new static; $params = $instance->getBasicEsParams(true, true, true, $limit, $offset); if ($sourceFields) { $params['body']['_source']['include'] = $sourceFields; } if ($query) { $params['body']['query'] = $query; } if ($aggregations) { $params['body']['aggs'] = $aggregations; } if ($sort) { $params['body']['sort'] = $sort; } $result = $instance->getElasticSearchClient()->search($params); return new ResultCollection($result, $instance = new static); }
php
{ "resource": "" }
q261926
StringManipulator.replaceAllDotsExceptLastThree
test
final public static function replaceAllDotsExceptLastThree(string $string): string { $countDots = substr_count($string, '.'); if ($countDots > 3) { $stringArray = explode('.', $string); $string = ''; for ($i = 0; $i < $countDots - 3; ++$i) { $string .= $stringArray[$i].'_'; } $string .= $stringArray[$countDots - 3].'.'.$stringArray[$countDots - 2].'.'.$stringArray[$countDots - 1].'.'.$stringArray[$countDots]; } return $string; }
php
{ "resource": "" }
q261927
StringManipulator.replaceAllDotsExceptLastTwo
test
final public static function replaceAllDotsExceptLastTwo(string $string): string { $countDots = substr_count($string, '.'); if ($countDots > 2) { $stringArray = explode('.', $string); $string = ''; for ($i = 0; $i < $countDots - 2; ++$i) { $string .= $stringArray[$i].'_'; } $string .= $stringArray[$countDots - 2].'.'.$stringArray[$countDots - 1].'.'.$stringArray[$countDots]; } return $string; }
php
{ "resource": "" }
q261928
StringManipulator.replaceAllDotsExceptLast
test
final public static function replaceAllDotsExceptLast(string $string): string { $countDots = substr_count($string, '.'); if ($countDots > 1) { $stringArray = explode('.', $string); $string = ''; for ($i = 0; $i < $countDots - 1; ++$i) { $string .= $stringArray[$i].'_'; } $string .= $stringArray[$countDots - 1].'.'.$stringArray[$countDots]; } return $string; }
php
{ "resource": "" }
q261929
DatetimeType.convertIntlFormaterToMalot
test
public static function convertIntlFormaterToMalot($formatter) { $intlToMalot = array_combine(self::$intlFormater, self::$malotFormater); $patterns = preg_split('([\\\/.:_;,\s-\ ]{1})', $formatter); $exits = array(); foreach ($patterns as $val) { if (isset($intlToMalot[$val])){ $exits[$val] = $intlToMalot[$val]; } else { // it can throw an Exception $exits[$val] = $val; } } return str_replace(array_keys($exits), array_values($exits), $formatter); }
php
{ "resource": "" }
q261930
DatetimeType.convertMalotToIntlFormater
test
public static function convertMalotToIntlFormater($formatter) { $malotToIntl = array_combine(self::$malotFormater, self::$intlFormater); $patterns = preg_split('([\\\/.:_;,\s-\ ]{1})', $formatter); $exits = array(); foreach ($patterns as $val) { if (isset($malotToIntl[$val])){ $exits[$val] = $malotToIntl[$val]; } else { // it can throw an Exception $exits[$val] = $val; } } return str_replace(array_keys($exits), array_values($exits), $formatter); }
php
{ "resource": "" }
q261931
Configuration.addPicker
test
private function addPicker(ArrayNodeDefinition $rootNode) { $rootNode ->children() ->arrayNode('picker') ->canBeUnset() ->addDefaultsIfNotSet() ->treatNullLike(array('enabled' => true)) ->treatTrueLike(array('enabled' => true)) ->children() ->booleanNode('enabled')->defaultTrue()->end() ->arrayNode('configs') ->addDefaultsIfNotSet() ->children() ->enumNode('formatter')->defaultValue('js') ->values(array('js', 'php')) ->end() ->end() ->end() ->end() ->end() ->end() ; }
php
{ "resource": "" }
q261932
AlexaServiceProvider.bindAlexaRequest
test
private function bindAlexaRequest(Request $request) { $this->app->singleton('alexa.request', function($app) use ($request) { /** @var AlexaRequest $alexaRequest */ $alexaRequest = AlexaRequest::capture(); if (!$app['config']['alexa.prompt.enable'] || $alexaRequest->getIntent() !== $app['config']['alexa.prompt.response_intent'] || is_null($alexaRequest->getPromptResponseIntent())) { return $alexaRequest; } else{ $alexaRequest->setPromptResponse(true); return $alexaRequest; } }); }
php
{ "resource": "" }
q261933
AlexaServiceProvider.registerMiddleware
test
protected function registerMiddleware() { $this->app->singleton(\Develpr\AlexaApp\Http\Middleware\Request::class, function ($app) { return new \Develpr\AlexaApp\Http\Middleware\Request($app, $app['alexa.router'], $app['alexa.request'], $app['alexa.router.middleware']); }); $this->app->singleton(\Develpr\AlexaApp\Http\Middleware\Certificate::class, function ($app) { return new \Develpr\AlexaApp\Http\Middleware\Certificate($app['alexa.request'], $app['alexa.certificateProvider'], $app['config']['alexa']); }); }
php
{ "resource": "" }
q261934
Alexa.resume
test
public function resume() { $token = $this->context('AudioPlayer.token'); $url = cache($token); $offset = $this->context('AudioPlayer.offsetInMilliseconds'); return $this->play($url, $token, $offset); }
php
{ "resource": "" }
q261935
DialogDirective.request
test
public function request() { if (!isset($this->alexaRequest)) { $this->alexaRequest = function_exists('app') ? app(AlexaRequest::class) : new AlexaRequest(); } return $this->alexaRequest; }
php
{ "resource": "" }
q261936
LumenServiceProvider.addRequestMiddlewareToBeginning
test
protected function addRequestMiddlewareToBeginning(ReflectionClass $reflection) { $property = $reflection->getProperty('middleware'); $property->setAccessible(true); $middleware = $property->getValue($this->app); array_unshift($middleware, 'Develpr\AlexaApp\Http\Middleware\Request'); $property->setValue($this->app, $middleware); $property->setAccessible(false); }
php
{ "resource": "" }
q261937
AlexaValidator.matches
test
public function matches(Route $route, Request $request) { // If this isn't an Alexa Route then it doesn't match! if (!$route instanceof AlexaRoute) { return false; } if (!$request->isPromptResponse()) { return ($request->getRequestType() . $request->getIntent() == $route->getRouteIntent()); } else { return ($request->getRequestType() . $request->getPromptResponseIntent() == $route->getRouteIntent()); } }
php
{ "resource": "" }
q261938
AlexaRouter.newAlexaRoute
test
protected function newAlexaRoute($methods, $uri, $intent, $action) { return (new AlexaRoute($methods, $uri, $intent, $action))->setContainer($this->container)->setRouter($this); }
php
{ "resource": "" }
q261939
AlexaRequest.getSessionValue
test
public function getSessionValue($key = null) { return array_key_exists($key, $this->getSession()) ? $this->getSession()[$key] : null; }
php
{ "resource": "" }
q261940
AlexaRequest.updateSlot
test
public function updateSlot($slotName, $value, $confirmed = null) { if (!$this->processed) { $this->process(); } if (array_has($this->slots, [$slotName])) { $this->slots[$slotName]['value'] = $value; if ($confirmed) { $this->slots[$slotName]['confirmationStatus'] = $this::CONFIRMED_STATUS; } elseif (!is_null($confirmed) && !$confirmed) { $this->slots[$slotName]['confirmationStatus'] = $this::DENIED_STATUS; } else { $this->slots[$slotName]['confirmationStatus'] = $this::NO_CONFIRMATION_STATUS; } } return $this; }
php
{ "resource": "" }
q261941
AlexaRoute.getValidators
test
public static function getValidators() { $validators = parent::getValidators(); foreach ($validators as $key => $validator) { if ($validator instanceof UriValidator) { break; } } $validators[] = new AlexaValidator; return $validators; }
php
{ "resource": "" }
q261942
AlexaRoute.compileRoute
test
protected function compileRoute() { if (version_compare(\Illuminate\Foundation\Application::VERSION, '5.5.0') < 0) { if ( is_callable( "parent::extractOptionalParameters" ) ) { return parent::compileRoute(); } } if (! $this->compiled) { //todo: this is a bit ugly - we should go deeper and solve the real problem //This is ugly - before 5.4, we didn't use "uri()" method in the RouteCompiler (there was no //route compiler!), and instead we used the private uri instance variable. Which meant that //`uri()` and `uri` were different. $tempRouterIntent = $this->routeIntent; $this->routeIntent = ""; $this->compiled = (new RouteCompiler($this))->compile(); $this->routeIntent = $tempRouterIntent; } return $this->compiled; }
php
{ "resource": "" }
q261943
Certificate.getCertificate
test
private function getCertificate(IlluminateRequest $request) { $signatureChainUri = $request->header(self::CERTIFICATE_URL_HEADER); $this->validateKeychainUri($signatureChainUri); $certificate = $this->certificateProvider->getCertificateFromUri($signatureChainUri); return $certificate; }
php
{ "resource": "" }
q261944
AlexaResponse.prepareResponseData
test
private function prepareResponseData() { $responseData = []; $responseData['version'] = self::ALEXA_RESPONSE_VERSION; $response = []; //Check to see if a speech, card, or reprompt object are set and if so //add them to the data object if (!is_null($this->speech) && $this->speech instanceof OutputSpeech) { $response = $this->speech->toArray(); } if (!is_null($this->card) && $this->card instanceof Card) { $response['card'] = $this->card->toArray(); } if (!is_null($this->reprompt) && $this->reprompt instanceof Reprompt && trim($this->reprompt->getValue()) != "") { $response['reprompt'] = $this->reprompt->toArray(); } if (!is_null($this->directives)) { foreach ($this->directives as $directive) { $response['directives'][] = $directive->toArray(); } } $response['shouldEndSession'] = $this->shouldSessionEnd; $sessionAttributes = $this->getSessionData(); if ($sessionAttributes && count($sessionAttributes) > 0) { $responseData['sessionAttributes'] = $sessionAttributes; } $responseData['response'] = $response; return $responseData; }
php
{ "resource": "" }
q261945
Request.sendRequestThroughRouter
test
protected function sendRequestThroughRouter($request) { $this->app->instance('request', $request); return (new Pipeline($this->app))->send($request)->through($this->middleware)->then(function ($request) { return $this->router->dispatch($this->alexaRequest); }); }
php
{ "resource": "" }
q261946
LaravelServiceProvider.gatherAppMiddleware
test
protected function gatherAppMiddleware(Kernel $kernel) { $reflection = new ReflectionClass($kernel); $property = $reflection->getProperty('middleware'); $property->setAccessible(true); $middleware = $property->getValue($kernel); if ($this->app['config']['alexa.skipCsrfCheck']) { $middleware = $this->unsetCsrfMiddleware($middleware); } return $middleware; }
php
{ "resource": "" }
q261947
FileCertificateProvider.persistCertificate
test
protected function persistCertificate($certificateChainUri, $certificateContents) { $this->filesystem->put($this->calculateFilePath($certificateChainUri), $certificateContents); }
php
{ "resource": "" }
q261948
FileCertificateProvider.retrieveCertificateFromStore
test
protected function retrieveCertificateFromStore($certificateChainUri) { try { $certificateChain = $this->filesystem->get($this->calculateFilePath($certificateChainUri)); } catch (FileNotFoundException $e) { $certificateChain = null; } return $certificateChain; }
php
{ "resource": "" }
q261949
FileCertificateProvider.calculateFilePath
test
private function calculateFilePath($certificateChainUri) { $filename = md5($certificateChainUri); $path = $this->filePath.$filename; return $path; }
php
{ "resource": "" }
q261950
APTitleCapitalizer.setCustomProtectedWords
test
public function setCustomProtectedWords(array $words) { $this->customProtectedWords = []; foreach ($words as $word) { $this->customProtectedWords[] = Stringy::create($word)->trim(); } }
php
{ "resource": "" }
q261951
APTitleCapitalizer.capitalize
test
public function capitalize($string) { $string = $this->normalizeInput($string); $parts = $this->splitStringIntoParts($string); $parts = $this->processStringParts($parts); $parts = $this->processFirstSentenceWordsInParts($parts); $parts = $this->processLastWordInParts($parts); return $this->joinStringParts($parts); }
php
{ "resource": "" }
q261952
APTitleCapitalizer.normalizeInput
test
protected function normalizeInput($string) { $string = Stringy::create($string)->collapseWhitespace(); $string = $this->normalizeInputPunctuation($string->__toString()); return Stringy::create($string); }
php
{ "resource": "" }
q261953
APTitleCapitalizer.processStringParts
test
protected function processStringParts(array $parts) { array_walk($parts, function (&$part) { $part = $this->isWordLike($part) ? $this->processWord($part) : $part; }); return $parts; }
php
{ "resource": "" }
q261954
APTitleCapitalizer.processFirstSentenceWordsInParts
test
protected function processFirstSentenceWordsInParts(array $parts) { $length = count($parts); $isFirst = true; for ($index = 0; $index < $length; $index++) { $part = $parts[$index]; if ($this->isWordLike($part)) { if ($isFirst) { $parts[$index] = $this->processFirstLastWord($part); $isFirst = false; } continue; } if ($this->isSentenceDelimiter($part)) { $isFirst = true; } } return $parts; }
php
{ "resource": "" }
q261955
APTitleCapitalizer.processLastWordInParts
test
protected function processLastWordInParts(array $parts) { $parts = array_reverse($parts); $length = count($parts); for ($index = 0; $index < $length; $index++) { $part = $parts[$index]; if ($this->isWordLike($part)) { $parts[$index] = $this->processFirstLastWord($part); break; } } return array_reverse($parts); }
php
{ "resource": "" }
q261956
APTitleCapitalizer.processWord
test
protected function processWord($word) { if ($this->isStandardProtectedWord($word)) { return $this->lowercaseWord($word); } if ($this->isCustomProtectedWord($word)) { return $word; } return $this->capitalizeWord($word); }
php
{ "resource": "" }
q261957
APTitleCapitalizer.replacePattern
test
protected function replacePattern($string, $pattern, $replacement) { $replaced = preg_replace($pattern, $replacement, $string); return is_null($replaced) ? $string : $replaced; }
php
{ "resource": "" }
q261958
FullNameParser.get_pro_suffix
test
public function get_pro_suffix($name) { $found_suffix_arr = array(); foreach ($this->dict['suffixes']['prof'] as $suffix) { if (preg_match('/[,\s]+' . preg_quote($suffix) . '\b/i', $name, $matches)) { $found_suffix = trim($matches[0]); $found_suffix = rtrim($found_suffix, ','); $found_suffix = ltrim($found_suffix, ','); $found_suffix_arr[] = trim($found_suffix); } } return $found_suffix_arr; }
php
{ "resource": "" }
q261959
FullNameParser.break_words
test
public function break_words($name) { $temp_word_arr = explode(' ', $name); $final_word_arr = array(); foreach ($temp_word_arr as $key => $word) { if ($word != "" && $word != ",") { $final_word_arr[] = $word; } } return $final_word_arr; }
php
{ "resource": "" }
q261960
FullNameParser.is_salutation
test
protected function is_salutation($word) { $word = str_replace('.', '', mb_strtolower($word)); foreach ($this->dict['prefix'] as $replace => $originals) { if (in_array($word, $originals)) { return $replace; } } return false; }
php
{ "resource": "" }
q261961
FullNameParser.is_line_suffix
test
protected function is_line_suffix($word, $name) { # Ignore periods and righ commas, normalize case $word = str_replace('.', '', mb_strtolower($word)); $word = rtrim($word, ','); # Search the array for our word $line_match = array_search($word, array_map('mb_strtolower', $this->dict['suffixes']['line'])); # Now test our edge cases based on lineage if ($line_match !== false) { # Store our match $matched_case = $this->dict['suffixes']['line'][$line_match]; # Remove it from the array $temp_array = $this->dict['suffixes']['line']; unset($temp_array[$line_match]); # Make sure we're dealing with the suffix and not a surname if ($word == 'senior' || $word == 'junior') { # If name is Joshua Senior, it's pretty likely that Senior is the surname # However, if the name is Joshua Jones Senior, then it's likely a suffix if ($this->mb_str_word_count($name) < 3) { return false; } # If the word Junior or Senior is contained, but so is some other # lineage suffix, then the word is likely a surname and not a suffix foreach ($temp_array as $suffix) { if (preg_match("/\b" . $suffix . "\b/i", $name)) { return false; } } } return $matched_case; } return false; }
php
{ "resource": "" }
q261962
EmojiService.generateEmojiPhpConstants
test
public function generateEmojiPhpConstants() { $data = json_decode(file_get_contents(Wordsmith::$plugin->getBasePath() . '/libs/emoji.json')); $data = array_map( function($entry){ $assumedName = !empty($entry->name) ? $entry->name : (string) Stringy::create($entry->short_name)->humanize()->toUpperCase(); $constantName = (string) Stringy::create($assumedName)->toLowerCase()->replace('&', 'AND')->slugify('_')->toUpperCase(); $char = ''; foreach (explode('-', $entry->unified) as $code) { $char .= '\u{' . $code . '}'; } return [ 'constantName' => $constantName, 'unicode' => $char, ]; }, $data ); $output = ''; foreach ($data as $emoji) { $output .= "\n" . "const {$emoji['constantName']} = \"{$emoji['unicode']}\";"; } return $output; }
php
{ "resource": "" }
q261963
WordsmithService.chop
test
public function chop($s, $limit = 1, $unit = 'p', $append = null, $allowedTags = null) : string { return (new Hacksaw())->chop($s, $limit, $unit, $append, $allowedTags); }
php
{ "resource": "" }
q261964
WordsmithService.emojify
test
public function emojify($s, $name_delimiter=':', $emoticon_delimiter='') : string { return Wordsmith::$plugin->emoji->emojify($s, $name_delimiter, $name_delimiter, $emoticon_delimiter, $emoticon_delimiter); }
php
{ "resource": "" }
q261965
WordsmithService.firstWord
test
public function firstWord($s) { if (empty($s)) { return null; } return (Stringy::create($s)->collapseWhitespace()->split(' ', 2))[0]; }
php
{ "resource": "" }
q261966
WordsmithService.isStringy
test
public function isStringy($thingy) : bool { return ( is_string($thingy) || is_numeric($thingy) || (is_object($thingy) && method_exists($thingy, '__toString' )) ); }
php
{ "resource": "" }
q261967
WordsmithService.lastWord
test
public function lastWord($s) { if (empty($s)) { return null; } $words = Stringy::create($s)->collapseWhitespace()->split(' '); return (string) current(end($words)); }
php
{ "resource": "" }
q261968
WordsmithService.lowerCaseRoman
test
public function lowerCaseRoman($s, $matchMode = 'strict') : string { $result = RomanNumerals::romanNumeralMatchCallback( $s, $matchMode, function (array $matches) { if (empty($matches[1])) { return $matches[1]; } return strtolower($matches[1]); } ); return $result; }
php
{ "resource": "" }
q261969
WordsmithService.markdown
test
public function markdown($s, $flavor = 'gfm', $inlineOnly = false) : string { // If flavor is 'extra' we're looking for Parsedown if ($flavor == 'extra') { if ($inlineOnly) { return (new \ParsedownExtra())->line($s); } else { return (new \ParsedownExtra())->text($s); } } // Otherwise, use Craft's built-in Yii-powered parser $flavor = ($flavor == 'yii-extra' ? 'extra' : $flavor); if ($inlineOnly) { return Markdown::processParagraph($s, $flavor); } else { return Markdown::process($s, $flavor); } }
php
{ "resource": "" }
q261970
WordsmithService.readTime
test
public function readTime($s, $rate = 200, $minimum = 1) { $words = $this->wordcount($s); return max( intval($minimum), floor($words / intval($rate)) ); }
php
{ "resource": "" }
q261971
WordsmithService.smartypants
test
public function smartypants($s, $settings = []) : string { return Wordsmith::$plugin->typography->smartypants($s, $settings); }
php
{ "resource": "" }
q261972
WordsmithService.substringAfterFirst
test
public function substringAfterFirst($s, $separator) { $s = SubStringy::create($s)->substringAfterFirst($separator); return ($s === false ? null : $s); }
php
{ "resource": "" }
q261973
WordsmithService.substringAfterLast
test
public function substringAfterLast($s, $separator) { $s = SubStringy::create($s)->substringAfterLast($separator); return ($s === false ? null : $s); }
php
{ "resource": "" }
q261974
WordsmithService.substringBeforeFirst
test
public function substringBeforeFirst($s, $separator) { $s = SubStringy::create($s)->substringBeforeFirst($separator); return ($s === false ? null : $s); }
php
{ "resource": "" }
q261975
WordsmithService.substringBeforeLast
test
public function substringBeforeLast($s, $separator) { $s = SubStringy::create($s)->substringBeforeLast($separator); return ($s === false ? null : $s); }
php
{ "resource": "" }
q261976
WordsmithService.titleize
test
public function titleize($s, $ignore=[]) : string { return (string) Stringy::create($s)->titleize($ignore); }
php
{ "resource": "" }
q261977
WordsmithService.trim
test
public function trim($s, $chars = null) : string { return (string) Stringy::create($s)->trim($chars); }
php
{ "resource": "" }
q261978
WordsmithService.trimLeft
test
public function trimLeft($s, $chars = null) : string { return (string) Stringy::create($s)->trimLeft($chars); }
php
{ "resource": "" }
q261979
WordsmithService.trimRight
test
public function trimRight($s, $chars = null) : string { return (string) Stringy::create($s)->trimRight($chars); }
php
{ "resource": "" }
q261980
WordsmithService.typogrify
test
public function typogrify($s, $settings = []) : string { return Wordsmith::$plugin->typography->typogrify($s, $settings); }
php
{ "resource": "" }
q261981
WordsmithService.upperCaseRoman
test
public function upperCaseRoman($s, $match_mode = 'strict') : string { $result = RomanNumerals::romanNumeralMatchCallback( $s, $match_mode, function (array $matches) { if (empty($matches[1])) { return $matches[1]; } return strtoupper($matches[1]); } ); return $result; }
php
{ "resource": "" }
q261982
WordsmithService.widont
test
public function widont($s, $settings = []) : string { return Wordsmith::$plugin->typography->widont($s, $settings); }
php
{ "resource": "" }
q261983
Settings.getByName
test
public static function getByName($settingName, $fallback = null) { if (static::$cachedRows === null) { static::cache(); } if (! array_key_exists($settingName, static::$cachedRows)) { return $fallback; } return static::$cachedRows[$settingName]; }
php
{ "resource": "" }
q261984
Extension.getIcon
test
public function getIcon() { if (($icon = $this->getExtensionProperty('icon'))) { if ($file = array_get($icon, 'image')) { $file = $this->path.'/'.$file; if (file_exists($file)) { $mimetype = pathinfo($file, PATHINFO_EXTENSION) === 'svg' ? 'image/svg+xml' : finfo_file(finfo_open(FILEINFO_MIME_TYPE), $file); $data = file_get_contents($file); $icon['backgroundImage'] = 'url(\'data:'.$mimetype.';base64,'.base64_encode($data).'\')'; } } return $icon; } }
php
{ "resource": "" }
q261985
Extension.toArray
test
public function toArray() { return (array) array_merge($this->composerJson, [ 'id' => $this->getId(), 'name' => $this->getName(), 'version' => $this->getVersion(), 'path' => $this->getPath(), 'enabled' => $this->isEnabled(), 'icon' => $this->getIcon(), 'hasAssets' => $this->hasAssets(), 'hasMigrations' => $this->hasMigrations(), ]); }
php
{ "resource": "" }
q261986
BlogController.index
test
public function index(Request $request) { $tag = $request->get('tag'); $data = $this->dispatch(new BlogIndexData($tag)); $layout = $tag ? Tag::layout($tag)->first() : config('blog.tag_layout'); $socialHeaderIconsUser = User::where('id', Settings::socialHeaderIconsUserId())->first(); $css = Settings::customCSS(); $js = Settings::customJS(); return view($layout, $data, compact('css', 'js', 'socialHeaderIconsUser')); }
php
{ "resource": "" }
q261987
BlogController.showPost
test
public function showPost($slug, Request $request) { $post = Post::with('tags')->whereSlug($slug)->firstOrFail(); $socialHeaderIconsUser = User::where('id', Settings::socialHeaderIconsUserId())->first(); $user = User::where('id', $post->user_id)->firstOrFail(); $tag = $request->get('tag'); $title = $post->title; $css = Settings::customCSS(); $js = Settings::customJS(); if ($tag) { $tag = Tag::whereTag($tag)->firstOrFail(); } if (! $post->is_published && ! Auth::guard('canvas')->check()) { return redirect()->route('canvas.blog.post.index'); } return view($post->layout, compact('post', 'tag', 'slug', 'title', 'user', 'css', 'js', 'socialHeaderIconsUser')); }
php
{ "resource": "" }
q261988
TagController.store
test
public function store(TagCreateRequest $request) { $tag = new Tag(); $tag->fill($request->toArray())->save(); $tag->save(); Session::put('_new-tag', trans('canvas::messages.create_success', ['entity' => 'tag'])); return redirect()->route('canvas.admin.tag.index'); }
php
{ "resource": "" }
q261989
TagController.edit
test
public function edit($id) { $tag = Tag::findOrFail($id); $data = ['id' => $id]; foreach (array_keys($this->fields) as $field) { $data[$field] = old($field, $tag->$field); } return view('canvas::backend.tag.edit', compact('data')); }
php
{ "resource": "" }
q261990
TagController.update
test
public function update(TagUpdateRequest $request, $id) { $tag = Tag::findOrFail($id); $tag->fill($request->toArray())->save(); $tag->save(); Session::put('_update-tag', trans('canvas::messages.update_success', ['entity' => 'Tag'])); return redirect()->route('canvas.admin.tag.edit', $id); }
php
{ "resource": "" }
q261991
TagController.destroy
test
public function destroy($id) { $tag = Tag::findOrFail($id); $tag->delete(); Session::put('_delete-tag', trans('canvas::messages.delete_success', ['entity' => 'Tag'])); return redirect()->route('canvas.admin.tag.index'); }
php
{ "resource": "" }
q261992
ToolsController.index
test
public function index() { $data = [ 'status' => App::isDownForMaintenance() ? CanvasHelper::MAINTENANCE_MODE_ENABLED : CanvasHelper::MAINTENANCE_MODE_DISABLED, ]; return view('canvas::backend.tools.index', compact('data')); }
php
{ "resource": "" }
q261993
ToolsController.clearCache
test
public function clearCache() { $exitCode = Artisan::call('cache:clear'); $exitCode = Artisan::call('route:clear'); $exitCode = Artisan::call('optimize'); if ($exitCode === 0) { Session::put('_cache-clear', trans('canvas::messages.cache_clear_success')); } else { Session::put('_cache-clear', trans('canvas::messages.cache_clear_error')); } return redirect()->route('canvas.admin.tools'); }
php
{ "resource": "" }
q261994
ToolsController.handleDownload
test
public function handleDownload() { $this->storeUsers(); $this->storePosts(); $this->storeTags(); $this->storePostTag(); $this->storeMigrations(); $this->storeUploads(); $this->storePasswordResets(); $this->storeSettings(); $date = date('Y-m-d'); $path = storage_path($date.'-canvas-archive'); $filename = sprintf('%s.zip', $path); $zip = new \ZipArchive(); $zip->open($filename, \ZipArchive::CREATE); $files = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($path), \RecursiveIteratorIterator::LEAVES_ONLY ); foreach ($files as $name => $file) { if (! $file->isDir()) { $filePath = $file->getRealPath(); $relativePath = substr($filePath, strlen($path) + 1); $zip->addFile($filePath, $relativePath); } } $zip->close(); \File::deleteDirectory(storage_path($date.'-canvas-archive')); return response()->download(storage_path($date.'-canvas-archive.zip'))->deleteFileAfterSend(true); }
php
{ "resource": "" }
q261995
ToolsController.enableMaintenanceMode
test
public function enableMaintenanceMode() { $exitCode = Artisan::call('down'); if ($exitCode === 0) { Session::put('admin_ip', request()->ip()); Session::put('_enable-maintenance-mode', trans('canvas::messages.enable_maintenance_mode_success')); } else { Session::put('_enable-maintenance-mode', trans('canvas::messages.enable_maintenance_mode_error')); } return redirect()->route('canvas.admin.tools'); }
php
{ "resource": "" }
q261996
ToolsController.disableMaintenanceMode
test
public function disableMaintenanceMode() { $exitCode = Artisan::call('up'); if ($exitCode === 0) { Session::put('_disable-maintenance-mode', trans('canvas::messages.disable_maintenance_mode_success')); } else { Session::put('_disable-maintenance-mode', trans('canvas::messages.disable_maintenance_mode_error')); } return redirect()->route('canvas.admin.tools'); }
php
{ "resource": "" }
q261997
CanvasServiceProvider.handleConfigs
test
private function handleConfigs() { $configPath = __DIR__.'/../config/blog.php'; // Allow publishing the config file, with tag: config $this->publishes([$configPath => config_path('blog.php')], 'config'); // Merge config files... // Allows any modifications from the published config file to be seamlessly merged with default config file $this->mergeConfigFrom($configPath, 'blog'); }
php
{ "resource": "" }
q261998
CanvasServiceProvider.handleTranslations
test
private function handleTranslations() { // Set locale for Carbon Carbon::setLocale(config('app.locale')); // Load translations... $this->loadTranslationsFrom(__DIR__.'/../resources/lang', 'canvas'); // Allow publishing translation files, with tag: translations $this->publishes([ __DIR__.'/../resources/lang' => base_path('resources/lang/vendor/canvas'), ], 'translations'); }
php
{ "resource": "" }
q261999
CanvasServiceProvider.handleViews
test
private function handleViews() { // Load the views... $this->loadViewsFrom(__DIR__.'/../resources/views', 'canvas'); // Allow publishing view files, with tag: views $this->publishes([ __DIR__.'/../resources/views/auth' => base_path('resources/views/vendor/canvas/auth'), __DIR__.'/../resources/views/backend' => base_path('resources/views/vendor/canvas/backend'), __DIR__.'/../resources/views/errors' => base_path('resources/views/vendor/canvas/errors'), __DIR__.'/../resources/views/frontend' => base_path('resources/views/vendor/canvas/frontend'), ], 'views'); }
php
{ "resource": "" }