_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q264100
ResolvedColumnType.buildHeaderView
test
public function buildHeaderView(HeaderView $view, ColumnInterface $column, array $options) { if (null !== $this->parent) { $this->parent->buildHeaderView($view, $column, $options); } $this->innerType->buildHeaderView($view, $column, $options); foreach ($this->typeExtensions as $extension) { $extension->buildHeaderView($view, $column, $options); } }
php
{ "resource": "" }
q264101
ResolvedColumnType.buildCellView
test
public function buildCellView(CellView $view, ColumnInterface $column, array $options) { if (null !== $this->parent) { $this->parent->buildCellView($view, $column, $options); } $this->innerType->buildCellView($view, $column, $options); foreach ($this->typeExtensions as $extension) { $extension->buildCellView($view, $column, $options); } }
php
{ "resource": "" }
q264102
ResolvedColumnType.newColumn
test
protected function newColumn($name, array $options): ColumnInterface { // Special case of CompoundColumnType which requires that child columns // are set afterwards. Whenever you extend this class, make sure to honor this // special use-case. if (null === $this->compound) { $this->compound = $this->isCompound(); } if ($this->compound) { return new CompoundColumn($name, $this, $options); } return new Column($name, $this, $options); }
php
{ "resource": "" }
q264103
ResolvedColumnType.isCompound
test
protected function isCompound(): bool { if ($this->innerType instanceof CompoundColumnType) { return true; } for ($type = $this->parent; null !== $type; $type = $type->getParent()) { if ($type->getInnerType() instanceof CompoundColumnType) { return true; } } return false; }
php
{ "resource": "" }
q264104
AbstractRequest.getBaseData
test
protected function getBaseData() { $data = array(); $data['GatewayUserName'] = $this->getUsername(); $data['GatewayPassword'] = $this->getPassword(); $data['PaymentType'] = $this->paymentType; if (isset($this->transactionType)) { $data['TransactionType'] = $this->transactionType; } if (isset($this->safeAction)) { $data['SAFE_Action'] = $this->safeAction; } return $data; }
php
{ "resource": "" }
q264105
AbstractRequest.getShippingData
test
protected function getShippingData() { $data = array(); // Customer shipping details if ($card = $this->getCard()) { // Customer shipping details if ($card->getShippingFirstName()) { $data['ShippingFirstName'] = $card->getShippingFirstName(); } if ($card->getShippingLastName()) { $data['ShippingLastName'] = $card->getShippingLastName(); } if ($card->getShippingCompany()) { $data['ShippingCompany'] = $card->getShippingCompany(); } if ($card->getShippingAddress1()) { $data['ShippingAddress1'] = $card->getShippingAddress1(); } if ($card->getShippingAddress2()) { $data['ShippingAddress2'] = $card->getShippingAddress2(); } if ($card->getShippingCity()) { $data['ShippingCity'] = $card->getShippingCity(); } if ($card->getShippingState()) { $data['ShippingState'] = $card->getShippingState(); } if ($card->getShippingPostcode()) { $data['ShippingZip'] = $card->getShippingPostcode(); } if ($card->getShippingCountry()) { $data['ShippingCountry'] = $card->getShippingCountry(); } } return $data; }
php
{ "resource": "" }
q264106
AbstractRequest.getInvoiceData
test
protected function getInvoiceData() { $data = array(); $data['Amount'] = $this->getAmount(); if ($this->getDescription()) { $data['OrderDescription'] = $this->getDescription(); } return $data; }
php
{ "resource": "" }
q264107
AbstractRequest.sendData
test
public function sendData($data) { $xml = $this->buildRequest($data); $headers = array( 'content-type' => 'text/xml; charset=utf-8', 'SOAPAction' => 'https://gateway.agms.com/roxapi/ProcessTransaction' ); $httpResponse = $this->httpClient->post($this->getEndpoint(), $headers, $xml)->send(); return $this->response = new Response($this, $httpResponse->getBody()); }
php
{ "resource": "" }
q264108
StringUtil.trim
test
public static function trim(string $string): string { if (null !== $result = @preg_replace('/^[\pZ\p{Cc}]+|[\pZ\p{Cc}]+$/u', '', $string)) { return $result; } return trim($string); }
php
{ "resource": "" }
q264109
StringUtil.fqcnToBlockPrefix
test
public static function fqcnToBlockPrefix(string $fqcn): string { // Non-greedy ("+?") to match "type" suffix, if present if (preg_match('~([^\\\\]+?)(type)?$~i', $fqcn, $matches)) { return strtolower( preg_replace(['/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'], ['\\1_\\2', '\\1_\\2'], $matches[1]) ); } }
php
{ "resource": "" }
q264110
MoneyToLocalizedStringTransformer.transform
test
public function transform($value) { if (null === $value) { return ''; } if (is_array($value)) { return $this->doTransformation($value['currency'] ?: $this->defaultCurrency, (string) $value['amount']); } // Convert fixed spaces to normal ones. $value = str_replace("\xc2\xa0", ' ', (string) $value); if (false !== strpos($value, ' ')) { return $this->transformStringWithCurrencyToLocalized($value); } return $this->doTransformation($this->defaultCurrency, $value); }
php
{ "resource": "" }
q264111
XmlArray.parseValue
test
protected function parseValue($value) { if (is_numeric($value)) { return strpos($value, '.') !== false ? (float) $value : (int) $value; } elseif ($value === 'true' || $value === '1') { return true; } elseif ($value === 'false' || $value === '0') { return false; } else { return $value; } }
php
{ "resource": "" }
q264112
CompoundColumnBuilder.add
test
public function add(string $name, string $type = null, array $options = []): CompoundColumnBuilderInterface { $this->unresolvedColumns[$name] = [ 'type' => $type, 'options' => $options, ]; return $this; }
php
{ "resource": "" }
q264113
File.isValidUpload
test
protected function isValidUpload() { $error = $this->error ?: UPLOAD_ERR_NO_FILE; switch ($error) { case UPLOAD_ERR_OK: return $this->isUploadedFile(); break; case UPLOAD_ERR_INI_SIZE: throw new \RuntimeException('The uploaded file exceeds the upload_max_filesize directive in php.ini'); break; case UPLOAD_ERR_FORM_SIZE: throw new \RuntimeException('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'); break; case UPLOAD_ERR_PARTIAL: throw new \RuntimeException('The uploaded file was only partially uploaded'); break; case UPLOAD_ERR_NO_FILE: throw new \RuntimeException('No file was uploaded'); break; case UPLOAD_ERR_NO_TMP_DIR: throw new \RuntimeException('Missing a temporary folder'); break; case UPLOAD_ERR_CANT_WRITE: throw new \RuntimeException('Failed to write file to disk'); break; case UPLOAD_ERR_EXTENSION: throw new \RuntimeException('A PHP extension stopped the file upload'); break; default: throw new \RuntimeException('Invalid error code'); break; } }
php
{ "resource": "" }
q264114
AssetHelper.resolve
test
public static function resolve(string $filename, string $basePath = ''): string { if (strpos($filename, '://')) { //Absolute path return $filename; } $localFilename = directory('public') . $filename; //Add query parameter to uniquely identify file version if (is_file($localFilename) && file_exists($localFilename)) { $filename .= '?' . hash('crc32', filemtime($localFilename)); } return str_replace('//', '/', $basePath . $filename); }
php
{ "resource": "" }
q264115
EditLockControllerExtension.updateForm
test
public function updateForm($form, $record) { if (!$record) { return; } // if the current user can't edit the record anyway, we don't need to do anything if ($record && !$record->canEdit()) { return $form; } // check if all classes should be locked by default or a certain list $lockedClasses = Config::inst()->get('EditLockControllerExtension', 'lockedClasses'); if (!empty($lockedClasses)) { if (!in_array($record->ClassName, $lockedClasses)) { return $form; } } // check if this record is being edited by another user $beingEdited = RecordBeingEdited::get()->filter(array( 'RecordID' => $record->ID, 'RecordClass' => $record->ClassName, 'EditorID:not' => Member::currentUserID() ))->first(); if ($beingEdited) { if ($this->owner->getRequest()->getVar('editanyway') == '1') { $beingEdited->isEditingAnyway(); return Controller::curr()->redirectBack(); } // if the RecordBeingEdited record has not been updated in the last 15 seconds (via ping) // the person editing it must have left the edit form, so delete the RecordBeingEdited if (strtotime($beingEdited->LastEdited) < (time() - 15)) { $beingEdited->delete(); // otherwise, there must be someone currently editing this record, so make the form readonly // unless they have permission to, and have chosen to edit anyway } else { if (!$beingEdited->isEditingAnyway()) { $readonlyFields = $form->Fields()->makeReadonly(); $form->setFields($readonlyFields); $form->addExtraClass('edit-locked'); $form->setAttribute('data-lockedmessage', $beingEdited->getLockedMessage()); return; } } } $form->setAttribute('data-recordclass', $record->ClassName); $form->setAttribute('data-recordid', $record->ID); $form->setAttribute('data-lockurl', $this->owner->link('lock')); return $form; }
php
{ "resource": "" }
q264116
EditLockControllerExtension.updateEditForm
test
public function updateEditForm($form) { if ($record = $form->getRecord()) { $form = $this->updateForm($form, $record); } }
php
{ "resource": "" }
q264117
EditLockControllerExtension.updateItemEditForm
test
public function updateItemEditForm($form) { if ($record = $form->getRecord()) { $form = $this->updateForm($form, $record); } }
php
{ "resource": "" }
q264118
EditLockControllerExtension.lock
test
public function lock($request) { $id = (int)$request->postVar('RecordID'); $class = $request->postVar('RecordClass'); $existing = RecordBeingEdited::get()->filter(array( 'RecordID' => $id, 'RecordClass' => $class, 'EditorID' => Member::currentUserID() ))->first(); if ($existing) { $existing->write(false, false, true); } else { $lock = RecordBeingEdited::create(array( 'RecordID' => $id, 'RecordClass' => $class, 'EditorID' => Member::currentUserID() )); $lock->write(); } }
php
{ "resource": "" }
q264119
PubControl.apply_config
test
public function apply_config($config) { if (!is_array(reset($config))) $config = array($config); foreach ($config as $entry) { $pub = new PubControlClient($entry['uri']); if (array_key_exists('iss', $entry)) $pub->set_auth_jwt(array('iss' => $entry['iss']), $entry['key']); $this->clients[] = $pub; } }
php
{ "resource": "" }
q264120
PubControl.publish
test
public function publish($channel, $item) { foreach ($this->clients as $client) $client->publish($channel, $item); }
php
{ "resource": "" }
q264121
TranslateLoader.load
test
public function load($locale): array { // if file not exists if (!\file_exists($this->getFilePath($locale))) { // if local support build in get translate from package. if ($this->isSupportLocal($locale)) { return include $this->getFilePath($locale, true); } return []; } return include $this->getFilePath($locale); }
php
{ "resource": "" }
q264122
Client.send
test
public function send(RequestInterface $request) { $this->request = $request; if ($this->httpClient instanceof ClientInterface || method_exists($this->httpClient, 'send')) { $this->response = $this->httpClient->send($request); } else { throw new \RuntimeException('HTTP Client must implement method send, and return ResponseInterface'); } return $this->response; }
php
{ "resource": "" }
q264123
Uri.buildFromParts
test
private function buildFromParts(array $parts) { $this->withScheme(isset($parts['scheme']) ? $parts['scheme'] : '') ->withUserInfo( isset($parts['user']) ? $parts['user'] : '', isset($parts['pass']) ? ':'.$parts['pass'] : null ) ->withHost(isset($parts['host']) ? $parts['host'] : '') ->withPort(!empty($parts['port']) ? $parts['port'] : null) ->withPath(isset($parts['path']) ? $parts['path'] : '') ->withQuery(isset($parts['query']) ? $parts['query'] : '') ->withFragment(isset($parts['fragment']) ? $parts['fragment'] : ''); }
php
{ "resource": "" }
q264124
UserController.store
test
public function store(CreateUserRequest $request) { $input = $request->all(); $user = $this->userRepository->create($input); Flash::success(trans('l5starter::messages.create.success')); return redirect(route('admin.users.index')); }
php
{ "resource": "" }
q264125
UserController.edit
test
public function edit($id) { $user = $this->userRepository->findWithoutFail($id); if (empty($user)) { Flash::error(trans('l5starter::messages.404_not_found')); return redirect(route('admin.users.index')); } return view('l5starter::admin.users.edit')->with('user', $user); }
php
{ "resource": "" }
q264126
UserController.update
test
public function update($id, UpdateUserRequest $request) { $user = $this->userRepository->findWithoutFail($id); if (empty($user)) { Flash::error(trans('l5starter::messages.404_not_found')); return redirect(route('admin.users.index')); } $user = $this->userRepository->update($request->all(), $id); Flash::success(trans('l5starter::messages.update.success')); return redirect(route('admin.users.index')); }
php
{ "resource": "" }
q264127
UserController.destroy
test
public function destroy($id) { $user = $this->userRepository->findWithoutFail($id); if (empty($user)) { Flash::error(trans('l5starter::messages.404_not_found')); return redirect(route('admin.users.index')); } $this->userRepository->delete($id); Flash::success(trans('l5starter::messages.delete.success')); return redirect(route('admin.users.index')); }
php
{ "resource": "" }
q264128
MpdfService.createMpdfInstance
test
public function createMpdfInstance( $format = 'A4', $fontSize = 0, $fontFamily = '', $marginLeft = 15, $marginRight = 15, $marginTop = 16, $marginBottom = 16, $marginHeader = 9, $marginFooter = 9, $orientation = 'P' ) { if (!(is_array($format) && count($format) == 2) || !in_array(strtoupper($format), $this->getAcceptedFormats())) { $format = 'A4'; } $constructorArgs = array( 'utf-8', $this->validateFormat($format), (int)$fontSize, $fontFamily, (int)$marginLeft, (int)$marginRight, (int)$marginTop, (int)$marginBottom, (int)$marginHeader, (int)$marginFooter, $this->validateOrientation($orientation)); $reflection = new \ReflectionClass('\mPDF'); $this->mpdf = $reflection->newInstanceArgs($constructorArgs); }
php
{ "resource": "" }
q264129
Request.addHostHeader
test
protected function addHostHeader(UriInterface $uri) { $host = $uri->getHost(); if ($port = $uri->getPort()) { $host = sprintf('%s:%s', $host, $port); } $this->headers['host'] = array($host); }
php
{ "resource": "" }
q264130
RequestBuilder.buildGuzzleRequest
test
public function buildGuzzleRequest(RequestInterface $request) { $this->addCallable(function () use ($request) { return $this->buildForVersionThree($request); }); $this->addCallable(function () use ($request) { return $this->buildForVersionFourOrFive($request); }); $this->addCallable(function () use ($request) { return $this->buildForVersionSix($request); }); $guzzleRequest = $this->executeCallableChain(); if (null === $guzzleRequest) { throw new RequestException('Unknown Guzzle client, request instance can not be created.'); } return $guzzleRequest; }
php
{ "resource": "" }
q264131
RequestBuilder.executeCallableChain
test
protected function executeCallableChain() { $callableResult = null; foreach ($this->callableChain as $callable) { $callableResult = call_user_func($callable); if (null !== $callableResult) { break; } } return $callableResult; }
php
{ "resource": "" }
q264132
GuzzleClient.checkClassExists
test
protected function checkClassExists($className, $throwException = true) { if (class_exists($className)) { return true; } if ($throwException) { throw new \BadMethodCallException( sprintf('%s not found. Please check your dependencies in composer.json', $className) ); } return false; }
php
{ "resource": "" }
q264133
ThreadSafeClient.run
test
public function run() { $quit = false; while (!$quit) { \Mutex::lock($this->thread_mutex); if (count($this->req_queue) == 0) { \Cond::wait($this->thread_cond, $this->thread_mutex); if (count($this->req_queue) == 0) { \Mutex::unlock($this->thread_mutex); continue; } } $reqs = array(); while (count($this->req_queue) > 0 and count($reqs) < 10) { $m = $this->req_queue->shift(); if ($m[0] == 'stop') { $quit = true; break; } $reqs[] = array($m[1], $m[2], $m[3], $m[4]); } \Mutex::unlock($this->thread_mutex); if (count($reqs) > 0) $this->pubbatch($reqs); } }
php
{ "resource": "" }
q264134
ThreadSafeClient.ensure_thread
test
public function ensure_thread() { if (!$this->is_thread_running) { $this->is_thread_running = true; $this->thread_cond = \Cond::create(); $this->thread_mutex = \Mutex::create(); $this->start(); } }
php
{ "resource": "" }
q264135
ThreadSafeClient.queue_req
test
public function queue_req($req) { \Mutex::lock($this->thread_mutex); $this->req_queue[] = $req; \Cond::signal($this->thread_cond); \Mutex::unlock($this->thread_mutex); }
php
{ "resource": "" }
q264136
ThreadSafeClient.pubbatch
test
public function pubbatch($reqs) { if (count($reqs) == 0) throw new \RuntimeException('reqs length == 0'); $uri = $reqs[0][0]; $auth_header = $reqs[0][1]; $items = array(); $callbacks = array(); foreach ($reqs as $req) { $items[] = $req[2]; $callbacks[] = $req[3]; } $result = null; try { $this->pcc_utilities->pubcall($uri, $auth_header, $items); $result = array(true, ''); } catch (\RuntimeException $exception) { $result = array(false, $exception->getMessage()); } foreach ($callbacks as $callback) if (!is_null($callback)) { call_user_func($callback, $result[0], $result[1]); } }
php
{ "resource": "" }
q264137
ArrayAccessIterator.getKey
test
public function getKey( $cursor ) { $this->calculateKeyMap(); if( !array_key_exists( $cursor, $this->keyMap ) ) { return null; } return $this->keyMap[ $cursor ]; }
php
{ "resource": "" }
q264138
ArrayAccessIterator.rewind
test
public function rewind() { $this->cursor = 0; $data = $this->collection->getArrayCopy(); reset( $data ); $this->collection->exchangeArray( $data ); return $this->current(); }
php
{ "resource": "" }
q264139
Item.export
test
public function export() { $format_types = array(); foreach ($this->formats as $format) { $format_class_name = get_class($format); if (in_array($format_class_name, $format_types)) throw new \RuntimeException('Multiple ' . $format_class_name . ' format classes specified'); array_push($format_types, $format_class_name); } $out = array(); if (!is_null($this->id)) $out['id'] = $this->id; if (!is_null($this->prev_id)) $out['prev-id'] = $this->prev_id; foreach ($this->formats as $format) $out[$format->name()] = $format->export(); return $out; }
php
{ "resource": "" }
q264140
AbstractOptionTrait.setFromArray
test
public function setFromArray($options) { if ($options instanceof self) { $options = $options->toArray(); } if (!is_array($options) && !$options instanceof Traversable) { throw new InvalidArgumentException(sprintf( 'Parameter provided to %s must be an %s, %s or %s', __METHOD__, 'array', 'Traversable', 'Zend\Stdlib\AbstractOptions' )); } foreach ($options as $key => $value) { $this->__set($key, $value); } return $this; }
php
{ "resource": "" }
q264141
PccUtilities.pubcall
test
public function pubcall($uri, $auth_header, $items) { $uri .= '/publish/'; $content = array(); $content['items'] = $items; $headers = array('Content-Type: application/json'); if (!is_null($auth_header)) $headers[] = 'Authorization: ' . $auth_header; $results = $this->make_http_request($uri, $headers, $content); $this->verify_http_status_code($results[0], $results[1]); }
php
{ "resource": "" }
q264142
PccUtilities.make_http_request
test
public function make_http_request($uri, $headers, $content) { $post = curl_init($uri); curl_setopt_array($post, array( CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => $headers, CURLOPT_POSTFIELDS => json_encode($content) )); $response = curl_exec($post); if (curl_error($post) != '') throw new \RuntimeException('Failed to publish: ' . curl_error($post)); return array($response, intval(curl_getinfo($post, CURLINFO_HTTP_CODE))); }
php
{ "resource": "" }
q264143
PubControlClient.publish
test
public function publish($channel, $item) { $export = $item->export(); $export['channel'] = $channel; $uri = null; $auth = null; $uri = $this->uri; $auth = $this->pcc_utilities->gen_auth_header($this->auth_jwt_claim, $this->auth_jwt_key, $this->auth_basic_user, $this->auth_basic_pass); $this->pcc_utilities->pubcall($uri, $auth, array($export)); }
php
{ "resource": "" }
q264144
AbstractHttpAdapter.importHeaders
test
public function importHeaders(MessageInterface $from, $to) { foreach ($from->getHeaders() as $key => $headers) { foreach ($headers as $header) { $to->addHeader($key, $from->getHeaderLine($key)); } } }
php
{ "resource": "" }
q264145
AbstractHttpAdapter.getProtocolVersion
test
public function getProtocolVersion() { if ($this->protocolVersion) { return $this->protocolVersion; } $protocolAndVersion = $_SERVER['SERVER_PROTOCOL']; list($protocol, $version) = explode('/', $protocolAndVersion); return $version; }
php
{ "resource": "" }
q264146
HasValidator.valid
test
protected function valid(array $data, array $rules, array $messages = [], array $aliases = []) { // load translate. $this->loadTranslate(); $this->validation = $this->getValidator()->make($data, $rules, $messages); if (\count($aliases) > 0) { $this->setAliases($aliases); } $this->validation->setAliases($this->getAliases()); $this->validation->validate(); // if has custom invalid callback. if (\method_exists($this, 'InValidCallback') && $this->getValidation()->fails()) { return $this->InValidCallback($this->getValidation()->errors()->firstOfAll()); } return !$this->getValidation()->fails(); }
php
{ "resource": "" }
q264147
HasValidator.loadTranslate
test
protected function loadTranslate(): self { $this->getValidator()->setMessages($this->getTranslateLoader()->load($this->getValidatorLocal())); return $this; }
php
{ "resource": "" }
q264148
HasValidator.setValidatorLocal
test
public function setValidatorLocal($local, $path = null): self { $this->validatorLocal = $local; if (!empty($path)) { $this->getTranslateLoader()->setPath($path); } return $this; }
php
{ "resource": "" }
q264149
HasValidator.getValidErrors
test
protected function getValidErrors($firstOfAll = false) { return $firstOfAll ? $this->getValidation()->errors()->firstOfAll() : $this->getValidation()->errors(); }
php
{ "resource": "" }
q264150
PubControlClientCallbackHandler.update
test
public function update($num_calls, $callback) { $this->completed = false; $this->num_calls = $num_calls; $this->callback = $callback; $this->success = true; }
php
{ "resource": "" }
q264151
RecordBeingEdited.getLockedMessage
test
public function getLockedMessage() { $editor = $this->Editor(); $editorString = $editor->getTitle(); if ($editor->Email) { $editorString .= " &lt;<a href='mailto:$editor->Email'>$editor->Email</a>&gt;"; } $message = sprintf( _t('RecordBeingEdited.LOCKEDMESSAGE', 'Sorry, this %s is currently being edited by %s. To avoid conflicts and data loss, editing will be locked until they are finished.'), FormField::name_to_label($this->RecordClass), $editorString ); if ($this->canEditAnyway()) { $editAnywayLink = Controller::join_links(Controller::curr()->getRequest()->requestVar('url'), '?editanyway=1'); $message .= "<span style='float:right'>"; $message .= sprintf(_t('RecordBeingEdited.EDITANYWAY', 'I understand the risks, %s edit anyway %s'), "<a href='$editAnywayLink'>", "</a>"); $message .= "</span>"; } return $message; }
php
{ "resource": "" }
q264152
RecordBeingEdited.isEditingAnyway
test
public function isEditingAnyway() { if (!$this->canEditAnyway()) { return false; } $sessionVar = 'EditAnyway_' . Member::currentUserID() . '_' . $this->ID; if (Controller::curr()->getRequest()->getVar('editanyway') == '1') { Session::set($sessionVar, true); return true; } return Session::get($sessionVar) ? true : false; }
php
{ "resource": "" }
q264153
ArrayAccess.offsetExists
test
public function offsetExists( $offset ) { // Can not retrieve a key based on a value other than a string, integer or boolean if( !is_string( $offset ) && !is_int( $offset ) && !is_bool( $offset ) ) { return false; } return array_key_exists( $offset, $this->data ); }
php
{ "resource": "" }
q264154
ArrayAccess.usort
test
public function usort( \Closure $callback ) { usort( $this->data, $callback ); reset( $this->data ); return $this; }
php
{ "resource": "" }
q264155
Birthday.parse
test
protected function parse(): void { list('year' => $year, 'month' => $month, 'day' => $day) = self::validate($this->birthday); $this->birthday = sprintf('%d-%02d-%02d', $year, $month, $day); // normalize the date $this->age = self::calculateAge($year, $month, $day); $this->constellation = self::parseConstellation($month, $day); }
php
{ "resource": "" }
q264156
Birthday.format
test
public function format($format = null): string { if (empty($format)) { return $this->birthday; } return date($format, strtotime($this->birthday)); }
php
{ "resource": "" }
q264157
Birthday.validate
test
public static function validate($birthday): array { $date = strtotime($birthday); if ($date === false) { throw new \InvalidArgumentException("Invalid birthday: $birthday"); } $year = date('Y', $date); $month = date('n', $date); $day = date('j', $date); $currentYear = date('Y'); if ($year > $currentYear || $year <= $currentYear - self::MAX_AGE) { throw new \OutOfRangeException('The age is out of range [0, 200)'); } return ['year' => $year, 'month' => $month, 'day' => $day]; }
php
{ "resource": "" }
q264158
Birthday.parseConstellation
test
public static function parseConstellation($month, $day): string { switch ($month) { case 1: return $day >= 20 ? 'Aquarius' : 'Capricorn'; case 2: return $day >= 19 ? 'Pisces' : 'Aquarius'; case 3: return $day >= 21 ? 'Aries' : 'Pisces'; case 4: return $day >= 20 ? 'Taurus' : 'Aries'; case 5: return $day >= 21 ? 'Gemini' : 'Taurus'; case 6: return $day >= 22 ? 'Cancer' : 'Gemini'; case 7: return $day >= 23 ? 'Leo' : 'Cancer'; case 8: return $day >= 23 ? 'Virgo' : 'Leo'; case 9: return $day >= 23 ? 'Libra' : 'Virgo'; case 10: return $day >= 24 ? 'Scorpio' : 'Libra'; case 11: return $day >= 23 ? 'Sagittarius' : 'Scorpio'; case 12: return $day >= 22 ? 'Capricorn' : 'Sagittarius'; } throw new \InvalidArgumentException("Invalid month and day: $month , $day"); }
php
{ "resource": "" }
q264159
Birthday.translate
test
protected function translate($constellation, $lang = 'en'): string { $arr = $this->loadTranslation($lang); return isset($arr[$constellation]) ? $arr[$constellation] : ''; }
php
{ "resource": "" }
q264160
AuthorizationController.updateSucceed
test
public function updateSucceed() { $this->synchronizer->handle(); app('antares.memory')->make('component.default')->update(); $message = trans('antares/acl::response.acls.update'); return (app('request')->ajax()) ? Response::json(['message' => $message], 200) : $this->redirectWithMessage(handles("antares::acl/index/roles"), $message); }
php
{ "resource": "" }
q264161
AuthorizationController.syncSucceed
test
public function syncSucceed(Fluent $acl) { $message = trans('antares/acl::response.acls.sync-roles', [ 'name' => $acl->get('name'), ]); return $this->redirectWithMessage(handles("antares::acl/acl?name={$acl->get('name')}"), $message); }
php
{ "resource": "" }
q264162
Breadcrumb.onList
test
public function onList() { $this->onInit(); Breadcrumbs::register('roles-list', function($breadcrumbs) { $breadcrumbs->parent('staff'); $breadcrumbs->push(trans('antares/acl::title.breadcrumbs.groups'), handles('antares::acl/index/roles')); }); view()->share('breadcrumbs', Breadcrumbs::render('roles-list')); }
php
{ "resource": "" }
q264163
Breadcrumb.onRoleCreateOrEdit
test
public function onRoleCreateOrEdit(Model $model = null) { $this->onList(); Breadcrumbs::register('edit-role', function($breadcrumbs) use($model) { $breadcrumbs->parent('roles-list'); $exists = is_null($model) ? false : $model->exists; $name = ($exists) ? 'Edit Group ' . $model->full_name : 'Add Group'; $breadcrumbs->push($name, '#'); }); view()->share('breadcrumbs', Breadcrumbs::render('edit-role')); }
php
{ "resource": "" }
q264164
Breadcrumb.onUserCreateOrEdit
test
public function onUserCreateOrEdit(Model $model) { $this->onUsersList(); $name = $model->exists ? 'User Edit ' . $model->fullname : 'User Add'; Breadcrumbs::register('user', function($breadcrumbs) use($name) { $breadcrumbs->parent('users-list'); $breadcrumbs->push($name, '#'); }); view()->share('breadcrumbs', Breadcrumbs::render('user')); }
php
{ "resource": "" }
q264165
Breadcrumb.onAreaCreate
test
public function onAreaCreate() { $this->onAreasList(); Breadcrumbs::register('area-create', function($breadcrumbs) { $breadcrumbs->parent('areas-list'); $breadcrumbs->push(trans('antares/acl::messages.area_add'), '#'); }); view()->share('breadcrumbs', Breadcrumbs::render('area-create')); }
php
{ "resource": "" }
q264166
User.form
test
public function form($model) { $this->breadcrumb->onUserCreateOrEdit($model); return $this->form->of('antares.users', function (FormGrid $form) use ($model) { $form->name('user.form'); $form->resource($this, 'antares::acl/index/users', $model); $form->hidden('id'); $form->fieldset('User fields', function (Fieldset $fieldset) use($model) { $fieldset->control('input:text', 'email') ->label(trans('antares/foundation::label.users.email')); $fieldset->control('input:text', 'firstname') ->label(trans('antares/foundation::label.users.firstname')); $fieldset->control('input:text', 'lastname') ->label(trans('antares/foundation::label.users.lastname')); $fieldset->control('input:password', 'password') ->label(trans('antares/foundation::label.users.password')); if ($model->id != user()->id) { $status = $fieldset->control('input:checkbox', 'status') ->label(trans('antares/foundation::label.users.active')) ->value(1); if ($model->status) { $status->checked(); } } $fieldset->control('select', 'roles[]') ->label(trans('antares/foundation::label.users.roles')) ->options(function () { $roles = app('antares.role'); if (config('antares/acl::allow_register_with_other_roles')) { return $roles->managers()->pluck('name', 'id'); } else { return user()->roles->pluck('name', 'id'); } }) ->value(function ($row) { $roles = []; foreach ($row->roles as $row) { $roles[] = $row->id; } return $roles; }); $fieldset->control('button', 'button') ->attributes(['type' => 'submit', 'class' => 'btn btn--md btn--primary mdl-button mdl-js-button mdl-js-ripple-effect']) ->value(trans('antares/foundation::label.save_changes')); $fieldset->control('button', 'cancel') ->field(function() { return app('html')->link(handles("antares::acl/index/users"), trans('antares/foundation::label.cancel'), ['class' => 'btn btn--md btn--default mdl-button mdl-js-button']); }); }); $form->rules([ 'email' => ['required', 'email', 'unique:tbl_users,email' . ((!$model->exists) ? '' : ',' . $model->id)], 'firstname' => ['required'], 'lastname' => ['required'], 'roles' => ['required'], ]); }); }
php
{ "resource": "" }
q264167
GroupsBreadcrumbMenu.handle
test
public function handle() { $acl = app('antares.acl')->make('antares/acl'); $canCreateRole = $acl->can('create-role'); if (!$canCreateRole) { return; } $this->createMenu(); if ($canCreateRole) { $this->handler ->add('role-add', '^:roles') ->title('Add Group') ->icon('zmdi-plus-circle-o') ->link(handles('antares::acl/index/roles/create')); } }
php
{ "resource": "" }
q264168
RepositoryTrait.findOneByOrGetNew
test
public function findOneByOrGetNew(array $criteria) { $object = $this->findOneBy($criteria); if ($object === null) { $object = $this->getNew(); } return $object; }
php
{ "resource": "" }
q264169
RepositoryTrait.getNew
test
public function getNew() { $object = \call_user_func($this->getObjectFactory()); if (!$this->canBeManaged($object)) { throw new \RuntimeException( \sprintf( 'Object factory must return an instance of %s. "%s" returned', $this->getClassName(), \is_object($object) ? \get_class($object) : \gettype($object) ) ); } return $object; }
php
{ "resource": "" }
q264170
RepositoryTrait.getObjectFactory
test
private function getObjectFactory(): callable { if ($this->objectFactory === null) { $className = $this->getClassName(); $this->objectFactory = function () use ($className) { return new $className(); }; } return $this->objectFactory; }
php
{ "resource": "" }
q264171
RepositoryTrait.removeBy
test
public function removeBy(array $criteria, bool $flush = false) { $this->runManagerAction('remove', $this->findBy($criteria), $flush); }
php
{ "resource": "" }
q264172
RepositoryTrait.removeOneBy
test
public function removeOneBy(array $criteria, bool $flush = false) { $this->runManagerAction('remove', $this->findOneBy($criteria), $flush); }
php
{ "resource": "" }
q264173
RepositoryTrait.remove
test
public function remove($objects, bool $flush = false) { if (!\is_object($objects) && !is_iterable($objects)) { $objects = $this->find($objects); } $this->runManagerAction('remove', $objects, $flush); }
php
{ "resource": "" }
q264174
RepositoryTrait.refresh
test
public function refresh($objects) { $backupAutoFlush = $this->autoFlush; $this->autoFlush = false; $this->runManagerAction('refresh', $objects, false); $this->autoFlush = $backupAutoFlush; }
php
{ "resource": "" }
q264175
RepositoryTrait.detach
test
public function detach($objects) { $backupAutoFlush = $this->autoFlush; $this->autoFlush = false; $this->runManagerAction('detach', $objects, false); $this->autoFlush = $backupAutoFlush; }
php
{ "resource": "" }
q264176
RepositoryTrait.getSupportedMethod
test
private function getSupportedMethod(string $method): string { foreach (static::$supportedMethods as $supportedMethod) { if (\strpos($method, $supportedMethod) === 0) { return $supportedMethod; } } throw new \BadMethodCallException(\sprintf( 'Undefined method "%s". Method call must start with one of "%s"!', $method, \implode('", "', static::$supportedMethods) )); }
php
{ "resource": "" }
q264177
RepositoryTrait.callSupportedMethod
test
protected function callSupportedMethod(string $method, string $fieldName, array $arguments) { $classMetadata = $this->getClassMetadata(); if (!$classMetadata->hasField($fieldName) && !$classMetadata->hasAssociation($fieldName)) { throw new \BadMethodCallException(\sprintf( 'Invalid call to %s::%s. Field "%s" does not exist', $this->getClassName(), $method, $fieldName )); } // @codeCoverageIgnoreStart $parameters = \array_merge( [$fieldName => $arguments[0]], \array_slice($arguments, 1) ); return \call_user_func_array([$this, $method], $parameters); // @codeCoverageIgnoreEnd }
php
{ "resource": "" }
q264178
RepositoryTrait.runManagerAction
test
protected function runManagerAction(string $action, $objects, bool $flush) { $manager = $this->getManager(); if (!is_iterable($objects)) { $objects = \array_filter([$objects]); } foreach ($objects as $object) { if (!$this->canBeManaged($object)) { throw new \InvalidArgumentException( \sprintf( 'Managed object must be a %s. "%s" given', $this->getClassName(), \is_object($object) ? \get_class($object) : \gettype($object) ) ); } $manager->$action($object); } // @codeCoverageIgnoreStart if ($objects instanceof \Traversable) { $objects = \iterator_to_array($objects); } // @codeCoverageIgnoreEnd $this->flushObjects($objects, $flush); }
php
{ "resource": "" }
q264179
RepositoryTrait.flushObjects
test
protected function flushObjects(array $objects, bool $flush) { if ($flush || $this->autoFlush) { $this->getManager()->flush($objects); } }
php
{ "resource": "" }
q264180
Collection.prepareTagFromBits
test
protected function prepareTagFromBits($additional_identifier, $visitor_identifier, $hash) { return implode(',', [$this->getApplicationIdentifier(), 'collection', get_class($this), $additional_identifier, $visitor_identifier, $hash]); }
php
{ "resource": "" }
q264181
Collection.&
test
public function &pagination($current_page = 1, $items_per_page = 100) { $this->is_paginated = true; $this->currentPage($current_page); $this->items_per_page = (int) $items_per_page; if ($this->items_per_page < 1) { $this->items_per_page = 100; } return $this; }
php
{ "resource": "" }
q264182
Collection.&
test
public function &currentPage($value) { if (!$this->is_paginated) { throw new LogicException('Page can be set only for paginated collections'); } $this->current_page = (int) $value; if ($this->current_page < 1) { $this->current_page = 1; } return $this; }
php
{ "resource": "" }
q264183
PermissionController.update
test
public function update(PermissionRequest $request, $id) { $this->authorize('edit_permission'); $permission = Permissions::where('id', $id)->firstOrFail(); $permission->update($request->all()); $request->session()->flash('message', 'Permission Updated Successfully'); return redirect()->route('RoleManager::permission.edit', $permission->id); }
php
{ "resource": "" }
q264184
PaginatorTrait.getPaginator
test
protected function getPaginator(AdapterInterface $adapter, int $itemsPerPage): Paginator { $paginator = new Paginator($adapter); $paginator->setItemCountPerPage(max(-1, $itemsPerPage)); return $paginator; }
php
{ "resource": "" }
q264185
PaginatorTrait.findPaginatedByOrFail
test
public function findPaginatedByOrFail(array $criteria, array $orderBy = null, int $itemsPerPage = 10): Paginator { $paginator = $this->findPaginatedBy($criteria, $orderBy, $itemsPerPage); if ($paginator->count() === 0) { throw new FindException('FindPaginatedBy did not return any results'); } return $paginator; }
php
{ "resource": "" }
q264186
AclServiceProvider.bootExtensionComponents
test
protected function bootExtensionComponents() { $path = __DIR__ . '/../resources'; $this->addConfigComponent('antares/acl', 'antares/acl', "{$path}/config"); $this->addLanguageComponent('antares/acl', 'antares/acl', "{$path}/lang"); $this->addViewComponent('antares/acl', 'antares/acl', "{$path}/views"); $this->bootMenu(); $this->bootMemory(); }
php
{ "resource": "" }
q264187
AclServiceProvider.bootMemory
test
protected function bootMemory() { $this->app->make('antares.acl')->make($this->routeGroup)->attach( $this->app->make('antares.platform.memory') ); }
php
{ "resource": "" }
q264188
RoleManagerProvider._loadParts
test
private function _loadParts() { $this->loadRoutesFrom(__DIR__ . '/routes.php'); $this->loadMigrationsFrom(__DIR__ . '/migrations'); $this->loadTranslationsFrom(__DIR__ . '/translations', 'RoleManager'); $this->loadViewsFrom(__DIR__ . '/views', 'RoleManager'); }
php
{ "resource": "" }
q264189
RoleManagerProvider._extendedValidation
test
private function _extendedValidation() { Validator::extend( 'classExist', function ($attribute, $value, $parameters, $validator) { if (empty($value)) { return true; } return class_exists($value); } ); Validator::extend( 'methodExist', function ($attribute, $value, $parameters, $validator) { if (!empty(Request::input('class'))) { return method_exists(Request::input('class'), $value); } return true; } ); Validator::replacer( 'classExist', function ($message, $attribute, $rule, $parameters) { return "Class does not exist"; } ); Validator::replacer( 'methodExist', function ($message, $attribute, $rule, $parameters) { return "Method in " . Request::input('class') . " class does not exist."; } ); }
php
{ "resource": "" }
q264190
Magniloquent.save
test
public function save(array $new_attributes = array(), $forceSave = false) { $options = array(); if (array_key_exists('touch', $new_attributes)) { $options['touch'] = $new_attributes['touch']; $new_attributes = array_except($new_attributes, array('touch')); } $this->fill($new_attributes); $this->beforeSave(); if (! $forceSave) { // If the validation failed, return false if (! $this->valid && ! $this->validate()) return false; } // Purge unnecessary fields $this->purgeUnneeded(); // Auto hash passwords $this->autoHash(); $this->saved = true; return parent::save($options); }
php
{ "resource": "" }
q264191
Magniloquent.validate
test
public function validate() { // Merge the rules arrays into one array $this->mergeRules(); // Exclude this object from unique checks if object exists if ($this->exists) { $this->excludeFromUniqueChecks(); } $validation = Validator::make($this->attributes, $this->mergedRules, $this->customMessages); // Sets the connection, based on the model's connection variable. $validation->getPresenceVerifier()->setConnection($this->connection); // Set custom messages on validator $validation->setAttributeNames($this->niceNames()); if ($validation->passes()) { $this->valid = true; return true; } $this->validationErrors = $validation->messages(); return false; }
php
{ "resource": "" }
q264192
Magniloquent.mergeRules
test
protected function mergeRules() { $rules = static::$rules; $output = array(); if ($this->exists) $merged = array_merge_recursive($rules['save'], $rules['update']); else $merged = array_merge_recursive($rules['save'], $rules['create']); foreach ($merged as $field => $rules) { if (is_array($rules)) $output[$field] = implode("|", $rules); else $output[$field] = $rules; } $this->mergedRules = $output; }
php
{ "resource": "" }
q264193
Magniloquent.purgeUnneeded
test
private function purgeUnneeded() { $clean = array(); foreach ($this->attributes as $key => $value) { if (! Str::endsWith($key, '_confirmation') && ! Str::startsWith($key, '_') && ! in_array($key, static::$purgeable)) $clean[$key] = $value; } $this->attributes = $clean; }
php
{ "resource": "" }
q264194
Magniloquent.autoHash
test
private function autoHash() { $attributes = array_merge(static::$needsHash, array('password')); foreach ($attributes as $name) { if (isset($this->attributes[$name]) && $this->isDirty($name)) { if ( ! Hash::check($this->attributes[$name], $this->getOriginal($name))) { $this->attributes[$name] = Hash::make($this->attributes[$name]); } } } }
php
{ "resource": "" }
q264195
FiltersTrait.disableFilters
test
public function disableFilters() { foreach (\array_keys($this->getFilterCollection()->getEnabledFilters()) as $filter) { $this->disableFilter($filter); } }
php
{ "resource": "" }
q264196
FiltersTrait.disableFilter
test
public function disableFilter(string $filter) { if (\in_array($filter, $this->disabledFilters, true)) { return; } $this->getFilterCollection()->disable($filter); $this->disabledFilters[] = $filter; }
php
{ "resource": "" }
q264197
FiltersTrait.restoreFilters
test
public function restoreFilters() { $filterCollection = $this->getFilterCollection(); foreach ($this->disabledFilters as $filter) { $filterCollection->enable($filter); } $this->disabledFilters = []; }
php
{ "resource": "" }
q264198
FiltersTrait.restoreFilter
test
public function restoreFilter(string $filter) { $position = \array_search($filter, $this->disabledFilters, true); if ($position === false) { return; } $this->getFilterCollection()->enable($filter); \array_splice($this->disabledFilters, $position, 1); }
php
{ "resource": "" }
q264199
Roles.getActionsColumn
test
protected function getActionsColumn($roleId, $canEditRole, $canDeleteRole) { return function ($row) use($roleId, $canEditRole, $canDeleteRole) { $btns = []; $html = app('html'); if ($canEditRole) { array_push($btns, $html->create('li', $html->link(handles("antares::acl/index/roles/{$row->id}/edit"), trans('antares/acl::title.edit_details'), ['data-icon' => 'edit']))); array_push($btns, $html->create('li', $html->link(handles("antares::acl/index/roles/{$row->id}/acl"), trans('antares/acl::title.acl_rules'), ['data-icon' => 'accounts-alt']))); } if ($row->id !== $roleId and $canDeleteRole) { $url = handles("antares::acl/index/roles/{$row->id}/delete", ['csrf' => true]); $class = 'triggerable confirm'; $dataTitle = trans('Are you sure?'); $dataDescription = trans('antares/acl::global.deleteing_role', ['name' => $row->name]); if ($row->users->count()) { publish('acl', ['js/delete-group-denied.js']); $url = '#'; $class = 'bindable delete-group-denied'; $dataTitle = trans('This action is not allowed'); $dataDescription = trans('There are users attached to this group. Only empty groups can be removed.'); } array_push($btns, $html->create('li', $html->link($url, trans('Delete'), [ 'class' => $class, 'data-icon' => 'delete', 'data-title' => $dataTitle, 'data-description' => $dataDescription ]))); } if (empty($btns)) { return ''; } $section = $html->create('div', $html->create('section', $html->create('ul', $html->raw(implode('', $btns)))), ['class' => 'mass-actions-menu'])->get(); return '<i class="zmdi zmdi-more"></i>' . $html->raw($section)->get(); }; }
php
{ "resource": "" }