_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q251600
ErrorHandler.formatBacktrace
validation
protected static function formatBacktrace(array $backtrace) : array { if (is_array($backtrace) === false || count($backtrace) === 0) { return $backtrace; } /** * Remove unnecessary info from backtrace */ if ($backtrace[0]['function'] == '{closure}') { unset($backtrace[0]); } /** * Format backtrace */ $trace = []; foreach ($backtrace as $entry) { /** * Function */ $function = ''; if (isset($entry['class'])) { $function .= $entry['class'] . $entry['type']; } $function .= $entry['function'] . '()'; /** * Arguments */ $arguments = []; if (isset($entry['args']) && count($entry['args']) > 0) { foreach ($entry['args'] as $arg) { ob_start(); var_dump($arg); $arg = htmlspecialchars(ob_get_contents()); ob_end_clean(); $arguments[] = $arg; } } /** * Location */ $location = []; if (isset($entry['file'])) { $location['file'] = $entry['file']; $location['line'] = $entry['line']; $location['code'] = self::highlightCode($entry['file'], $entry['line']); } /** * Compile into array */ $trace[] = array ( 'function' => $function, 'arguments' => $arguments, 'location' => $location, ); } return $trace; }
php
{ "resource": "" }
q251601
ErrorHandler.fatal
validation
public static function fatal() { $e = error_get_last(); if ($e !== null && (error_reporting() & $e['type']) !== 0) { ErrorHandler::exception(new \ErrorException($e['message'], $e['type'], 0, $e['file'], $e['line'])); exit(1); } }
php
{ "resource": "" }
q251602
ErrorHandler.writeLogs
validation
public static function writeLogs(string $message) : bool { return (bool) file_put_contents(rtrim(LOGS_PATH, '/') . '/' . gmdate('Y_m_d') . '.log', '[' . gmdate('d-M-Y H:i:s') . '] ' . $message . PHP_EOL, FILE_APPEND); }
php
{ "resource": "" }
q251603
ErrorHandler.exception
validation
public static function exception($exception) { try { // Empty output buffers while(ob_get_level() > 0) ob_end_clean(); // Get exception info $error['code'] = $exception->getCode(); $error['message'] = $exception->getMessage(); $error['file'] = $exception->getFile(); $error['line'] = $exception->getLine(); // Determine error type if ($exception instanceof \ErrorException) { $error['type'] = 'ErrorException: '; $error['type'] .= in_array($error['code'], array_keys(ErrorHandler::$levels)) ? ErrorHandler::$levels[$error['code']] : 'Unknown Error'; } else { $error['type'] = get_class($exception); } // Write to log ErrorHandler::writeLogs("{$error['type']}: {$error['message']} in {$error['file']} at line {$error['line']}"); // Send headers and output @header('Content-Type: text/html; charset=UTF-8'); if (DEVELOPMENT) { $error['backtrace'] = $exception->getTrace(); if ($exception instanceof \ErrorException) { $error['backtrace'] = array_slice($error['backtrace'], 1); //Remove call to error handler from backtrace } $error['backtrace'] = self::formatBacktrace($error['backtrace']); $error['highlighted'] = self::highlightCode($error['file'], $error['line']); @header('HTTP/1.1 500 Internal Server Error'); include 'views/exception.php'; } else { @header('HTTP/1.1 500 Internal Server Error'); include 'views/production.php'; } } catch (Exception $e) { // Empty output buffers while(ob_get_level() > 0) ob_end_clean(); echo $e->getMessage() . ' in ' . $e->getFile() . ' (line ' . $e->getLine() . ').'; } exit(1); }
php
{ "resource": "" }
q251604
NodeList.__isset
validation
public function __isset( $childName ) { // Iterate over all nodes and check if a child with the requested name // exists. foreach ( $this->nodes as $node ) { if ( isset( $node->$childName ) ) { // We found something, so that we can immediatly exit with // true. The general count is out of interest here. return true; } } // Return false, if no such property could be found before... return false; }
php
{ "resource": "" }
q251605
NodeList.offsetSet
validation
public function offsetSet( $item, $node ) { // We only allow to append nodes to node list, so that we bail out on // all other array keys then null. if ( $item !== null ) { throw new ValueException( $item, 'null' ); } return $this->nodes[] = $node; }
php
{ "resource": "" }
q251606
AuthController.login
validation
public function login(LoginRequest $request) { $this->bus->pipeThrough($this->pipesOf('login'))->dispatchFrom(LoginJob::class, $request); return redirect()->route(config('_auth.login.redirect')); }
php
{ "resource": "" }
q251607
AuthController.logout
validation
public function logout() { $this->bus->pipeThrough($this->pipesOf('logout'))->dispatchNow(new LogoutJob); return redirect()->route(config('_auth.logout.redirect')); }
php
{ "resource": "" }
q251608
AuthController.register
validation
public function register(RegisterRequest $request) { $this->bus->pipeThrough($this->pipesOf('register'))->dispatchFrom(RegisterJob::class, $request); return redirect()->route(config('_auth.register.redirect'))->withSuccess(trans('auth::register.success')); }
php
{ "resource": "" }
q251609
AuthController.recover
validation
public function recover(RecoverRequest $request) { $this->bus->pipeThrough($this->pipesOf('recover'))->dispatchFrom(RecoverJob::class, $request); return back()->withSuccess(trans('auth::recover.success')); }
php
{ "resource": "" }
q251610
AuthController.reset
validation
public function reset(ResetRequest $request, $token) { $this->bus->pipeThrough($this->pipesOf('reset'))->dispatchFrom(ResetJob::class, $request, compact('token')); return redirect()->route('login.index')->withSuccess(trans('auth::reset.success')); }
php
{ "resource": "" }
q251611
WP_Register.add
validation
public static function add( $type, $data = [] ) { $is_admin = is_admin(); if ( self::validate( $type, $data, $is_admin ) ) { $hook = $is_admin ? 'admin_enqueue_scripts' : 'wp_enqueue_scripts'; $method = __CLASS__ . "::add_{$type}s"; if ( has_action( $hook, $method ) === false ) { add_action( $hook, $method ); } return true; } return false; }
php
{ "resource": "" }
q251612
WP_Register.add_scripts
validation
public static function add_scripts() { self::look_if_process_files( 'script' ); foreach ( self::$data['script'] as $data ) { $params = [ 'plugin_url' => defined( 'WP_PLUGIN_URL' ) ? WP_PLUGIN_URL . '/' : '', 'nonce' => wp_create_nonce( $data['name'] ), ]; $data['params'] = array_merge( $data['params'], $params ); wp_register_script( $data['name'], $data['url'], $data['deps'], $data['version'], $data['footer'] ); wp_enqueue_script( $data['name'] ); wp_localize_script( $data['name'], $data['name'], $data['params'] ); } }
php
{ "resource": "" }
q251613
WP_Register.add_styles
validation
public static function add_styles() { self::look_if_process_files( 'style' ); foreach ( self::$data['style'] as $data ) { wp_register_style( $data['name'], $data['url'], $data['deps'], $data['version'], $data['media'] ); wp_enqueue_style( $data['name'] ); } }
php
{ "resource": "" }
q251614
WP_Register.unify
validation
public static function unify( $id, $params, $minify = '' ) { self::$id = $id; self::$unify = $params; self::$minify = $minify; return true; }
php
{ "resource": "" }
q251615
WP_Register.remove
validation
public static function remove( $type, $name ) { if ( isset( self::$data[ $type ][ $name ] ) ) { unset( self::$data[ $type ][ $name ] ); } return true; }
php
{ "resource": "" }
q251616
WP_Register.validate
validation
protected static function validate( $type, $data, $admin ) { $place = ( isset( $data['place'] ) ) ? $data['place'] : 'front'; $place = $admin && 'admin' == $place || ! $admin && 'front' == $place; if ( ! $place || self::set_params( $type, $data ) === false ) { return false; } return true; }
php
{ "resource": "" }
q251617
WP_Register.look_if_process_files
validation
protected static function look_if_process_files( $type ) { if ( is_string( self::$unify ) || isset( self::$unify[ "{$type}s" ] ) ) { return self::unify_files( self::prepare_files( $type ) ); } }
php
{ "resource": "" }
q251618
WP_Register.prepare_files
validation
protected static function prepare_files( $type ) { $params['type'] = $type; $params['routes'] = self::get_routes_to_folder( $type ); self::get_processed_files(); foreach ( self::$data[ $type ] as $id => $file ) { $path = self::get_path_from_url( $file['url'] ); $params['files'][ $id ] = basename( $file['url'] ); $params['urls'][ $id ] = $file['url']; $params['paths'][ $id ] = $path; if ( is_file( $path ) && self::is_modified_file( $path ) ) { unset( $params['urls'][ $id ] ); continue; } $path = $params['routes']['path'] . $params['files'][ $id ]; if ( is_file( $path ) ) { if ( self::is_modified_hash( $file['url'], $path ) ) { continue; } $params['paths'][ $id ] = $path; } elseif ( self::is_external_url( $file['url'] ) ) { continue; } unset( $params['urls'][ $id ] ); } return $params; }
php
{ "resource": "" }
q251619
WP_Register.get_routes_to_folder
validation
protected static function get_routes_to_folder( $type ) { $url = isset( self::$unify[ "{$type}s" ] ) ? self::$unify[ "{$type}s" ] : self::$unify; return [ 'url' => $url, 'path' => self::get_path_from_url( $url ), ]; }
php
{ "resource": "" }
q251620
WP_Register.is_modified_file
validation
protected static function is_modified_file( $filepath ) { $actual = filemtime( $filepath ); $last = isset( self::$files[ $filepath ] ) ? self::$files[ $filepath ] : 0; if ( $actual !== $last ) { self::$files[ $filepath ] = $actual; self::$changes = true; return self::$changes; } return false; }
php
{ "resource": "" }
q251621
WP_Register.is_modified_hash
validation
protected static function is_modified_hash( $url, $path ) { if ( self::is_external_url( $url ) ) { if ( sha1_file( $url ) !== sha1_file( $path ) ) { self::$changes = true; return self::$changes; } } return false; }
php
{ "resource": "" }
q251622
WP_Register.unify_files
validation
protected static function unify_files( $params, $data = '' ) { $type = $params['type']; $routes = $params['routes']; $extension = ( 'style' == $type ) ? '.css' : '.js'; $hash = sha1( implode( '', $params['files'] ) ); $min_file = $routes['path'] . $hash . $extension; if ( ! is_file( $min_file ) || self::$changes ) { foreach ( $params['paths'] as $id => $path ) { if ( isset( $params['urls'][ $id ] ) ) { $url = $params['urls'][ $id ]; $path = $routes['path'] . $params['files'][ $id ]; $data .= self::save_external_file( $url, $path ); } $data .= file_get_contents( $path ); } $data = ( self::$minify ) ? self::compress_files( $data ) : $data; self::save_file( $min_file, $data ); } self::set_processed_files(); return self::set_new_params( $type, $hash, $routes['url'], $extension ); }
php
{ "resource": "" }
q251623
WP_Register.save_external_file
validation
protected static function save_external_file( $url, $path ) { $data = file_get_contents( $url ); return ( $data && self::save_file( $path, $data ) ) ? $data : ''; }
php
{ "resource": "" }
q251624
WP_Register.compress_files
validation
protected static function compress_files( $content ) { $var = array( "\r\n", "\r", "\n", "\t", ' ', ' ', ' ' ); $content = preg_replace( '!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $content ); $content = str_replace( $var, '', $content ); $content = str_replace( '{ ', '{', $content ); $content = str_replace( ' }', '}', $content ); $content = str_replace( '; ', ';', $content ); return $content; }
php
{ "resource": "" }
q251625
WP_Register.set_new_params
validation
protected static function set_new_params( $type, $hash, $url, $extension ) { $data = [ 'name' => self::$id, 'url' => $url . $hash . $extension, 'deps' => self::unify_params( $type, 'deps' ), 'version' => self::unify_params( $type, 'version', '1.0.0' ), ]; switch ( $type ) { case 'style': $data['media'] = self::unify_params( $type, 'media', 'all' ); break; case 'script': $data['params'] = self::unify_params( $type, 'params' ); $data['footer'] = self::unify_params( $type, 'footer', false ); $data['params']['nonce'] = wp_create_nonce( self::$id ); break; default: } self::$data[ $type ] = [ $data['name'] => $data ]; return true; }
php
{ "resource": "" }
q251626
WP_Register.unify_params
validation
protected static function unify_params( $type, $field, $default = '' ) { $data = array_column( self::$data[ $type ], $field ); switch ( $field ) { case 'media': case 'footer': case 'version': foreach ( $data as $key => $value ) { if ( $data[0] !== $value ) { return $default; } } return ( isset( $data[0] ) && $data[0] ) ? $data[0] : $default; default: $params = []; foreach ( $data as $key => $value ) { $params = array_merge( $params, $value ); } return array_unique( $params ); } }
php
{ "resource": "" }
q251627
OriginalInitCommand.createInitializer
validation
protected function createInitializer() { $initializer = new Initializer(); $initializer->addTemplate('Common', new CommonTemplate()); $initializer->addTemplate('Laravel', new LaravelTemplate()); $initializer->addTemplate('Symfony', new SymfonyTemplate()); $initializer->addTemplate('Yii', new YiiTemplate()); $initializer->addTemplate('Yii2 Basic App', new Yii2BasicAppTemplate()); $initializer->addTemplate('Yii2 Advanced App', new Yii2AdvancedAppTemplate()); return $initializer; }
php
{ "resource": "" }
q251628
Calgamo.newApp
validation
public function newApp() : ApplicationInterface { $app = new CalgamoApplication($this->filesystem); $app->requireModule(CalgamoLogExceptionHandlerModule::class); $app->requireModule(CalgamoRouterModule::class); $app->requireModule(CalgamoDiModule::class); $app->requireModule(Wa72SimpleLoggerModule::class); return $app; }
php
{ "resource": "" }
q251629
ValueTrait.handleTtl
validation
protected function handleTtl($key, $expireSetTs, $expireSec) { $ttl = $expireSetTs + $expireSec - time(); if ($ttl <= 0) { $this->getClient()->delete($key); throw new KeyNotFoundException(); } return $ttl; }
php
{ "resource": "" }
q251630
Document.loadFile
validation
public static function loadFile( $xmlFile ) { // Check if user exists at all if ( !is_file( $xmlFile ) || !is_readable( $xmlFile ) ) { throw new NoSuchFileException( $xmlFile ); } return self::parseXml( $xmlFile ); }
php
{ "resource": "" }
q251631
Document.loadString
validation
public static function loadString( $xmlString ) { $xmlFile = tempnam( self::getSysTempDir(), 'xml_' ); file_put_contents( $xmlFile, $xmlString ); $xml = self::parseXml( $xmlFile ); unlink( $xmlFile ); return $xml; }
php
{ "resource": "" }
q251632
Document.getSysTempDir
validation
protected static function getSysTempDir() { if ( function_exists( 'sys_get_temp_dir' ) ) { return sys_get_temp_dir(); } else if ( $tmp = getenv( 'TMP' ) ) { return $tmp; } else if ( $tmp = getenv( 'TEMP' ) ) { return $tmp; } else if ( $tmp = getenv( 'TMPDIR' ) ) { return $tmp; } return '/tmp'; }
php
{ "resource": "" }
q251633
Document.parseXml
validation
protected static function parseXml( $xmlFile ) { $reader = new \XMLReader(); // Use custom error handling to suppress warnings and errors during // parsing. $libXmlErrors = libxml_use_internal_errors( true ); // Try to open configuration file, and throw parsing exception if // something fails. $errors = array(); // Just open, errors will not occure before actually reading. if ( !$reader->open( $xmlFile ) ) { throw new XmlParserException( $xmlFile, array() ); } // Current node, processed. Start with a reference to th root node. $current = $root = new Document(); // Stack of parents for the current node. We store this list, because // we do not want to store a parent node reference in the nodes, as // this breaks with var_export'ing those structures. $parents = array( $root ); // Start processing the XML document // // The read method may issue warning, even if // libxml_use_internal_errors was set to true. That sucks, and we need // to use the @ here... while( @$reader->read() ) { switch( $reader->nodeType ) { case \XMLReader::ELEMENT: // A new element, which results in a new configuration node as // a child of the current node // // Get name of new element $nodeName = $reader->name; // We create a new object, so append the current node as // future parent node to the parent stack. array_push( $parents, $current ); // Create new child and reference node as current working // node $current = $current->$nodeName = new Node(); // After reading the elements we need to know about this // for further progressing $emptyElement = $reader->isEmptyElement; // Process elements attributes, if available if ( $reader->hasAttributes ) { // Read all attributes and store their values in the // current configuration node while( $reader->moveToNextAttribute() ) { $current[$reader->name] = $reader->value; } } if ( !$emptyElement ) { // We only break for non empty elements. // // For empty elements the element may also be counted // as a closing tag, so that we want also process the // next case statement. break; } case \XMLReader::END_ELEMENT: // At the end of a element set the current pointer back to its // parent // // Pop new current node from parents stack $current = array_pop( $parents ); break; case \XMLReader::TEXT: case \XMLReader::CDATA: // Text and CData node are added as node content. // // Append string, in case several text or Cdata nodes exist // in one node $current->setContent( (string) $current . $reader->value ); break; // Everything else can be ignored for now.. } } // Check if errors occured while reading configuration if ( count( $errors = libxml_get_errors() ) ) { // Reset libxml error handling to old state libxml_use_internal_errors( $libXmlErrors ); libxml_clear_errors(); throw new XmlParserException( $xmlFile, $errors ); } // Reset libxml error handling to old state libxml_use_internal_errors( $libXmlErrors ); return $root->skipRoot(); }
php
{ "resource": "" }
q251634
SyncStorage.isValidOperation
validation
private function isValidOperation($operationType) { $operationType = strtoupper($operationType); return in_array( $operationType, [ ActionTypes::CREATE, ActionTypes::UPDATE, ActionTypes::DELETE, ] ); }
php
{ "resource": "" }
q251635
ModifyEventListener.transform
validation
protected function transform(DocumentInterface $document, $entity, $skip = null) { $entityMethods = get_class_methods($entity); $documentMethods = get_class_methods($document); if ($skip === null) { $skip = $this->getCopySkipFields(); } foreach ($entityMethods as $method) { if (strpos($method, 'get') !== 0) { continue; } $property = substr($method, 3); if (in_array(lcfirst($property), $skip)) { continue; } $setter = 'set' . $property; if (in_array($setter, $documentMethods)) { $document->{$setter}($entity->{$method}()); } } }
php
{ "resource": "" }
q251636
AbstractExtractor.getShopIds
validation
protected function getShopIds() { $shopIds = []; try { $shops = $this->container->getParameter('ongr_connections.shops'); } catch (InvalidArgumentException $e) { $shops = []; } foreach ($shops as $shop) { $shopIds[] = $shop['shop_id']; } return $shopIds; }
php
{ "resource": "" }
q251637
LoadClassMetadataListener.loadClassMetadata
validation
public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs) { if (empty($this->replacements)) { return; } /** @var ClassMetadataInfo $metadata */ $metadata = $eventArgs->getClassMetadata(); // Handle table name. $tableName = $metadata->getTableName(); if ($tableName) { $metadata->setPrimaryTable( [ 'name' => $this->doReplacement($tableName), ] ); } // Handle fields AKA columns. foreach ($metadata->getFieldNames() as $fieldName) { $mapping = $metadata->getFieldMapping($fieldName); foreach ($mapping as $key => $value) { if (is_string($value)) { $mapping[$key] = $this->doReplacement($value); } } $metadata->setAttributeOverride($fieldName, $mapping); } // Handle associations AKA foreign keys. $associationMappings = $metadata->getAssociationMappings(); foreach ($metadata->getAssociationNames() as $fieldName) { if (isset($associationMappings[$fieldName])) { $associationMapping = $associationMappings[$fieldName]; if (isset($associationMapping['joinColumns'])) { foreach ($associationMapping['joinColumns'] as $key => $joinColumn) { $associationMapping['joinColumns'][$key]['name'] = $this->doReplacement($joinColumn['name']); $associationMapping['joinColumns'][$key]['referencedColumnName'] = $this->doReplacement( $joinColumn['referencedColumnName'] ); } $metadata->setAssociationOverride($fieldName, $associationMapping); } } } // Handle discriminator. if (count($metadata->discriminatorMap)) { $this->processDiscriminatorMap($metadata); } }
php
{ "resource": "" }
q251638
LoadClassMetadataListener.processDiscriminatorMap
validation
protected function processDiscriminatorMap(ClassMetadataInfo $metadata) { $newMap = []; foreach ($metadata->discriminatorMap as $mapId => $mappedEntityName) { $newKey = $this->doReplacement($mapId); $newMap[$newKey] = $mappedEntityName; } $metadata->discriminatorMap = $newMap; }
php
{ "resource": "" }
q251639
LoadClassMetadataListener.doReplacement
validation
protected function doReplacement($inputString) { if (is_string($inputString)) { $inputString = str_replace( array_keys($this->replacements), array_values($this->replacements), $inputString ); } return $inputString; }
php
{ "resource": "" }
q251640
AbstractStartServiceCommand.start
validation
protected function start(InputInterface $input, OutputInterface $output, $serviceClass, $prefix) { $benchmark = new CommandBenchmark($output); $benchmark->start(); /** @var PipelineStarter $service */ $service = $this->getContainer()->get($serviceClass); $factory = $service->getPipelineFactory(); $factory->setProgressBar(new ProgressBar($output)); $service->startPipeline($prefix, $input->getArgument('target')); $benchmark->finish(); }
php
{ "resource": "" }
q251641
ItemSkipper.skip
validation
public static function skip(ItemPipelineEvent $event, $reason = '') { $itemSkip = new ItemSkip(); $itemSkip->setReason($reason); $event->setItemSkip($itemSkip); $event->stopPropagation(); }
php
{ "resource": "" }
q251642
Pipeline.countSourceItems
validation
private function countSourceItems($sources) { $count = 0; foreach ($sources as $source) { $count += count($source); } return $count; }
php
{ "resource": "" }
q251643
DefaultApplicationFactory.createApplication
validation
public function createApplication(string $app_type, FileSystemInterface $filesystem) : ApplicationInterface { switch($app_type) { case ApplicationType::SHELL: return (new Calgamo($filesystem)) ->newApp() ->requireModule(CalgamoShellRequestModule::class); case ApplicationType::CRON: return (new Calgamo($filesystem)) ->newApp() ->requireModule(CalgamoShellRequestModule::class); break; case ApplicationType::HTTP: return (new Calgamo($filesystem)) ->newApp() ->requireModule('zend.request'); break; case ApplicationType::REST: return (new Calgamo($filesystem)) ->newApp() ->requireModule(ZendRequestModule::class) ->requireModule(CalgamoRestApiModule::class); break; } return new NullApplication(); }
php
{ "resource": "" }
q251644
AbstractConsumeEventListener.onConsume
validation
public function onConsume(ItemPipelineEvent $event) { if ($event->getItemSkip()) { $this->skip($event); } else { $this->consume($event); } }
php
{ "resource": "" }
q251645
PairStorage.get
validation
public function get($key) { $pair = $this->repository->find($key); return $pair ? $pair->getValue() : null; }
php
{ "resource": "" }
q251646
PairStorage.set
validation
public function set($key, $value) { $pair = $this->repository->find($key); if ($pair === null) { $pair = new Pair(); $pair->setId($key); } $pair->setValue($value); $this->save($pair); return $pair; }
php
{ "resource": "" }
q251647
PairStorage.remove
validation
public function remove($key) { $pair = $this->repository->find($key); if ($pair !== null) { $this->repository->remove($pair->getId()); $this->manager->flush(); $this->manager->refresh(); } }
php
{ "resource": "" }
q251648
PairStorage.save
validation
private function save(Pair $pair) { $this->manager->persist($pair); $this->manager->commit(); $this->manager->refresh(); }
php
{ "resource": "" }
q251649
UrlInvalidatorService.addDocumentParameter
validation
public function addDocumentParameter($field, $value) { $this->documentParamCache[md5($value . $field)] = [$field, $value]; }
php
{ "resource": "" }
q251650
UrlInvalidatorService.getUrlsByDocumentParameter
validation
protected function getUrlsByDocumentParameter() { if (count($this->documentParamCache) < 1) { return []; } $urls = []; $query = new Query(); $queryTerms = []; foreach ($this->documentParamCache as $param) { $queryTerms[$param[0]][] = $param[1]; } foreach ($queryTerms as $field => $values) { $termQuery = new TermQuery($field, $values); $query->addQuery($termQuery, 'should'); } $limitFilter = new LimitFilter(count($this->documentParamCache)); $repository = $this->manager->getRepository('MultiModel'); $search = $repository->createSearch()->addQuery($query) ->addFilter($limitFilter); $documents = $repository->execute($search); // Add all category urls to invalidate. foreach ($documents as $document) { if (is_array($document->url)) { foreach ($document->url as $url) { $urls[] = $url['url']; } } } array_walk($urls, [$this, 'addWildcard']); $this->addUrls($urls); return $urls; }
php
{ "resource": "" }
q251651
UrlInvalidatorService.createUrlsTempFile
validation
public function createUrlsTempFile() { $hash = md5(microtime(true)); $links = array_merge($this->getUrls(), $this->getUrlsByDocumentParameter()); $urlsFile = "/tmp/urls_{$hash}.txt"; $urls = []; foreach ($links as $url) { $separator = ($url[0] !== '/') ? '/' : ''; $urls[] = $this->baseUrl . $separator . $url; } file_put_contents($urlsFile, implode(PHP_EOL, $urls)); return $urlsFile; }
php
{ "resource": "" }
q251652
UrlInvalidatorService.invalidate
validation
public function invalidate() { $script = escapeshellcmd($this->rootDir . "/../{$this->cacheScript}"); $urlsFile = escapeshellarg($this->createUrlsTempFile()); $curlTimeout = escapeshellarg($this->curlTimeout); // Execute in background. $process = new Process(sprintf('%s %s %s', $script, $urlsFile, $curlTimeout)); $process->start(); $this->resetCache(); return $urlsFile; }
php
{ "resource": "" }
q251653
UrlInvalidatorService.loadUrlsFromDocument
validation
public function loadUrlsFromDocument($type, SeoAwareInterface $document) { if ($this->invalidateSeoUrls) { // Default behavior. $urls = $document->getUrls(); if (is_array($urls) || $urls instanceof \Traversable) { /** @var UrlObject $url */ foreach ($urls as $url) { $this->addUrl($url->getUrl()); } } } // Special behavior from bundles. foreach ($this->urlCollectors as $collector) { $this->addUrls($collector->getDocumentUrls($type, $document, $this->router)); $this->addMultipleDocumentParameters($collector->getDocumentParameters($type, $document)); } }
php
{ "resource": "" }
q251654
UrlInvalidatorService.loadUrlsByType
validation
public function loadUrlsByType($type) { foreach ($this->urlCollectors as $collector) { $this->addUrls($collector->getUrlsByType($type, $this->router)); } }
php
{ "resource": "" }
q251655
TableManager.createTable
validation
public function createTable($connection = null) { $connection = $connection ? : $this->connection; $schemaManager = $connection->getSchemaManager(); if ($schemaManager->tablesExist([$this->tableName])) { return null; } $table = new Table($this->tableName); $this->buildTable($table); $schemaManager->createTable($table); return true; }
php
{ "resource": "" }
q251656
TableManager.updateTable
validation
public function updateTable($connection = null) { $connection = $connection ? : $this->connection; $schemaManager = $connection->getSchemaManager(); if (!$schemaManager->tablesExist([$this->tableName])) { return false; } $table = new Table($this->tableName); $this->buildTable($table); $oldTable = $schemaManager->listTableDetails($this->tableName); $comparator = new Comparator(); $diff = $comparator->diffTable($oldTable, $table); if (!$diff) { return null; } $schemaManager->alterTable($diff); return true; }
php
{ "resource": "" }
q251657
TableManager.addStatusField
validation
protected function addStatusField(Table $table) { if (empty($this->shops)) { $table->addColumn('status', 'boolean', ['default' => 0])->setComment('0-new,1-done'); $table->addIndex(['status']); } else { foreach ($this->shops as $shop) { $fieldName = "status_{$shop}"; $table->addColumn($fieldName, 'boolean', ['default' => 0])->setComment('0-new,1-done'); $table->addIndex([$fieldName]); } } }
php
{ "resource": "" }
q251658
PipelineStarter.startPipeline
validation
public function startPipeline($prefix, $target) { if ($target === null) { $target = 'default'; } $this->getPipelineFactory()->create($prefix . $target)->start(); }
php
{ "resource": "" }
q251659
YamlExtractor.extract
validation
public static function extract($yamlArray, $key, $needed = false) { if (!empty($yamlArray) && array_key_exists($key, $yamlArray)) return $yamlArray[$key]; if ($needed) { throw new \Deployer\Exception\Exception( 'Cannot find the setting: ' . $key . '. This key needs to be given!' ); } return null; // The key was not needed, so continue! }
php
{ "resource": "" }
q251660
YamlExtractor.parse
validation
public static function parse($path) { if (!file_exists($path)) { throw new Exception('The give file ' . $path . ' doesn\'t exist.'); } return Yaml::parse(file_get_contents($path)); }
php
{ "resource": "" }
q251661
PipelineFactory.create
validation
public function create($pipelineName, $listeners = []) { $listeners = array_merge( [ 'sources' => [], 'modifiers' => [], 'consumers' => [], ], $listeners ); $className = $this->getClassName(); /** @var PipelineInterface $pipeline */ $pipeline = new $className($pipelineName); if (!$pipeline instanceof Pipeline) { throw new \InvalidArgumentException('Pipeline class\' name must implement PipelineInterface'); } $pipeline->setProgressBar($this->getProgressBar()); $dispatcher = $this->getDispatcher(); $pipeline->setDispatcher($dispatcher); foreach ($listeners['consumers'] as &$listener) { if ($listener === self::CONSUMER_RETURN) { $listener = function (ItemPipelineEvent $event) { $event->setOutput($event->getItem()); }; } } $registerListener = function ($key, $suffix) use ($listeners, $dispatcher, $pipeline) { foreach ($listeners[$key] as $listener) { $dispatcher->addListener( $pipeline->getEventName($suffix), $listener ); } }; $registerListener('sources', Pipeline::EVENT_SUFFIX_SOURCE); $registerListener('modifiers', Pipeline::EVENT_SUFFIX_MODIFY); $registerListener('consumers', Pipeline::EVENT_SUFFIX_CONSUME); return $pipeline; }
php
{ "resource": "" }
q251662
ExtractionDescriptor.addToUpdateFields
validation
public function addToUpdateFields($updateField, $updateType = null) { $this->updateFields[$updateField] = ['priority' => isset($updateType) ? $updateType : $this->defaultJobType]; }
php
{ "resource": "" }
q251663
ExtractionDescriptor.addToInsertList
validation
public function addToInsertList($key, $value, $isString = true) { $this->sqlInsertList[$key] = [ 'value' => $value, 'string' => $isString, ]; }
php
{ "resource": "" }
q251664
ExtractionDescriptor.setTriggerType
validation
public function setTriggerType($type) { if (!array_key_exists($type, $this->validTypes)) { throw new \InvalidArgumentException('The type MUST be one of:' . implode(',', $this->validTypes)); } $this->type = $this->validTypes[$type]; $this->typeAlias = $type; }
php
{ "resource": "" }
q251665
NcipService.parseXml
validation
public function parseXml($xml) { if (is_null($xml)) { return null; } $xml = new QuiteSimpleXMLElement($xml); $xml->registerXPathNamespaces($this->namespaces); return $xml; }
php
{ "resource": "" }
q251666
Emitter.headers
validation
private function headers(ResponseInterface $response): void { if (!headers_sent()) { foreach ($response->getHeaders() as $name => $values) { $cookie = stripos($name, 'Set-Cookie') === 0 ? false : true; foreach ($values as $value) { header(sprintf('%s: %s', $name, $value), $cookie); $cookie = false; } } header(sprintf( 'HTTP/%s %s %s', $response->getProtocolVersion(), $response->getStatusCode(), $response->getReasonPhrase() ), true, $response->getStatusCode()); } }
php
{ "resource": "" }
q251667
Emitter.body
validation
private function body(ResponseInterface $response): ResponseInterface { if (!in_array($response->getStatusCode(), $this->responseIsEmpty)) { $stream = $response->getBody(); if ($stream->isSeekable()) { $stream->rewind(); } $bufferLenght = (!$response->getHeaderLine('Content-Length')) ? $stream->getSize() : $response->getHeaderLine('Content-Length'); if (isset($bufferLenght)) { $lengthToRead = $bufferLenght; while ($lengthToRead > 0 && !$stream->eof()) { $data = $stream->read(min($this->sizeLimit, $lengthToRead)); echo $data; $lengthToRead -= strlen($data); } } else { while (!$stream->eof()) { echo $stream->read($this->size); } } } return $response; }
php
{ "resource": "" }
q251668
ONGRConnectionsExtension.initShops
validation
private function initShops(ContainerBuilder $container, array $config) { $activeShop = !empty($config['active_shop']) ? $config['active_shop'] : null; if ($activeShop !== null && !isset($config['shops'][$activeShop])) { throw new LogicException( "Parameter 'ongr_connections.active_shop' must be set to one" . "of the values defined in 'ongr_connections.shops'." ); } $container->setParameter('ongr_connections.active_shop', $activeShop); $container->setParameter('ongr_connections.shops', $config['shops']); $container->setDefinition( 'ongr_connections.shop_service', new Definition( 'ONGR\ConnectionsBundle\Service\ShopService', [ $activeShop, $config['shops'], ] ) ); }
php
{ "resource": "" }
q251669
ONGRConnectionsExtension.initSyncStorage
validation
private function initSyncStorage(ContainerBuilder $container, array $config) { $availableStorages = array_keys($config['sync']['sync_storage']); $syncStorageStorage = current($availableStorages); if (empty($syncStorageStorage)) { throw new LogicException('Data synchronization storage must be set.'); } $syncStorageStorageConfig = $config['sync']['sync_storage'][$syncStorageStorage]; switch ($syncStorageStorage) { case SyncStorage::STORAGE_MYSQL: $this->initSyncStorageForMysql($container, $syncStorageStorageConfig); break; default: throw new LogicException("Unknown storage is set: {$syncStorageStorage}"); } }
php
{ "resource": "" }
q251670
ONGRConnectionsExtension.initSyncStorageForMysql
validation
private function initSyncStorageForMysql(ContainerBuilder $container, array $config) { // Initiate MySQL storage manager. $doctrineConnection = sprintf('doctrine.dbal.%s_connection', $config['connection']); $definition = $container->getDefinition( 'ongr_connections.sync.storage_manager.mysql_storage_manager' ); $definition->setArguments( [ new Reference($doctrineConnection, ContainerInterface::IGNORE_ON_INVALID_REFERENCE), $config['table_name'], ] ); $definition->addMethodCall('setContainer', [new Reference('service_container')]); // Initiate SyncStorage and inject storage manager into it. $container->getDefinition('ongr_connections.sync.sync_storage')->setArguments( [$definition] ); }
php
{ "resource": "" }
q251671
ONGRConnectionsExtension.createPipelines
validation
protected function createPipelines(ContainerBuilder $container, array $config) { foreach ($config['pipelines'] as $pipelineName => $pipelineConfig) { if (!isset($pipelineConfig['shop'])) { $pipelineConfig['shop'] = $container->getParameter('ongr_connections.active_shop'); } $serviceConfig = $this->prepareServiceConfigs($container, $pipelineConfig, $pipelineName); $this->createServices( $container, $pipelineConfig['provide_sources'], $serviceConfig, "data_sync.{$pipelineName}.source", 'onSource' ); $this->createServices( $container, $pipelineConfig['provide_consumers'], $serviceConfig, "data_sync.{$pipelineName}.consume", 'onConsume' ); foreach ($pipelineConfig['types'] as $type => $typeConfig) { $typeServiceConfig = $this->prepareTypeServiceConfigs($serviceConfig, $typeConfig, $type); $serviceList = $this->getServiceList($pipelineName, $type); foreach ($serviceList as $name => $service) { $this->createServices( $container, array_merge($pipelineConfig[$name], $typeConfig[$name]), $typeServiceConfig, $service['tag'], $service['method'] ); } } } }
php
{ "resource": "" }
q251672
ONGRConnectionsExtension.getShopId
validation
protected function getShopId(ContainerBuilder $container, $shop, $name) { $shops = $container->getParameter('ongr_connections.shops'); if (!isset($shops[$shop])) { throw new \InvalidArgumentException('Non existing shop provided for pipeline ' . $name); } return $shops[$shop]['shop_id']; }
php
{ "resource": "" }
q251673
ONGRConnectionsExtension.createServices
validation
protected function createServices(ContainerBuilder $container, $classes, $config, $tag, $method) { if (!is_array($tag)) { $tag = [$tag]; } foreach ($classes as $class) { $methods = $this->getMethods($class); $definition = new Definition($class); $this->setProperties($definition, $config, $methods); $this->setTags($definition, $tag, $method); $container->setDefinition($this->getServiceName($tag[0]), $definition); } }
php
{ "resource": "" }
q251674
ONGRConnectionsExtension.prepareServiceConfigs
validation
protected function prepareServiceConfigs(ContainerBuilder $container, $pipelineConfig, $pipelineName) { return array_merge( $pipelineConfig['config'], [ 'doctrineManager' => $pipelineConfig['doctrineManager'], 'elasticsearchManager' => $pipelineConfig['elasticsearchManager'], 'sync_storage' => $pipelineConfig['sync_storage'], 'diff_provider' => $pipelineConfig['diff_provider'], 'extractor' => $pipelineConfig['extractor'], 'chunk_size' => $pipelineConfig['chunk_size'], 'shop' => $pipelineConfig['shop'], 'shop_id' => $this->getShopId($container, $pipelineConfig['shop'], $pipelineName), ] ); }
php
{ "resource": "" }
q251675
ONGRConnectionsExtension.prepareTypeServiceConfigs
validation
protected function prepareTypeServiceConfigs($serviceConfig, $typeConfig, $type) { return array_merge( $serviceConfig, $typeConfig['config'], [ 'entity_class' => $typeConfig['entity_class'], 'document_class' => $typeConfig['document_class'], 'document_type' => $type, ] ); }
php
{ "resource": "" }
q251676
NcipConnector.post
validation
public function post($request) { if ($request instanceof Request) { $request = $request->xml(); } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->url); if ($this->user_agent != null) { curl_setopt($ch, CURLOPT_USERAGENT, $this->user_agent); } curl_setopt($ch, CURLOPT_HEADER, 0); // no headers in the output curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return instead of output curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $request); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-type: application/xml; charset=utf-8', )); $response = curl_exec($ch); curl_close($ch); if (empty($response)) { return null; } return $response; }
php
{ "resource": "" }
q251677
CalgamoLoggerAdapter.channel
validation
public function channel(string $channel_id) : LoggerChannelInterface { $logger = $this->log_manager->get($channel_id); if (!$logger){ return new NullLoggerChannel(); } return new CalgamoLoggerChannelAdapter($logger); }
php
{ "resource": "" }
q251678
com_meego_planet_injector.inject_template
validation
public function inject_template(midgardmvc_core_request $request) { // Replace the default MeeGo sidebar with our own $route = $request->get_route(); $route->template_aliases['content-sidebar'] = 'cmp-show-sidebar'; $route->template_aliases['main-menu'] = 'cmp-show-main_menu'; midgardmvc_core::get_instance()->head->add_link ( array ( 'rel' => 'stylesheet', 'type' => 'text/css', 'href' => MIDGARDMVC_STATIC_URL . '/com_meego_planet/planet.css' ) ); }
php
{ "resource": "" }
q251679
Node.offsetSet
validation
public function offsetSet( $attributeName, $attribute ) { if ( !is_string( $attributeName ) || !is_string( $attribute ) ) { // We only accept strings for name AND content throw new ValueException( $attribute, 'string' ); } $this->attributes[$attributeName] = $attribute; }
php
{ "resource": "" }
q251680
BinlogParser.nextBufferLine
validation
protected function nextBufferLine() { $query = $this->parseQuery(); if (!empty($query)) { $this->buffer[$this->key][self::PARAM_QUERY] = $query; } else { $this->buffer[$this->key] = false; } }
php
{ "resource": "" }
q251681
BinlogParser.parseQuery
validation
protected function parseQuery() { if (empty($this->lastLine) || $this->lastLineType != self::LINE_TYPE_QUERY) { $this->getNextLine(self::LINE_TYPE_QUERY); if (empty($this->lastLine)) { return false; } } $buffer = $this->handleStart($this->lastLine); // Associate last date with current query. $this->buffer[$this->key][self::PARAM_DATE] = $this->lastDateTime; // Associate last log position with current query. $this->buffer[$this->key][self::PARAM_POSITION] = $this->lastLogPosition; $this->getNextLine(self::LINE_TYPE_QUERY); if ($buffer['type'] == ActionTypes::DELETE || $buffer['type'] === ActionTypes::UPDATE) { $buffer['where'] = $this->handleStatement($this->lastLine, self::STATEMENT_TYPE_WHERE); } if ($buffer['type'] == ActionTypes::CREATE || $buffer['type'] === ActionTypes::UPDATE) { $buffer['set'] = $this->handleStatement($this->lastLine, self::STATEMENT_TYPE_SET); } return $buffer; }
php
{ "resource": "" }
q251682
BinlogParser.getLineType
validation
protected function getLineType($line) { if (preg_match('/^###\s+@[0-9]+=.*$/', $line)) { return self::LINE_TYPE_PARAM; } elseif (preg_match('/^###/', $line)) { return self::LINE_TYPE_QUERY; } elseif (preg_match('/^#[0-9]/', $line)) { return self::LINE_TYPE_META; } elseif (preg_match('/Errcode|ERROR/', $line)) { return self::LINE_TYPE_ERROR; } return self::LINE_TYPE_UNKNOWN; }
php
{ "resource": "" }
q251683
BinlogParser.getNewPipe
validation
protected function getNewPipe() { $cmd = 'mysqlbinlog ' . escapeshellarg($this->logDir . '/' . $this->baseName) . '.[0-9]*'; if ($this->from !== null) { if ($this->startType == self::START_TYPE_DATE) { $cmd .= ' --start-datetime=' . escapeshellarg($this->from->format('Y-m-d H:i:s')); } elseif ($this->startType == self::START_TYPE_POSITION) { $cmd .= ' --start-position=' . escapeshellarg($this->from); } } $cmd .= " --base64-output=DECODE-ROWS -v 2>&1 | grep -E '###|#[0-9]|Errcode|ERROR'"; $this->pipe = popen($cmd, 'r'); if (empty($this->pipe)) { throw new \RuntimeException('Error while executing mysqlbinlog'); } }
php
{ "resource": "" }
q251684
BinlogParser.handleStart
validation
protected function handleStart($line) { if (preg_match('/^(INSERT INTO|UPDATE|DELETE FROM)\s+`?(.*?)`?\.`?(.*?)`?$/', $line, $part)) { return [ 'type' => $this->detectQueryType($part[1]), 'table' => $part[3], ]; } throw new \UnexpectedValueException("Expected a statement, got {$line}"); }
php
{ "resource": "" }
q251685
BinlogParser.handleStatement
validation
protected function handleStatement($line, $type) { if (!preg_match("/^{$type}$/", $line)) { throw new \UnexpectedValueException("Expected a {$type} statement, got {$line}"); } $params = []; $param = $this->handleParam(); while ($param !== null) { $params = $params + $param; $param = $this->handleParam(); } return $params; }
php
{ "resource": "" }
q251686
BinlogParser.handleParam
validation
protected function handleParam() { if (preg_match('/^@([0-9]+)=(.*)$/', $this->getNextLine(self::LINE_TYPE_ANY), $part)) { $paramValue = trim($part[2], "'"); return [$part[1] => $paramValue]; } return null; }
php
{ "resource": "" }
q251687
BinlogParser.detectQueryType
validation
protected function detectQueryType($type) { switch ($type) { case 'INSERT INTO': return ActionTypes::CREATE; case 'UPDATE': return ActionTypes::UPDATE; case 'DELETE FROM': return ActionTypes::DELETE; default: throw new \UnexpectedValueException("Unknown statement of type {$type}"); } }
php
{ "resource": "" }
q251688
Webhook.post
validation
public function post(Payload $payload, $endpoint) { if (! Type::isValidWebhookType($payload->getAction())) { throw new \Exception(sprintf('Webhook "%s" isn\'t valid', $payload->getAction())); } $requestContent = [ 'headers' => ['Content-Type' => 'application/json'], 'body' => json_encode($payload), 'timeout' => self::DEFAULT_REQUEST_TIMEOUT ]; return $this->guzzleClient->post($endpoint, $requestContent); }
php
{ "resource": "" }
q251689
AbstractPipe.callIfExistsAndEnabled
validation
private function callIfExistsAndEnabled($method, array $parameters = []) { if( ! $this->isEnabled()) return; if(method_exists($this, $method) && $this->{"{$method}IsEnabled"}()) { $this->container->call([$this, $method], $parameters); } }
php
{ "resource": "" }
q251690
DefaultConfigurator.load
validation
public function load($config) { if (is_string($config) and file_exists($config)) { $config = include $config; } if ( ! is_array($config)) { $msg = 'Failed to load configuration data'; throw new ConfigurationException($msg); } return new Configuration($config); }
php
{ "resource": "" }
q251691
KeyTrait.delete
validation
public function delete($key) { try { $this->get($key); } catch (KeyNotFoundException $e) { return false; } return $this->getClient()->delete($key); }
php
{ "resource": "" }
q251692
KeyTrait.getTtl
validation
public function getTtl($key) { $getResult = $this->getValue($key); $unserialized = @unserialize($getResult); if (!Util::hasInternalExpireTime($unserialized)) { throw new \Exception('Cannot retrieve ttl'); } return $this->handleTtl($key, $unserialized['ts'], $unserialized['s']); }
php
{ "resource": "" }
q251693
WithDefault.format
validation
public function format(string $question, string $default = null): string { if($default != '') { $default = sprintf('[%s]', $default); } return trim($question . $default) . sprintf('%s ', $this->getDelimiter()); }
php
{ "resource": "" }
q251694
EloquentUserRepository.assignResetToken
validation
public function assignResetToken($token, $email) { $user = $this->user->whereEmail($email)->first(); $user->reset_token = $token; $user->save(); }
php
{ "resource": "" }
q251695
EloquentUserRepository.resetPassword
validation
public function resetPassword($user, $password) { $user->password = $password; $user->reset_token = null; $user->save(); }
php
{ "resource": "" }
q251696
AbstractImportConsumeEventListener.consume
validation
public function consume(ItemPipelineEvent $event) { if (!$this->setItem($event)) { return; } $this->log( sprintf( 'Start update single document of type %s id: %s', get_class($this->getItem()->getDocument()), $this->getItem()->getDocument()->getId() ) ); if (!$this->persistDocument()) { return; }; $this->log('End an update of a single document.'); }
php
{ "resource": "" }
q251697
AbstractImportConsumeEventListener.setItem
validation
protected function setItem(ItemPipelineEvent $event) { /** @var AbstractImportItem $tempItem */ $tempItem = $event->getItem(); if (!$tempItem instanceof $this->importItemClass) { $this->log("Item provided is not an {$this->importItemClass}", LogLevel::ERROR); return false; } $this->importItem = $tempItem; return true; }
php
{ "resource": "" }
q251698
AbstractQuantity.to
validation
public function to(Uom $uom) { // Get the conversion factor as a Fraction $conversionFactor = Uom::getConversionFactor( $this->getUom(), $uom ); // Multiply the amount by the conversion factor and create a new // Weight with the new Unit return new static( $this->getAmount()->multiply($conversionFactor), $uom ); }
php
{ "resource": "" }
q251699
NotEmpty.validate
validation
public function validate(string $answer): string { if(trim((string) $answer) === '') { throw new \RuntimeException(sprintf('%s Given value: "%s"', $this->getErrorMessage(), $answer)); } return $answer; }
php
{ "resource": "" }