_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q244600
File.preview
validation
public function preview($width, $height) { if (!$width || !$height) { throw new \Exception('Please, provide both width and height for preview'); } $result = clone $this; $result->operations[]['preview'] = array( 'width' => $width, 'height' => $height, ); return $result; }
php
{ "resource": "" }
q244601
File.op
validation
public function op($operation) { if (!$operation) { return $this; } $result = clone $this; $result->operations[]['custom'] = $operation; return $result; }
php
{ "resource": "" }
q244602
PagedDataIterator.exists
validation
private function exists($offset = null) { return isset($this->container[$offset !== null ? $offset : $this->position]); }
php
{ "resource": "" }
q244603
PagedDataIterator.isFullyLoaded
validation
private function isFullyLoaded() { return $this->fullyLoaded || ($this->limit && count($this->container) >= $this->limit); }
php
{ "resource": "" }
q244604
PagedDataIterator.loadChunk
validation
private function loadChunk() { $portion = $this->pdGetDataChunk($this->api, $this->options, $this->reverse); $this->options = $portion['params']; $this->nextPageParams = $portion['nextParams']; $this->prevPageParams = $portion['prevParams']; if ($portion['data']) { $this->container = array_merge($this->container, $portion['data']); } if (!count($portion['params'])) { $this->fullyLoaded = true; } }
php
{ "resource": "" }
q244605
Rewrite_Command.flush
validation
public function flush( $args, $assoc_args ) { // make sure we detect mod_rewrite if configured in apache_modules in config self::apache_modules(); if ( Utils\get_flag_value( $assoc_args, 'hard' ) && ! in_array( 'mod_rewrite', (array) WP_CLI::get_config( 'apache_modules' ), true ) ) { WP_CLI::warning( 'Regenerating a .htaccess file requires special configuration. See usage docs.' ); } if ( Utils\get_flag_value( $assoc_args, 'hard' ) && is_multisite() ) { WP_CLI::warning( "WordPress can't generate .htaccess file for a multisite install." ); } self::check_skip_plugins_themes(); flush_rewrite_rules( Utils\get_flag_value( $assoc_args, 'hard' ) ); if ( ! get_option( 'rewrite_rules' ) ) { WP_CLI::warning( "Rewrite rules are empty, possibly because of a missing permalink_structure option. Use 'wp rewrite list' to verify, or 'wp rewrite structure' to update permalink_structure." ); } else { WP_CLI::success( 'Rewrite rules flushed.' ); } }
php
{ "resource": "" }
q244606
Rewrite_Command.structure
validation
public function structure( $args, $assoc_args ) { global $wp_rewrite; // copypasta from /wp-admin/options-permalink.php $blog_prefix = ''; $prefix = $blog_prefix; if ( is_multisite() && ! is_subdomain_install() && is_main_site() ) { $blog_prefix = '/blog'; } $permalink_structure = ( 'default' === $args[0] ) ? '' : $args[0]; if ( ! empty( $permalink_structure ) ) { $permalink_structure = preg_replace( '#/+#', '/', '/' . str_replace( '#', '', $permalink_structure ) ); if ( $prefix && $blog_prefix ) { $permalink_structure = $prefix . preg_replace( '#^/?index\.php#', '', $permalink_structure ); } else { $permalink_structure = $blog_prefix . $permalink_structure; } } $wp_rewrite->set_permalink_structure( $permalink_structure ); // Update category or tag bases if ( isset( $assoc_args['category-base'] ) ) { $category_base = $assoc_args['category-base']; if ( ! empty( $category_base ) ) { $category_base = $blog_prefix . preg_replace( '#/+#', '/', '/' . str_replace( '#', '', $category_base ) ); } $wp_rewrite->set_category_base( $category_base ); } if ( isset( $assoc_args['tag-base'] ) ) { $tag_base = $assoc_args['tag-base']; if ( ! empty( $tag_base ) ) { $tag_base = $blog_prefix . preg_replace( '#/+#', '/', '/' . str_replace( '#', '', $tag_base ) ); } $wp_rewrite->set_tag_base( $tag_base ); } // make sure we detect mod_rewrite if configured in apache_modules in config self::apache_modules(); WP_CLI::success( 'Rewrite structure set.' ); // Launch a new process to flush rewrites because core expects flush // to happen after rewrites are set $new_assoc_args = []; $cmd = 'rewrite flush'; if ( Utils\get_flag_value( $assoc_args, 'hard' ) ) { $cmd .= ' --hard'; $new_assoc_args['hard'] = true; if ( ! in_array( 'mod_rewrite', (array) WP_CLI::get_config( 'apache_modules' ), true ) ) { WP_CLI::warning( 'Regenerating a .htaccess file requires special configuration. See usage docs.' ); } } $process_run = WP_CLI::runcommand( $cmd ); if ( ! empty( $process_run->stderr ) ) { // Strip "Warning: " WP_CLI::warning( substr( $process_run->stderr, 9 ) ); } }
php
{ "resource": "" }
q244607
Rewrite_Command.apache_modules
validation
private static function apache_modules() { $mods = WP_CLI::get_config( 'apache_modules' ); if ( ! empty( $mods ) && ! function_exists( 'apache_get_modules' ) ) { global $is_apache; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited $is_apache = true; // needed for get_home_path() and .htaccess location $_SERVER['SCRIPT_FILENAME'] = ABSPATH; function apache_get_modules() { return WP_CLI::get_config( 'apache_modules' ); } } }
php
{ "resource": "" }
q244608
ElementAnnotationsListener.prepareEvent
validation
protected function prepareEvent(EventInterface $event) { foreach (['elementSpec', 'inputSpec'] as $type) { if (! $event->getParam($type)) { $event->setParam($type, new ArrayObject()); } } $elementSpec = $event->getParam('elementSpec'); $inputSpec = $event->getParam('inputSpec'); if (! isset($elementSpec['spec'])) { $elementSpec['spec'] = []; } if (! isset($inputSpec['filters'])) { $inputSpec['filters'] = []; } if (! isset($inputSpec['validators'])) { $inputSpec['validators'] = []; } }
php
{ "resource": "" }
q244609
MetadataGrapher.generateFromMetadata
validation
public function generateFromMetadata(array $metadata) { $this->metadata = $metadata; $this->visitedAssociations = []; $str = []; foreach ($metadata as $class) { $parent = $this->getParent($class); if ($parent) { $str[] = $this->getClassString($parent) . '^' . $this->getClassString($class); } $associations = $class->getAssociationNames(); if (empty($associations) && ! isset($this->visitedAssociations[$class->getName()])) { $str[] = $this->getClassString($class); continue; } foreach ($associations as $associationName) { if ($parent && in_array($associationName, $parent->getAssociationNames())) { continue; } if ($this->visitAssociation($class->getName(), $associationName)) { $str[] = $this->getAssociationString($class, $associationName); } } } return implode(',', $str); }
php
{ "resource": "" }
q244610
MetadataGrapher.getClassString
validation
private function getClassString(ClassMetadata $class) { $this->visitAssociation($class->getName()); $className = $class->getName(); $classText = '[' . str_replace('\\', '.', $className); $fields = []; $parent = $this->getParent($class); $parentFields = $parent ? $parent->getFieldNames() : []; foreach ($class->getFieldNames() as $fieldName) { if (in_array($fieldName, $parentFields)) { continue; } if ($class->isIdentifier($fieldName)) { $fields[] = '+' . $fieldName; } else { $fields[] = $fieldName; } } if (! empty($fields)) { $classText .= '|' . implode(';', $fields); } $classText .= ']'; return $classText; }
php
{ "resource": "" }
q244611
MetadataGrapher.getClassByName
validation
private function getClassByName($className) { if (! isset($this->classByNames[$className])) { foreach ($this->metadata as $class) { if ($class->getName() === $className) { $this->classByNames[$className] = $class; break; } } } return $this->classByNames[$className] ?? null; }
php
{ "resource": "" }
q244612
MetadataGrapher.visitAssociation
validation
private function visitAssociation($className, $association = null) { if (null === $association) { if (isset($this->visitedAssociations[$className])) { return false; } $this->visitedAssociations[$className] = []; return true; } if (isset($this->visitedAssociations[$className][$association])) { return false; } if (! isset($this->visitedAssociations[$className])) { $this->visitedAssociations[$className] = []; } $this->visitedAssociations[$className][$association] = true; return true; }
php
{ "resource": "" }
q244613
FormAnnotationBuilderFactory.getFormFactory
validation
private function getFormFactory(ContainerInterface $services) { $elements = null; if ($services->has('FormElementManager')) { $elements = $services->get('FormElementManager'); } return new Factory($elements); }
php
{ "resource": "" }
q244614
YumlController.indexAction
validation
public function indexAction() { /* @var $request \Zend\Http\Request */ $request = $this->getRequest(); $this->httpClient->setMethod(Request::METHOD_POST); $this->httpClient->setParameterPost(['dsl_text' => $request->getPost('dsl_text')]); $response = $this->httpClient->send(); if (! $response->isSuccess()) { throw new \UnexpectedValueException('HTTP Request failed'); } /* @var $redirect \Zend\Mvc\Controller\Plugin\Redirect */ $redirect = $this->plugin('redirect'); return $redirect->toUrl('https://yuml.me/' . $response->getBody()); }
php
{ "resource": "" }
q244615
ImageHandler.getFilename
validation
protected function getFilename($filename) { $callback = $this->fileCallback; if (null === $callback || substr($filename, 0, 1) == '/') { return $filename; } return $callback($filename); }
php
{ "resource": "" }
q244616
ImageHandling.open
validation
public function open($file) { if (strlen($file) >= 1 && $file[0] == '@') { try { if ($this->fileLocator instanceof FileLocatorInterface) { $file = $this->fileLocator->locate($file); } else { $this->fileLocator->locateResource($file); } } catch (\InvalidArgumentException $exception) { if ($this->throwException || false == $this->fallbackImage) { throw $exception; } $file = $this->fallbackImage; } } return $this->createInstance($file); }
php
{ "resource": "" }
q244617
ImageHandling.createInstance
validation
private function createInstance($file, $w = null, $h = null) { $container = $this->container; $webDir = $container->getParameter('gregwar_image.web_dir'); $handlerClass = $this->handlerClass; /** @var ImageHandler $image */ $image = new $handlerClass($file, $w, $h, $this->throwException, $this->fallbackImage); $image->setCacheDir($this->cacheDirectory); $image->setCacheDirMode($this->cacheDirMode); $image->setActualCacheDir($webDir.'/'.$this->cacheDirectory); if ($container->has('templating.helper.assets')) { $image->setFileCallback(function ($file) use ($container) { return $container->get('templating.helper.assets')->getUrl($file); }); } else { $image->setFileCallback(function ($file) use ($container) { return $this->assetsPackages->getUrl($file); }); } return $image; }
php
{ "resource": "" }
q244618
RemindersController.postRemind
validation
public function postRemind() { \App::make('route'); \Config::set('auth.defaults.passwords', 'panel'); $response = \Password::sendResetLink(Input::only('email'), function($message) { $message->subject('Password Reminder'); }); switch ($response) { case PasswordBrokerContract::INVALID_USER: return \Redirect::back()->with('message', \Lang::get($response))->with('mesType', 'error'); case PasswordBrokerContract::RESET_LINK_SENT: return \Redirect::back()->with('message', \Lang::get($response))->with('mesType', 'info'); } }
php
{ "resource": "" }
q244619
dashboard.showLink
validation
private function showLink ($link) { if (!$link['show_menu']) return false; $user = \Auth::guard('panel')->user(); return $user->hasRole('super') || $user->hasPermission('/' . $link['url'] . '/all'); }
php
{ "resource": "" }
q244620
CreateControllerPanelCommand.getDefaultNamespace
validation
protected function getDefaultNamespace($rootNamespace) { $controllersPath = \Config::get('panel.controllers'); if ( isset($controllersPath) && $controllersPath != NULL ){ return $controllersPath; } else { return $rootNamespace.'\Http\Controllers'; } }
php
{ "resource": "" }
q244621
AppHelper.getModel
validation
public function getModel($entity) { if ( \Links::isMain($entity) ) { $modelClass = 'Serverfireteam\\Panel\\'.$entity; } else { if (!empty(\Config::get('panel.modelPath'))) { $modelClass = $this->getNameSpace() . \Config::get('panel.modelPath') . '\\' . $entity; } else { $modelClass = $this->getNameSpace() . $entity; } } return $modelClass; }
php
{ "resource": "" }
q244622
HasRoles.hasRole
validation
public function hasRole($role) { if (is_string($role)) { return $this->roles->contains('name', $role); } return !! $role->intersect($this->roles)->count(); }
php
{ "resource": "" }
q244623
HasRoles.hasPermission
validation
public function hasPermission($permission) { $permission = Permission::whereName($permission)->first(); if (is_null($permission)){ return false; } return $this->hasRole($permission->roles); }
php
{ "resource": "" }
q244624
PdoAdapter.authenticate
validation
public function authenticate() { $user = $this->findUser(); if ($user === false) { return new AuthenticationResult( AuthenticationResult::FAILURE_IDENTITY_NOT_FOUND, array(), array('User not found.') ); } $validationResult = $this->passwordValidator->isValid( $this->credential, $user[$this->credentialColumn], $user[$this->identityColumn] ); if ($validationResult->isValid()) { // Don't store password in identity unset($user[$this->getCredentialColumn()]); return new AuthenticationResult(AuthenticationResult::SUCCESS, $user, array()); } return new AuthenticationResult( AuthenticationResult::FAILURE_CREDENTIAL_INVALID, array(), array('Invalid username or password provided') ); }
php
{ "resource": "" }
q244625
PdoAdapter.findUser
validation
private function findUser() { $sql = sprintf( 'SELECT * FROM %s WHERE %s = :identity', $this->getTableName(), $this->getIdentityColumn() ); $stmt = $this->db->prepare($sql); $stmt->execute(array('identity' => $this->getIdentity())); // Explicitly setting fetch mode fixes // https://github.com/jeremykendall/slim-auth/issues/13 return $stmt->fetch(PDO::FETCH_ASSOC); }
php
{ "resource": "" }
q244626
Authorization.getRole
validation
private function getRole($identity = null) { if (is_object($identity)) { return $identity->getRole(); } if (is_array($identity) && isset($identity['role'])) { return $identity['role']; } return 'guest'; }
php
{ "resource": "" }
q244627
Authenticator.authenticate
validation
public function authenticate($identity, $credential) { $adapter = $this->auth->getAdapter(); $adapter->setIdentity($identity); $adapter->setCredential($credential); return $this->auth->authenticate(); }
php
{ "resource": "" }
q244628
SendsPasswordResetEmails.sendResetLinkEmail
validation
public function sendResetLinkEmail(Request $request) { $this->validateEmail($request); $user = $this->broker()->getUser($request->only('email')); // If the user hasn't confirmed their email address, // we will throw a validation exception for this error. // A user can not request a password reset link if they are not confirmed. if ($user && is_null($user->confirmed_at)) { session(['confirmation_user_id' => $user->getKey()]); throw ValidationException::withMessages([ 'confirmation' => [ __('confirmation::confirmation.not_confirmed_reset_password', [ 'resend_link' => route('auth.resend_confirmation') ]) ] ]); } // We will send the password reset link to this user. Once we have attempted // to send the link, we will examine the response then see the message we // need to show to the user. Finally, we'll send out a proper response. $response = $this->broker()->sendResetLink( $request->only('email') ); return $response == Password::RESET_LINK_SENT ? $this->sendResetLinkResponse($response) : $this->sendResetLinkFailedResponse($request, $response); }
php
{ "resource": "" }
q244629
RegistersUsers.redirectAfterConfirmationPath
validation
public function redirectAfterConfirmationPath() { if (method_exists($this, 'redirectConfirmationTo')) { return $this->redirectConfirmationTo(); } return property_exists($this, 'redirectConfirmationTo') ? $this->redirectConfirmationTo : route('login'); }
php
{ "resource": "" }
q244630
RegistersUsers.redirectAfterRegistrationPath
validation
public function redirectAfterRegistrationPath() { if (method_exists($this, 'redirectAfterRegistrationTo')) { return $this->redirectAfterRegistrationTo(); } return property_exists($this, 'redirectAfterRegistrationTo') ? $this->redirectAfterRegistrationTo : route('login'); }
php
{ "resource": "" }
q244631
RegistersUsers.redirectAfterResendConfirmationPath
validation
public function redirectAfterResendConfirmationPath() { if (method_exists($this, 'redirectAfterResendConfirmationTo')) { return $this->redirectAfterResendConfirmationTo(); } return property_exists($this, 'redirectAfterResendConfirmationTo') ? $this->redirectAfterResendConfirmationTo : route('login'); }
php
{ "resource": "" }
q244632
RegistersUsers.confirm
validation
public function confirm($confirmation_code) { $model = $this->guard()->getProvider()->createModel(); $user = $model->where('confirmation_code', $confirmation_code)->firstOrFail(); $user->confirmation_code = null; $user->confirmed_at = now(); $user->save(); event(new Confirmed($user)); return $this->confirmed($user) ?: redirect($this->redirectAfterConfirmationPath())->with('confirmation', __('confirmation::confirmation.confirmation_successful')); }
php
{ "resource": "" }
q244633
RegistersUsers.resendConfirmation
validation
public function resendConfirmation(Request $request) { $model = $this->guard()->getProvider()->createModel(); $user = $model->findOrFail($request->session()->pull('confirmation_user_id')); $this->sendConfirmationToUser($user); return redirect($this->redirectAfterResendConfirmationPath())->with('confirmation', __('confirmation::confirmation.confirmation_resent')); }
php
{ "resource": "" }
q244634
RegistersUsers.register
validation
public function register(Request $request) { $this->validator($request->all())->validate(); event(new Registered($user = $this->create($request->all()))); $this->sendConfirmationToUser($user); return $this->registered($request, $user) ?: redirect($this->redirectAfterRegistrationPath())->with('confirmation', __('confirmation::confirmation.confirmation_info')); }
php
{ "resource": "" }
q244635
RegistersUsers.sendConfirmationToUser
validation
protected function sendConfirmationToUser($user) { // Create the confirmation code $user->confirmation_code = str_random(25); $user->save(); // Notify the user $notification = app(config('confirmation.notification')); $user->notify($notification); }
php
{ "resource": "" }
q244636
AuthenticatesUsers.attemptLogin
validation
protected function attemptLogin(Request $request) { if ($this->guard()->validate($this->credentials($request))) { $user = $this->guard()->getLastAttempted(); if (! is_null($user->confirmed_at)) { return $this->baseAttemptLogin($request); } session([ 'confirmation_user_id' => $user->getKey() ]); throw ValidationException::withMessages([ 'confirmation' => [ __('confirmation::confirmation.not_confirmed', [ 'resend_link' => route('auth.resend_confirmation') ]) ] ]); } return false; }
php
{ "resource": "" }
q244637
ConfirmEmail.toMail
validation
public function toMail($notifiable) { return (new MailMessage) ->subject(__('confirmation::confirmation.confirmation_subject')) ->line(__('confirmation::confirmation.confirmation_subject_title')) ->line(__('confirmation::confirmation.confirmation_body')) ->action(__('confirmation::confirmation.confirmation_button'), url("register/confirm/$notifiable->confirmation_code")); }
php
{ "resource": "" }
q244638
Normalizer.urlDecodeUnreservedChars
validation
public function urlDecodeUnreservedChars($string) { $string = rawurldecode($string); $string = rawurlencode($string); $string = str_replace(array( '%2F', '%3A', '%40' ), array( '/', ':', '@' ), $string); return $string; }
php
{ "resource": "" }
q244639
Normalizer.parseStr
validation
private function parseStr($string) { $params = array(); $pairs = explode('&', $string); foreach ($pairs as $pair) { if (! $pair) { continue; } $var = explode('=', $pair, 2); $val = ( isset( $var[1] ) ? $var[1] : '' ); if (isset($params[$var[0]])) { if (is_array($params[$var[0]])) { $params[$var[0]][] = $val; } else { $params[$var[0]] = array($params[$var[0]], $val); } } else { $params[$var[0]] = $val; } } return $params; }
php
{ "resource": "" }
q244640
ApistMethod.get
validation
public function get($arguments = []) { try { $this->makeRequest($arguments); } catch (ConnectException $e) { $url = $e->getRequest()->getUrl(); return $this->errorResponse($e->getCode(), $e->getMessage(), $url); } catch (RequestException $e) { $url = $e->getRequest()->getUrl(); $status = $e->getCode(); $response = $e->getResponse(); $reason = $e->getMessage(); if ( ! is_null($response)) { $reason = $response->getReasonPhrase(); } return $this->errorResponse($status, $reason, $url); } return $this->parseBlueprint($this->schemaBlueprint); }
php
{ "resource": "" }
q244641
ApistMethod.makeRequest
validation
protected function makeRequest($arguments = []) { $defaults = $this->getDefaultOptions(); $arguments = array_merge($defaults, $arguments); $client = $this->resource->getGuzzle(); $request = $client->createRequest($this->getMethod(), $this->url, $arguments); $response = $client->send($request); $this->setResponse($response); $this->setContent((string)$response->getBody()); }
php
{ "resource": "" }
q244642
ApistSelector.getValue
validation
public function getValue(ApistMethod $method, Crawler $rootNode = null) { if (is_null($rootNode)) { $rootNode = $method->getCrawler(); } $result = $rootNode->filter($this->selector); return $this->applyResultCallbackChain($result, $method); }
php
{ "resource": "" }
q244643
ApistSelector.applyResultCallbackChain
validation
protected function applyResultCallbackChain(Crawler $node, ApistMethod $method) { if (empty($this->resultMethodChain)) { $this->addCallback('text'); } /** @var ResultCallback[] $traceStack */ $traceStack = []; foreach ($this->resultMethodChain as $resultCallback) { try { $traceStack[] = $resultCallback; $node = $resultCallback->apply($node, $method); } catch (InvalidArgumentException $e) { if ($method->getResource()->isSuppressExceptions()) { return null; } $message = $this->createExceptionMessage($e, $traceStack); throw new InvalidArgumentException($message, 0, $e); } } return $node; }
php
{ "resource": "" }
q244644
YamlApist.loadFromYml
validation
protected function loadFromYml($file) { $this->parser = new Parser($file); $this->parser->load($this); }
php
{ "resource": "" }
q244645
Command.lock
validation
public function lock(Output $output) { # If this command doesn't require locking then don't do anything if (!$this->lock) { return; } $this->lock = $this->getApplication()->getLockFactory()->createLock($this->getName()); if (!$this->lock->acquire()) { $output->error("Another instance of this command (" . $this->getName() . ") is currently running"); exit(Application::STATUS_LOCKED); } }
php
{ "resource": "" }
q244646
Command.timeout
validation
public function timeout(int $timeout): bool { $application = $this->getApplication(); if (!$application instanceof Application) { return false; } # Check if the application is currently allowing time limiting or not if (!$application->timeLimit()) { return false; } $endTime = $this->startTime + $timeout; return (time() > $endTime); }
php
{ "resource": "" }
q244647
Application.loadCommands
validation
public function loadCommands(string $path, string $namespace = "", string $suffix = "Command"): Application { $commands = []; # Get the realpath so we can strip it from the start of the filename $realpath = (string) realpath($path); $finder = (new Finder())->files()->in($path)->name("/[A-Z].*{$suffix}.php/"); foreach ($finder as $file) { # Get the realpath of the file and ensure the class is loaded $filename = (string) $file->getRealPath(); require_once $filename; # Convert the filename to a class $class = $filename; $class = str_replace($realpath, "", $class); $class = str_replace(".php", "", $class); $class = str_replace("/", "\\", $class); # Convert the class name to a command name $command = $class; if (substr($command, 0, 1) == "\\") { $command = substr($command, 1); } $command = (string) preg_replace_callback("/^([A-Z])(.*){$suffix}$/", function ($match) { return strtolower($match[1]) . $match[2]; }, $command); $command = preg_replace_callback("/(\\\\)?([A-Z])/", function ($match) { $result = ($match[1]) ? ":" : "-"; $result .= strtolower($match[2]); return $result; }, $command); $class = $namespace . $class; # Don't attempt create things we can't instantiate $reflected = new \ReflectionClass($class); if (!$reflected->isInstantiable()) { continue; } $commands[] = new $class($command); } if (count($commands) < 1) { throw new \InvalidArgumentException("No commands were found in the path (" . $path . ")"); } $this->addCommands($commands); return $this; }
php
{ "resource": "" }
q244648
Application.setLockStore
validation
public function setLockStore(StoreInterface $store): Factory { $this->lockFactory = new Factory($store); return $this->lockFactory; }
php
{ "resource": "" }
q244649
Application.getLockFactory
validation
public function getLockFactory(): Factory { if ($this->lockFactory !== null) { return $this->lockFactory; } if (!is_dir($this->lockPath)) { (new Filesystem())->mkdir($this->lockPath); } $store = new FlockStore($this->lockPath); return $this->setLockStore($store); }
php
{ "resource": "" }
q244650
Application.setLockPath
validation
public function setLockPath(string $path): Application { if (!is_dir($path)) { (new Filesystem())->mkdir($path); } if (!$realpath = realpath($path)) { throw new \InvalidArgumentException("The directory (" . $path . ") is unavailable"); } $this->lockPath = $realpath; return $this; }
php
{ "resource": "" }
q244651
Application.runCommand
validation
public function runCommand(string $command, array $options, InputInterface $current, OutputInterface $output): int { # The first input argument must be the command name array_unshift($options, $command); $input = new ArrayInput($options); if (!$current->isInteractive()) { $input->setInteractive(false); } $command = $this->get($command); return $this->doRunCommand($command, $input, $output); }
php
{ "resource": "" }
q244652
Duration.format
validation
public function format(): string { foreach ($this->times as $unit => $value) { if ($this->time >= $value) { $time = floor($this->time / $value * 100) / 100; return "{$time} {$unit}"; } } return round($this->time * 1000) . " ms"; }
php
{ "resource": "" }
q244653
CrawlLogger.finishedCrawling
validation
public function finishedCrawling() { $this->consoleOutput->writeln(''); $this->consoleOutput->writeln('Crawling summary'); $this->consoleOutput->writeln('----------------'); ksort($this->crawledUrls); foreach ($this->crawledUrls as $statusCode => $urls) { $colorTag = $this->getColorTagForStatusCode($statusCode); $count = count($urls); if (is_numeric($statusCode)) { $this->consoleOutput->writeln("<{$colorTag}>Crawled {$count} url(s) with statuscode {$statusCode}</{$colorTag}>"); } if ($statusCode == static::UNRESPONSIVE_HOST) { $this->consoleOutput->writeln("<{$colorTag}>{$count} url(s) did have unresponsive host(s)</{$colorTag}>"); } } $this->consoleOutput->writeln(''); }
php
{ "resource": "" }
q244654
BaseBitrixModel.refreshFields
validation
public function refreshFields() { if ($this->id === null) { $this->original = []; return $this->fields = []; } $this->fields = static::query()->getById($this->id)->fields; $this->original = $this->fields; $this->fieldsAreFetched = true; return $this->fields; }
php
{ "resource": "" }
q244655
BaseBitrixModel.fill
validation
public function fill($fields) { if (!is_array($fields)) { return; } if (isset($fields['ID'])) { $this->id = $fields['ID']; } $this->fields = $fields; $this->fieldsAreFetched = true; if (method_exists($this, 'afterFill')) { $this->afterFill(); } $this->original = $this->fields; }
php
{ "resource": "" }
q244656
BaseBitrixModel.update
validation
public function update(array $fields = []) { $keys = []; foreach ($fields as $key => $value) { array_set($this->fields, $key, $value); $keys[] = $key; } return $this->save($keys); }
php
{ "resource": "" }
q244657
BaseBitrixModel.normalizeFieldsForSave
validation
protected function normalizeFieldsForSave($selectedFields) { $fields = []; if ($this->fields === null) { return []; } foreach ($this->fields as $field => $value) { if (!$this->fieldShouldNotBeSaved($field, $value, $selectedFields)) { $fields[$field] = $value; } } return $fields ?: null; }
php
{ "resource": "" }
q244658
BaseBitrixModel.getValueFromLanguageField
validation
protected function getValueFromLanguageField($field) { $key = $field . '_' . $this->getCurrentLanguage(); return isset($this->fields[$key]) ? $this->fields[$key] : null; }
php
{ "resource": "" }
q244659
ServiceProvider.registerEloquent
validation
public static function registerEloquent() { $capsule = self::bootstrapIlluminateDatabase(); class_alias(Capsule::class, 'DB'); if ($_COOKIE["show_sql_stat"] == "Y") { Capsule::enableQueryLog(); $em = \Bitrix\Main\EventManager::getInstance(); $em->addEventHandler('main', 'OnAfterEpilog', [IlluminateQueryDebugger::class, 'onAfterEpilogHandler']); } static::addEventListenersForHelpersHighloadblockTables($capsule); }
php
{ "resource": "" }
q244660
ServiceProvider.instantiateServiceContainer
validation
protected static function instantiateServiceContainer() { $container = Container::getInstance(); if (!$container) { $container = new Container(); Container::setInstance($container); } return $container; }
php
{ "resource": "" }
q244661
BitrixModel.delete
validation
public function delete() { if ($this->onBeforeDelete() === false) { return false; } $result = static::$bxObject->delete($this->id); $this->setEventErrorsOnFail($result, static::$bxObject); $this->onAfterDelete($result); $this->resetEventErrors(); $this->throwExceptionOnFail($result, static::$bxObject); return $result; }
php
{ "resource": "" }
q244662
UserQuery.loadModels
validation
protected function loadModels() { $queryType = 'UserQuery::getList'; $sort = $this->sort; $filter = $this->normalizeFilter(); $params = [ 'SELECT' => $this->propsMustBeSelected() ? ['UF_*'] : ($this->normalizeUfSelect() ?: false), 'NAV_PARAMS' => $this->navigation, 'FIELDS' => $this->normalizeSelect(), ]; $selectGroups = $this->groupsMustBeSelected(); $keyBy = $this->keyBy; $callback = function() use ($sort, $filter, $params, $selectGroups){ $users = []; $rsUsers = $this->bxObject->getList($sort, $sortOrder = false, $filter, $params); while ($arUser = $this->performFetchUsingSelectedMethod($rsUsers)) { if ($selectGroups) { $arUser['GROUP_ID'] = $this->bxObject->getUserGroup($arUser['ID']); } $this->addItemToResultsUsingKeyBy($users, new $this->modelName($arUser['ID'], $arUser)); } return new Collection($users); }; return $this->handleCacheIfNeeded(compact('queryType', 'sort', 'filter', 'params', 'selectGroups', 'keyBy'), $callback); }
php
{ "resource": "" }
q244663
UserQuery.count
validation
public function count() { if ($this->queryShouldBeStopped) { return 0; } $queryType = 'UserQuery::count'; $filter = $this->normalizeFilter(); $callback = function() use ($filter) { return (int) $this->bxObject->getList($order = 'ID', $by = 'ASC', $filter, [ 'NAV_PARAMS' => [ 'nTopCount' => 0, ], ])->NavRecordCount; }; return $this->handleCacheIfNeeded(compact('queryType', 'filter'), $callback); }
php
{ "resource": "" }
q244664
UserQuery.groupsMustBeSelected
validation
protected function groupsMustBeSelected() { return in_array('GROUPS', $this->select) || in_array('GROUP_ID', $this->select) || in_array('GROUPS_ID', $this->select); }
php
{ "resource": "" }
q244665
UserQuery.normalizeFilter
validation
protected function normalizeFilter() { $this->substituteField($this->filter, 'GROUPS', 'GROUPS_ID'); $this->substituteField($this->filter, 'GROUP_ID', 'GROUPS_ID'); return $this->filter; }
php
{ "resource": "" }
q244666
BaseQuery.getById
validation
public function getById($id) { if (!$id || $this->queryShouldBeStopped) { return false; } $this->sort = []; $this->filter['ID'] = $id; return $this->getList()->first(null, false); }
php
{ "resource": "" }
q244667
BaseQuery.sort
validation
public function sort($by, $order = 'ASC') { $this->sort = is_array($by) ? $by : [$by => $order]; return $this; }
php
{ "resource": "" }
q244668
BaseQuery.addFilter
validation
public function addFilter($filters) { foreach ($filters as $field => $value) { $this->filter[$field] = $value; } return $this; }
php
{ "resource": "" }
q244669
BaseQuery.paginate
validation
public function paginate($perPage = 15, $pageName = 'page') { $page = Paginator::resolveCurrentPage($pageName); $total = $this->count(); $results = $this->forPage($page, $perPage)->getList(); return new LengthAwarePaginator($results, $total, $perPage, $page, [ 'path' => Paginator::resolveCurrentPath(), 'pageName' => $pageName, ]); }
php
{ "resource": "" }
q244670
BaseQuery.propsMustBeSelected
validation
protected function propsMustBeSelected() { return in_array('PROPS', $this->select) || in_array('PROPERTIES', $this->select) || in_array('PROPERTY_VALUES', $this->select); }
php
{ "resource": "" }
q244671
BaseQuery.rememberInCache
validation
protected function rememberInCache($key, $minutes, Closure $callback) { $minutes = (double) $minutes; if ($minutes <= 0) { return $callback(); } $cache = Cache::createInstance(); if ($cache->initCache($minutes * 60, $key, '/bitrix-models')) { $vars = $cache->getVars(); return !empty($vars['isCollection']) ? new Collection($vars['cache']) : $vars['cache']; } $cache->startDataCache(); $result = $callback(); // Bitrix cache is bad for storing collections. Let's convert it to array. $isCollection = $result instanceof Collection; if ($isCollection) { $result = $result->all(); } $cache->endDataCache(['cache' => $result, 'isCollection' => $isCollection]); return $isCollection ? new Collection($result) : $result; }
php
{ "resource": "" }
q244672
SectionQuery.count
validation
public function count() { if ($this->queryShouldBeStopped) { return 0; } $queryType = 'SectionQuery::count'; $filter = $this->normalizeFilter(); $callback = function() use ($filter) { return (int) $this->bxObject->getCount($filter); }; return $this->handleCacheIfNeeded(compact('queryType', 'filter'), $callback); }
php
{ "resource": "" }
q244673
SectionQuery.normalizeSelect
validation
protected function normalizeSelect() { if ($this->fieldsMustBeSelected()) { $this->select = array_merge($this->standardFields, $this->select); } if ($this->propsMustBeSelected()) { $this->select[] = 'IBLOCK_ID'; $this->select[] = 'UF_*'; } $this->select[] = 'ID'; return $this->clearSelectArray(); }
php
{ "resource": "" }
q244674
UserModel.refreshFields
validation
public function refreshFields() { if ($this->id === null) { $this->original = []; return $this->fields = []; } $groupBackup = isset($this->fields['GROUP_ID']) ? $this->fields['GROUP_ID'] : null; $this->fields = static::query()->getById($this->id)->fields; if ($groupBackup) { $this->fields['GROUP_ID'] = $groupBackup; } $this->fieldsAreFetched = true; $this->original = $this->fields; return $this->fields; }
php
{ "resource": "" }
q244675
UserModel.refreshGroups
validation
public function refreshGroups() { if ($this->id === null) { return []; } global $USER; $this->fields['GROUP_ID'] = $this->isCurrent() ? $USER->getUserGroupArray() : static::$bxObject->getUserGroup($this->id); $this->groupsAreFetched = true; return $this->fields['GROUP_ID']; }
php
{ "resource": "" }
q244676
UserModel.substituteGroup
validation
public function substituteGroup($old, $new) { $groups = $this->getGroups(); if(($key = array_search($old, $groups)) !== false) { unset($groups[$key]); } if (!in_array($new, $groups)) { $groups[] = $new; } $this->fields['GROUP_ID'] = $groups; }
php
{ "resource": "" }
q244677
ElementQuery.fetchAllPropsForSelect
validation
protected function fetchAllPropsForSelect() { $props = []; $rsProps = static::$cIblockObject->GetProperties($this->iblockId); while ($prop = $rsProps->Fetch()) { $props[] = 'PROPERTY_'.$prop['CODE']; } return $props; }
php
{ "resource": "" }
q244678
ElementModel.refreshFields
validation
public function refreshFields() { if ($this->id === null) { $this->original = []; return $this->fields = []; } $sectionsBackup = isset($this->fields['IBLOCK_SECTION']) ? $this->fields['IBLOCK_SECTION'] : null; $this->fields = static::query()->getById($this->id)->fields; if (!empty($sectionsBackup)) { $this->fields['IBLOCK_SECTION'] = $sectionsBackup; } $this->fieldsAreFetched = true; $this->original = $this->fields; return $this->fields; }
php
{ "resource": "" }
q244679
ElementModel.refreshSections
validation
public function refreshSections() { if ($this->id === null) { return []; } $this->fields['IBLOCK_SECTION'] = []; $dbSections = static::$bxObject->getElementGroups($this->id, true); while ($section = $dbSections->Fetch()) { $this->fields['IBLOCK_SECTION'][] = $section; } $this->sectionsAreFetched = true; return $this->fields['IBLOCK_SECTION']; }
php
{ "resource": "" }
q244680
ElementModel.section
validation
public function section($load = false) { $fields = $this->getFields(); /** @var SectionModel $sectionModel */ $sectionModel = static::sectionModel(); return $load ? $sectionModel::query()->getById($fields['IBLOCK_SECTION_ID']) : new $sectionModel($fields['IBLOCK_SECTION_ID']); }
php
{ "resource": "" }
q244681
ElementModel.saveProps
validation
public function saveProps($selected = []) { $propertyValues = $this->constructPropertyValuesForSave($selected); if (empty($propertyValues)) { return false; } $bxMethod = empty($selected) ? 'setPropertyValues' : 'setPropertyValuesEx'; static::$bxObject->$bxMethod( $this->id, static::iblockId(), $propertyValues ); return true; }
php
{ "resource": "" }
q244682
ElementModel.normalizePropertyFormat
validation
protected function normalizePropertyFormat() { if (empty($this->fields['PROPERTIES'])) { return; } foreach ($this->fields['PROPERTIES'] as $code => $prop) { $this->fields['PROPERTY_'.$code.'_VALUE'] = $prop['VALUE']; $this->fields['~PROPERTY_'.$code.'_VALUE'] = $prop['~VALUE']; $this->fields['PROPERTY_'.$code.'_DESCRIPTION'] = $prop['DESCRIPTION']; $this->fields['~PROPERTY_'.$code.'_DESCRIPTION'] = $prop['~DESCRIPTION']; $this->fields['PROPERTY_'.$code.'_VALUE_ID'] = $prop['PROPERTY_VALUE_ID']; } }
php
{ "resource": "" }
q244683
OldCoreQuery.fetchUsing
validation
public function fetchUsing($methodAndParams) { // simple case if (is_string($methodAndParams) || empty($methodAndParams['method'])) { $this->fetchUsing = in_array($methodAndParams, ['GetNext', 'getNext']) ? ['method' => 'GetNext', 'params' => [true, true]] : ['method' => 'Fetch']; return $this; } // complex case if (in_array($methodAndParams['method'], ['GetNext', 'getNext'])) { $bTextHtmlAuto = isset($methodAndParams['params'][0]) ? $methodAndParams['params'][0] : true; $useTilda = isset($methodAndParams['params'][1]) ? $methodAndParams['params'][1] : true; $this->fetchUsing = ['method' => 'GetNext', 'params' => [$bTextHtmlAuto, $useTilda]]; } else { $this->fetchUsing = ['method' => 'Fetch']; } return $this; }
php
{ "resource": "" }
q244684
ArrayableModel.offsetExists
validation
public function offsetExists($offset) { return $this->getAccessor($offset) || $this->getAccessorForLanguageField($offset) ? true : isset($this->fields[$offset]); }
php
{ "resource": "" }
q244685
ArrayableModel.offsetGet
validation
public function offsetGet($offset) { $fieldValue = isset($this->fields[$offset]) ? $this->fields[$offset] : null; $accessor = $this->getAccessor($offset); if ($accessor) { return $this->$accessor($fieldValue); } $accessorForLanguageField = $this->getAccessorForLanguageField($offset); if ($accessorForLanguageField) { return $this->$accessorForLanguageField($offset); } return $fieldValue; }
php
{ "resource": "" }
q244686
ArrayableModel.getAccessor
validation
private function getAccessor($field) { $method = 'get'.camel_case($field).'Attribute'; return method_exists($this, $method) ? $method : false; }
php
{ "resource": "" }
q244687
ArrayableModel.getAccessorForLanguageField
validation
private function getAccessorForLanguageField($field) { $method = 'getValueFromLanguageField'; return in_array($field, $this->languageAccessors) && method_exists($this, $method) ? $method : false; }
php
{ "resource": "" }
q244688
ArrayableModel.toArray
validation
public function toArray() { $array = $this->fields; foreach ($this->appends as $accessor) { if (isset($this[$accessor])) { $array[$accessor] = $this[$accessor]; } } foreach ($this->related as $key => $value) { if (is_object($value) && method_exists($value, 'toArray')) { $array[$key] = $value->toArray(); } elseif (is_null($value) || $value === false) { $array[$key] = $value; } } if (count($this->getVisible()) > 0) { $array = array_intersect_key($array, array_flip($this->getVisible())); } if (count($this->getHidden()) > 0) { $array = array_diff_key($array, array_flip($this->getHidden())); } return $array; }
php
{ "resource": "" }
q244689
EloquentModel.getAttribute
validation
public function getAttribute($key) { if (in_array($key, $this->multipleHighloadBlockFields)) { return unserialize($this->attributes[$key]); } return parent::getAttribute($key); }
php
{ "resource": "" }
q244690
EloquentModel.setAttribute
validation
public function setAttribute($key, $value) { if (in_array($key, $this->multipleHighloadBlockFields)) { $this->attributes[$key] = serialize($value); return $this; } parent::setAttribute($key, $value); return $this; }
php
{ "resource": "" }
q244691
SectionModel.getDirectChildren
validation
public function getDirectChildren(array $filter = []) { return static::query() ->filter($filter) ->filter(['SECTION_ID' => $this->id]) ->select('ID') ->getList() ->transform(function ($section) { return (int) $section['ID']; }) ->all(); }
php
{ "resource": "" }
q244692
EventProducerTrait.recordThat
validation
protected function recordThat(AggregateChanged $event): void { $this->version += 1; $this->recordedEvents[] = $event->withVersion($this->version); $this->apply($event); }
php
{ "resource": "" }
q244693
AggregateRepository.getAggregateRoot
validation
public function getAggregateRoot(string $aggregateId) { if (! $this->disableIdentityMap && isset($this->identityMap[$aggregateId])) { return $this->identityMap[$aggregateId]; } if ($this->snapshotStore) { $eventSourcedAggregateRoot = $this->loadFromSnapshotStore($aggregateId); if ($eventSourcedAggregateRoot && ! $this->disableIdentityMap) { //Cache aggregate root in the identity map $this->identityMap[$aggregateId] = $eventSourcedAggregateRoot; } return $eventSourcedAggregateRoot; } $streamName = $this->determineStreamName($aggregateId); if ($this->oneStreamPerAggregate) { try { $streamEvents = $this->eventStore->load($streamName, 1); } catch (StreamNotFound $e) { return null; } } else { $metadataMatcher = new MetadataMatcher(); $metadataMatcher = $metadataMatcher->withMetadataMatch( '_aggregate_type', Operator::EQUALS(), $this->aggregateType->toString() ); $metadataMatcher = $metadataMatcher->withMetadataMatch( '_aggregate_id', Operator::EQUALS(), $aggregateId ); try { $streamEvents = $this->eventStore->load($streamName, 1, null, $metadataMatcher); } catch (StreamNotFound $e) { return null; } } if (! $streamEvents->valid()) { return null; } $eventSourcedAggregateRoot = $this->aggregateTranslator->reconstituteAggregateFromHistory( $this->aggregateType, $streamEvents ); if (! $this->disableIdentityMap) { //Cache aggregate root in the identity map but without pending events $this->identityMap[$aggregateId] = $eventSourcedAggregateRoot; } return $eventSourcedAggregateRoot; }
php
{ "resource": "" }
q244694
AggregateRepository.determineStreamName
validation
protected function determineStreamName(string $aggregateId): StreamName { if ($this->oneStreamPerAggregate) { if (null === $this->streamName) { $prefix = $this->aggregateType->toString(); } else { $prefix = $this->streamName->toString(); } return new StreamName($prefix . '-' . $aggregateId); } if (null === $this->streamName) { return new StreamName('event_stream'); } return $this->streamName; }
php
{ "resource": "" }
q244695
AggregateType.fromAggregateRoot
validation
public static function fromAggregateRoot($eventSourcedAggregateRoot): AggregateType { if (! \is_object($eventSourcedAggregateRoot)) { throw new Exception\AggregateTypeException( \sprintf('Aggregate root must be an object but type of %s given', \gettype($eventSourcedAggregateRoot)) ); } if ($eventSourcedAggregateRoot instanceof AggregateTypeProvider) { return $eventSourcedAggregateRoot->aggregateType(); } $self = new static(); $self->aggregateType = \get_class($eventSourcedAggregateRoot); return $self; }
php
{ "resource": "" }
q244696
AggregateType.fromAggregateRootClass
validation
public static function fromAggregateRootClass(string $aggregateRootClass): AggregateType { if (! \class_exists($aggregateRootClass)) { throw new Exception\InvalidArgumentException(\sprintf('Aggregate root class %s can not be found', $aggregateRootClass)); } $self = new static(); $self->aggregateType = $aggregateRootClass; return $self; }
php
{ "resource": "" }
q244697
AggregateType.fromString
validation
public static function fromString(string $aggregateTypeString): AggregateType { if (empty($aggregateTypeString)) { throw new Exception\InvalidArgumentException('AggregateType must be a non empty string'); } $self = new static(); $self->aggregateType = $aggregateTypeString; return $self; }
php
{ "resource": "" }
q244698
EventSourcedTrait.replay
validation
protected function replay(Iterator $historyEvents): void { foreach ($historyEvents as $pastEvent) { /** @var AggregateChanged $pastEvent */ $this->version = $pastEvent->version(); $this->apply($pastEvent); } }
php
{ "resource": "" }
q244699
Application.extend
validation
public function extend($module): void { if (is_object($module) || class_exists($module)) { $this->modules[] = $module; } else { throw ApplicationException::forInvalidModule($module); } }
php
{ "resource": "" }