_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q14500
MediaRepository.applyFilterToMediaCollection
train
protected function applyFilterToMediaCollection(Collection $media, $filter): Collection { if (is_array($filter)) { $filter = $this->getDefaultFilterFunction($filter); } return $media->filter($filter); }
php
{ "resource": "" }
q14501
MediaRepository.getDefaultFilterFunction
train
protected function getDefaultFilterFunction(array $filters): Closure { return function (Media $media) use ($filters) { foreach ($filters as $property => $value) { if (! Arr::has($media->custom_properties, $property)) { return false; } if (Arr::get($media->custom_properties, $property) !== $value) { return false; } } return true; }; }
php
{ "resource": "" }
q14502
Conversion.setManipulations
train
public function setManipulations($manipulations) : self { if ($manipulations instanceof Manipulations) { $this->manipulations = $this->manipulations->mergeManipulations($manipulations); } if (is_callable($manipulations)) { $manipulations($this->manipulations); } return $this; }
php
{ "resource": "" }
q14503
Conversion.addAsFirstManipulations
train
public function addAsFirstManipulations(Manipulations $manipulations) : self { $manipulationSequence = $manipulations->getManipulationSequence()->toArray(); $this->manipulations ->getManipulationSequence() ->mergeArray($manipulationSequence); return $this; }
php
{ "resource": "" }
q14504
FileManipulator.createDerivedFiles
train
public function createDerivedFiles(Media $media, array $only = [], $onlyIfMissing = false) { $profileCollection = ConversionCollection::createForMedia($media); if (! empty($only)) { $profileCollection = $profileCollection->filter(function ($collection) use ($only) { return in_array($collection->getName(), $only); }); } $this->performConversions( $profileCollection->getNonQueuedConversions($media->collection_name), $media, $onlyIfMissing ); $queuedConversions = $profileCollection->getQueuedConversions($media->collection_name); if ($queuedConversions->isNotEmpty()) { $this->dispatchQueuedConversions($media, $queuedConversions); } }
php
{ "resource": "" }
q14505
FileManipulator.performConversions
train
public function performConversions(ConversionCollection $conversions, Media $media, $onlyIfMissing = false) { if ($conversions->isEmpty()) { return; } $imageGenerator = $this->determineImageGenerator($media); if (! $imageGenerator) { return; } $temporaryDirectory = TemporaryDirectory::create(); $copiedOriginalFile = app(Filesystem::class)->copyFromMediaLibrary( $media, $temporaryDirectory->path(str_random(16).'.'.$media->extension) ); $conversions ->reject(function (Conversion $conversion) use ($onlyIfMissing, $media) { $relativePath = $media->getPath($conversion->getName()); $rootPath = config('filesystems.disks.'.$media->disk.'.root'); if ($rootPath) { $relativePath = str_replace($rootPath, '', $relativePath); } return $onlyIfMissing && Storage::disk($media->disk)->exists($relativePath); }) ->each(function (Conversion $conversion) use ($media, $imageGenerator, $copiedOriginalFile) { event(new ConversionWillStart($media, $conversion, $copiedOriginalFile)); $copiedOriginalFile = $imageGenerator->convert($copiedOriginalFile, $conversion); $manipulationResult = $this->performManipulations($media, $conversion, $copiedOriginalFile); $newFileName = pathinfo($media->file_name, PATHINFO_FILENAME). '-'.$conversion->getName(). '.'.$conversion->getResultExtension(pathinfo($copiedOriginalFile, PATHINFO_EXTENSION)); $renamedFile = MediaLibraryFileHelper::renameInDirectory($manipulationResult, $newFileName); if ($conversion->shouldGenerateResponsiveImages()) { app(ResponsiveImageGenerator::class)->generateResponsiveImagesForConversion( $media, $conversion, $renamedFile ); } app(Filesystem::class)->copyToMediaLibrary($renamedFile, $media, 'conversions'); $media->markAsConversionGenerated($conversion->getName(), true); event(new ConversionHasBeenCompleted($media, $conversion)); }); $temporaryDirectory->delete(); }
php
{ "resource": "" }
q14506
LocalUrlGenerator.getResponsiveImagesDirectoryUrl
train
public function getResponsiveImagesDirectoryUrl(): string { return url($this->getBaseMediaDirectoryUrl().'/'.$this->pathGenerator->getPathForResponsiveImages($this->media)).'/'; }
php
{ "resource": "" }
q14507
ConversionCollection.getByName
train
public function getByName(string $name): Conversion { $conversion = $this->first(function (Conversion $conversion) use ($name) { return $conversion->getName() === $name; }); if (! $conversion) { throw InvalidConversion::unknownName($name); } return $conversion; }
php
{ "resource": "" }
q14508
ConversionCollection.addConversionsFromRelatedModel
train
protected function addConversionsFromRelatedModel(Media $media) { $modelName = Arr::get(Relation::morphMap(), $media->model_type, $media->model_type); /** @var \Spatie\MediaLibrary\HasMedia\HasMedia $model */ $model = new $modelName(); /* * In some cases the user might want to get the actual model * instance so conversion parameters can depend on model * properties. This will causes extra queries. */ if ($model->registerMediaConversionsUsingModelInstance) { $model = $media->model; $model->mediaConversion = []; } $model->registerAllMediaConversions($media); $this->items = $model->mediaConversions; }
php
{ "resource": "" }
q14509
ConversionCollection.addManipulationsFromDb
train
protected function addManipulationsFromDb(Media $media) { collect($media->manipulations)->each(function ($manipulations, $conversionName) { $this->addManipulationToConversion(new Manipulations([$manipulations]), $conversionName); }); }
php
{ "resource": "" }
q14510
S3UrlGenerator.getTemporaryUrl
train
public function getTemporaryUrl(DateTimeInterface $expiration, array $options = []): string { return $this ->filesystemManager ->disk($this->media->disk) ->temporaryUrl($this->getPath(), $expiration, $options); }
php
{ "resource": "" }
q14511
HasMediaTrait.addMediaFromUrl
train
public function addMediaFromUrl(string $url, ...$allowedMimeTypes) { if (! $stream = @fopen($url, 'r')) { throw UnreachableUrl::create($url); } $temporaryFile = tempnam(sys_get_temp_dir(), 'media-library'); file_put_contents($temporaryFile, $stream); $this->guardAgainstInvalidMimeType($temporaryFile, $allowedMimeTypes); $filename = basename(parse_url($url, PHP_URL_PATH)); $filename = str_replace('%20', ' ', $filename); if ($filename === '') { $filename = 'file'; } $mediaExtension = explode('/', mime_content_type($temporaryFile)); if (! str_contains($filename, '.')) { $filename = "{$filename}.{$mediaExtension[1]}"; } return app(FileAdderFactory::class) ->create($this, $temporaryFile) ->usingName(pathinfo($filename, PATHINFO_FILENAME)) ->usingFileName($filename); }
php
{ "resource": "" }
q14512
HasMediaTrait.addMediaFromBase64
train
public function addMediaFromBase64(string $base64data, ...$allowedMimeTypes): FileAdder { // strip out data uri scheme information (see RFC 2397) if (strpos($base64data, ';base64') !== false) { [$_, $base64data] = explode(';', $base64data); [$_, $base64data] = explode(',', $base64data); } // strict mode filters for non-base64 alphabet characters if (base64_decode($base64data, true) === false) { throw InvalidBase64Data::create(); } // decoding and then reencoding should not change the data if (base64_encode(base64_decode($base64data)) !== $base64data) { throw InvalidBase64Data::create(); } $binaryData = base64_decode($base64data); // temporarily store the decoded data on the filesystem to be able to pass it to the fileAdder $tmpFile = tempnam(sys_get_temp_dir(), 'medialibrary'); file_put_contents($tmpFile, $binaryData); $this->guardAgainstInvalidMimeType($tmpFile, $allowedMimeTypes); $file = app(FileAdderFactory::class)->create($this, $tmpFile); return $file; }
php
{ "resource": "" }
q14513
HasMediaTrait.updateMedia
train
public function updateMedia(array $newMediaArray, string $collectionName = 'default'): Collection { $this->removeMediaItemsNotPresentInArray($newMediaArray, $collectionName); return collect($newMediaArray) ->map(function (array $newMediaItem) use ($collectionName) { static $orderColumn = 1; $mediaClass = config('medialibrary.media_model'); $currentMedia = $mediaClass::findOrFail($newMediaItem['id']); if ($currentMedia->collection_name !== $collectionName) { throw MediaCannotBeUpdated::doesNotBelongToCollection($collectionName, $currentMedia); } if (array_key_exists('name', $newMediaItem)) { $currentMedia->name = $newMediaItem['name']; } if (array_key_exists('custom_properties', $newMediaItem)) { $currentMedia->custom_properties = $newMediaItem['custom_properties']; } $currentMedia->order_column = $orderColumn++; $currentMedia->save(); return $currentMedia; }); }
php
{ "resource": "" }
q14514
HasMediaTrait.clearMediaCollection
train
public function clearMediaCollection(string $collectionName = 'default'): self { $this->getMedia($collectionName) ->each->delete(); event(new CollectionHasBeenCleared($this, $collectionName)); if ($this->mediaIsPreloaded()) { unset($this->media); } return $this; }
php
{ "resource": "" }
q14515
HasMediaTrait.clearMediaCollectionExcept
train
public function clearMediaCollectionExcept(string $collectionName = 'default', $excludedMedia = []) { if ($excludedMedia instanceof Media) { $excludedMedia = collect()->push($excludedMedia); } $excludedMedia = collect($excludedMedia); if ($excludedMedia->isEmpty()) { return $this->clearMediaCollection($collectionName); } $this->getMedia($collectionName) ->reject(function (Media $media) use ($excludedMedia) { return $excludedMedia->where('id', $media->id)->count(); }) ->each->delete(); if ($this->mediaIsPreloaded()) { unset($this->media); } return $this; }
php
{ "resource": "" }
q14516
HasMediaTrait.deleteMedia
train
public function deleteMedia($mediaId) { if ($mediaId instanceof Media) { $mediaId = $mediaId->id; } $media = $this->media->find($mediaId); if (! $media) { throw MediaCannotBeDeleted::doesNotBelongToModel($mediaId, $this); } $media->delete(); }
php
{ "resource": "" }
q14517
HasMediaTrait.loadMedia
train
public function loadMedia(string $collectionName) { $collection = $this->exists ? $this->media : collect($this->unAttachedMediaLibraryItems)->pluck('media'); return $collection ->filter(function (Media $mediaItem) use ($collectionName) { if ($collectionName == '') { return true; } return $mediaItem->collection_name === $collectionName; }) ->sortBy('order_column') ->values(); }
php
{ "resource": "" }
q14518
ParamHelpers.cleanParams
train
protected function cleanParams(array $params) { $values = []; foreach ($params as $name => $details) { $this->cleanValueFrom($name, $details['value'], $values); } return $values; }
php
{ "resource": "" }
q14519
ParamHelpers.cleanValueFrom
train
protected function cleanValueFrom($name, $value, array &$values = []) { if (str_contains($name, '[')) { $name = str_replace(['][', '[', ']', '..'], ['.', '.', '', '.*.'], $name); } array_set($values, str_replace('.*', '.0', $name), $value); }
php
{ "resource": "" }
q14520
ResponseTagStrategy.getDocBlockResponses
train
protected function getDocBlockResponses(array $tags) { $responseTags = array_values( array_filter($tags, function ($tag) { return $tag instanceof Tag && strtolower($tag->getName()) === 'response'; }) ); if (empty($responseTags)) { return; } return array_map(function (Tag $responseTag) { preg_match('/^(\d{3})?\s?([\s\S]*)$/', $responseTag->getContent(), $result); $status = $result[1] ?: 200; $content = $result[2] ?: '{}'; return new JsonResponse(json_decode($content, true), (int) $status); }, $responseTags); }
php
{ "resource": "" }
q14521
ResponseFileStrategy.getFileResponses
train
protected function getFileResponses(array $tags) { // avoid "holes" in the keys of the filtered array, by using array_values on the filtered array $responseFileTags = array_values( array_filter($tags, function ($tag) { return $tag instanceof Tag && strtolower($tag->getName()) === 'responsefile'; }) ); if (empty($responseFileTags)) { return; } return array_map(function (Tag $responseFileTag) { preg_match('/^(\d{3})?\s?([\S]*[\s]*?)(\{.*\})?$/', $responseFileTag->getContent(), $result); $status = $result[1] ?: 200; $content = $result[2] ? file_get_contents(storage_path(trim($result[2])), true) : '{}'; $json = ! empty($result[3]) ? str_replace("'", '"', $result[3]) : '{}'; $merged = array_merge(json_decode($content, true), json_decode($json, true)); return new JsonResponse($merged, (int) $status); }, $responseFileTags); }
php
{ "resource": "" }
q14522
Generator.castToType
train
private function castToType(string $value, string $type) { $casts = [ 'integer' => 'intval', 'number' => 'floatval', 'float' => 'floatval', 'boolean' => 'boolval', ]; // First, we handle booleans. We can't use a regular cast, //because PHP considers string 'false' as true. if ($value == 'false' && $type == 'boolean') { return false; } if (isset($casts[$type])) { return $casts[$type]($value); } return $value; }
php
{ "resource": "" }
q14523
TransformerTagsStrategy.getTransformerResponse
train
protected function getTransformerResponse(array $tags) { try { if (empty($transformerTag = $this->getTransformerTag($tags))) { return; } $transformer = $this->getTransformerClass($transformerTag); $model = $this->getClassToBeTransformed($tags, (new ReflectionClass($transformer))->getMethod('transform')); $modelInstance = $this->instantiateTransformerModel($model); $fractal = new Manager(); if (! is_null(config('apidoc.fractal.serializer'))) { $fractal->setSerializer(app(config('apidoc.fractal.serializer'))); } $resource = (strtolower($transformerTag->getName()) == 'transformercollection') ? new Collection([$modelInstance, $modelInstance], new $transformer) : new Item($modelInstance, new $transformer); return [response($fractal->createData($resource)->toJson())]; } catch (\Exception $e) { return; } }
php
{ "resource": "" }
q14524
Lfm.currentLfmType
train
public function currentLfmType() { $lfm_type = 'file'; $request_type = lcfirst(str_singular($this->input('type') ?: '')); $available_types = array_keys($this->config->get('lfm.folder_categories') ?: []); if (in_array($request_type, $available_types)) { $lfm_type = $request_type; } return $lfm_type; }
php
{ "resource": "" }
q14525
Lfm.translateFromUtf8
train
public function translateFromUtf8($input) { if ($this->isRunningOnWindows()) { $input = iconv('UTF-8', mb_detect_encoding($input), $input); } return $input; }
php
{ "resource": "" }
q14526
Lfm.routes
train
public static function routes() { $middleware = [ CreateDefaultFolder::class, MultiUser::class ]; $as = 'unisharp.lfm.'; $namespace = '\\UniSharp\\LaravelFilemanager\\Controllers\\'; Route::group(compact('middleware', 'as', 'namespace'), function () { // display main layout Route::get('/', [ 'uses' => 'LfmController@show', 'as' => 'show', ]); // display integration error messages Route::get('/errors', [ 'uses' => 'LfmController@getErrors', 'as' => 'getErrors', ]); // upload Route::any('/upload', [ 'uses' => 'UploadController@upload', 'as' => 'upload', ]); // list images & files Route::get('/jsonitems', [ 'uses' => 'ItemsController@getItems', 'as' => 'getItems', ]); Route::get('/move', [ 'uses' => 'ItemsController@move', 'as' => 'move', ]); Route::get('/domove', [ 'uses' => 'ItemsController@domove', 'as' => 'domove' ]); // folders Route::get('/newfolder', [ 'uses' => 'FolderController@getAddfolder', 'as' => 'getAddfolder', ]); // list folders Route::get('/folders', [ 'uses' => 'FolderController@getFolders', 'as' => 'getFolders', ]); // crop Route::get('/crop', [ 'uses' => 'CropController@getCrop', 'as' => 'getCrop', ]); Route::get('/cropimage', [ 'uses' => 'CropController@getCropimage', 'as' => 'getCropimage', ]); Route::get('/cropnewimage', [ 'uses' => 'CropController@getNewCropimage', 'as' => 'getCropimage', ]); // rename Route::get('/rename', [ 'uses' => 'RenameController@getRename', 'as' => 'getRename', ]); // scale/resize Route::get('/resize', [ 'uses' => 'ResizeController@getResize', 'as' => 'getResize', ]); Route::get('/doresize', [ 'uses' => 'ResizeController@performResize', 'as' => 'performResize', ]); // download Route::get('/download', [ 'uses' => 'DownloadController@getDownload', 'as' => 'getDownload', ]); // delete Route::get('/delete', [ 'uses' => 'DeleteController@getDelete', 'as' => 'getDelete', ]); Route::get('/demo', 'DemoController@index'); }); }
php
{ "resource": "" }
q14527
ItemsController.getItems
train
public function getItems() { return [ 'items' => array_map(function ($item) { return $item->fill()->attributes; }, array_merge($this->lfm->folders(), $this->lfm->files())), 'display' => $this->helper->getDisplayMode(), 'working_dir' => $this->lfm->path('working_dir'), ]; }
php
{ "resource": "" }
q14528
FolderController.getAddfolder
train
public function getAddfolder() { $folder_name = $this->helper->input('name'); try { if (empty($folder_name)) { return $this->helper->error('folder-name'); } elseif ($this->lfm->setName($folder_name)->exists()) { return $this->helper->error('folder-exist'); } elseif (config('lfm.alphanumeric_directory') && preg_match('/[^\w-]/i', $folder_name)) { return $this->helper->error('folder-alnum'); } else { $this->lfm->setName($folder_name)->createFolder(); } } catch (\Exception $e) { return $e->getMessage(); } return parent::$success_response; }
php
{ "resource": "" }
q14529
DeleteController.getDelete
train
public function getDelete() { $item_names = request('items'); $errors = []; foreach ($item_names as $name_to_delete) { $file_to_delete = $this->lfm->pretty($name_to_delete); $file_path = $file_to_delete->path(); event(new ImageIsDeleting($file_path)); if (is_null($name_to_delete)) { array_push($errors, parent::error('folder-name')); continue; } if (! $this->lfm->setName($name_to_delete)->exists()) { array_push($errors, parent::error('folder-not-found', ['folder' => $file_path])); continue; } if ($this->lfm->setName($name_to_delete)->isDirectory()) { if (! $this->lfm->setName($name_to_delete)->directoryIsEmpty()) { array_push($errors, parent::error('delete-folder')); continue; } } else { if ($file_to_delete->isImage()) { $this->lfm->setName($name_to_delete)->thumb()->delete(); } } $this->lfm->setName($name_to_delete)->delete(); event(new ImageWasDeleted($file_path)); } if (count($errors) > 0) { return $errors; } return parent::$success_response; }
php
{ "resource": "" }
q14530
LfmPath.createFolder
train
public function createFolder() { if ($this->storage->exists($this)) { return false; } $this->storage->makeDirectory(0777, true, true); }
php
{ "resource": "" }
q14531
LfmPath.sortByColumn
train
public function sortByColumn($arr_items) { $sort_by = $this->helper->input('sort_type'); if (in_array($sort_by, ['name', 'time'])) { $key_to_sort = $sort_by; } else { $key_to_sort = 'name'; } uasort($arr_items, function ($a, $b) use ($key_to_sort) { return strcmp($a->{$key_to_sort}, $b->{$key_to_sort}); }); return $arr_items; }
php
{ "resource": "" }
q14532
LfmController.getErrors
train
public function getErrors() { $arr_errors = []; if (! extension_loaded('gd') && ! extension_loaded('imagick')) { array_push($arr_errors, trans('laravel-filemanager::lfm.message-extension_not_found')); } if (! extension_loaded('exif')) { array_push($arr_errors, 'EXIF extension not found.'); } if (! extension_loaded('fileinfo')) { array_push($arr_errors, 'Fileinfo extension not found.'); } $mine_config_key = 'lfm.folder_categories.' . $this->helper->currentLfmType() . '.valid_mime'; if (! is_array(config($mine_config_key))) { array_push($arr_errors, 'Config : ' . $mine_config_key . ' is not a valid array.'); } return $arr_errors; }
php
{ "resource": "" }
q14533
LfmController.applyIniOverrides
train
public function applyIniOverrides() { $overrides = config('lfm.php_ini_overrides'); if ($overrides && is_array($overrides) && count($overrides) === 0) { return; } foreach ($overrides as $key => $value) { if ($value && $value != 'false') { ini_set($key, $value); } } }
php
{ "resource": "" }
q14534
ResizeController.getResize
train
public function getResize() { $ratio = 1.0; $image = request('img'); $original_image = Image::make($this->lfm->setName($image)->path('absolute')); $original_width = $original_image->width(); $original_height = $original_image->height(); $scaled = false; // FIXME size should be configurable if ($original_width > 600) { $ratio = 600 / $original_width; $width = $original_width * $ratio; $height = $original_height * $ratio; $scaled = true; } else { $width = $original_width; $height = $original_height; } if ($height > 400) { $ratio = 400 / $original_height; $width = $original_width * $ratio; $height = $original_height * $ratio; $scaled = true; } return view('laravel-filemanager::resize') ->with('img', $this->lfm->pretty($image)) ->with('height', number_format($height, 0)) ->with('width', $width) ->with('original_height', $original_height) ->with('original_width', $original_width) ->with('scaled', $scaled) ->with('ratio', $ratio); }
php
{ "resource": "" }
q14535
FlashPolicy.addAllowedAccess
train
public function addAllowedAccess($domain, $ports = '*', $secure = false) { if (!$this->validateDomain($domain)) { throw new \UnexpectedValueException('Invalid domain'); } if (!$this->validatePorts($ports)) { throw new \UnexpectedValueException('Invalid Port'); } $this->_access[] = array($domain, $ports, (boolean)$secure); $this->_cacheValid = false; return $this; }
php
{ "resource": "" }
q14536
FlashPolicy.setSiteControl
train
public function setSiteControl($permittedCrossDomainPolicies = 'all') { if (!$this->validateSiteControl($permittedCrossDomainPolicies)) { throw new \UnexpectedValueException('Invalid site control set'); } $this->_siteControl = $permittedCrossDomainPolicies; $this->_cacheValid = false; return $this; }
php
{ "resource": "" }
q14537
FlashPolicy.renderPolicy
train
public function renderPolicy() { $policy = new \SimpleXMLElement($this->_policy); $siteControl = $policy->addChild('site-control'); if ($this->_siteControl == '') { $this->setSiteControl(); } $siteControl->addAttribute('permitted-cross-domain-policies', $this->_siteControl); if (empty($this->_access)) { throw new \UnexpectedValueException('You must add a domain through addAllowedAccess()'); } foreach ($this->_access as $access) { $tmp = $policy->addChild('allow-access-from'); $tmp->addAttribute('domain', $access[0]); $tmp->addAttribute('to-ports', $access[1]); $tmp->addAttribute('secure', ($access[2] === true) ? 'true' : 'false'); } return $policy; }
php
{ "resource": "" }
q14538
Topic.broadcast
train
public function broadcast($msg, array $exclude = array(), array $eligible = array()) { $useEligible = (bool)count($eligible); foreach ($this->subscribers as $client) { if (in_array($client->WAMP->sessionId, $exclude)) { continue; } if ($useEligible && !in_array($client->WAMP->sessionId, $eligible)) { continue; } $client->event($this->id, $msg); } return $this; }
php
{ "resource": "" }
q14539
IoServer.handleConnect
train
public function handleConnect($conn) { $conn->decor = new IoConnection($conn); $conn->decor->resourceId = (int)$conn->stream; $uri = $conn->getRemoteAddress(); $conn->decor->remoteAddress = trim( parse_url((strpos($uri, '://') === false ? 'tcp://' : '') . $uri, PHP_URL_HOST), '[]' ); $this->app->onOpen($conn->decor); $conn->on('data', function ($data) use ($conn) { $this->handleData($data, $conn); }); $conn->on('close', function () use ($conn) { $this->handleEnd($conn); }); $conn->on('error', function (\Exception $e) use ($conn) { $this->handleError($e, $conn); }); }
php
{ "resource": "" }
q14540
IoServer.handleData
train
public function handleData($data, $conn) { try { $this->app->onMessage($conn->decor, $data); } catch (\Exception $e) { $this->handleError($e, $conn); } }
php
{ "resource": "" }
q14541
IoServer.handleEnd
train
public function handleEnd($conn) { try { $this->app->onClose($conn->decor); } catch (\Exception $e) { $this->handleError($e, $conn); } unset($conn->decor); }
php
{ "resource": "" }
q14542
IoServer.handleError
train
public function handleError(\Exception $e, $conn) { $this->app->onError($conn->decor, $e); }
php
{ "resource": "" }
q14543
CloseResponseTrait.close
train
private function close(ConnectionInterface $conn, $code = 400, array $additional_headers = []) { $response = new Response($code, array_merge([ 'X-Powered-By' => \Ratchet\VERSION ], $additional_headers)); $conn->send(gPsr\str($response)); $conn->close(); }
php
{ "resource": "" }
q14544
SessionProvider.parseCookie
train
private function parseCookie($cookie, $host = null, $path = null, $decode = false) { // Explode the cookie string using a series of semicolons $pieces = array_filter(array_map('trim', explode(';', $cookie))); // The name of the cookie (first kvp) must include an equal sign. if (empty($pieces) || !strpos($pieces[0], '=')) { return false; } // Create the default return array $data = array_merge(array_fill_keys(array_keys(self::$cookieParts), null), array( 'cookies' => array(), 'data' => array(), 'path' => $path ?: '/', 'http_only' => false, 'discard' => false, 'domain' => $host )); $foundNonCookies = 0; // Add the cookie pieces into the parsed data array foreach ($pieces as $part) { $cookieParts = explode('=', $part, 2); $key = trim($cookieParts[0]); if (count($cookieParts) == 1) { // Can be a single value (e.g. secure, httpOnly) $value = true; } else { // Be sure to strip wrapping quotes $value = trim($cookieParts[1], " \n\r\t\0\x0B\""); if ($decode) { $value = urldecode($value); } } // Only check for non-cookies when cookies have been found if (!empty($data['cookies'])) { foreach (self::$cookieParts as $mapValue => $search) { if (!strcasecmp($search, $key)) { $data[$mapValue] = $mapValue == 'port' ? array_map('trim', explode(',', $value)) : $value; $foundNonCookies++; continue 2; } } } // If cookies have not yet been retrieved, or this value was not found in the pieces array, treat it as a // cookie. IF non-cookies have been parsed, then this isn't a cookie, it's cookie data. Cookies then data. $data[$foundNonCookies ? 'data' : 'cookies'][$key] = $value; } // Calculate the expires date if (!$data['expires'] && $data['max_age']) { $data['expires'] = time() + (int) $data['max_age']; } return $data; }
php
{ "resource": "" }
q14545
IpBlackList.unblockAddress
train
public function unblockAddress($ip) { if (isset($this->_blacklist[$this->filterAddress($ip)])) { unset($this->_blacklist[$this->filterAddress($ip)]); } return $this; }
php
{ "resource": "" }
q14546
WampConnection.callResult
train
public function callResult($id, $data = array()) { return $this->send(json_encode(array(WAMP::MSG_CALL_RESULT, $id, $data))); }
php
{ "resource": "" }
q14547
WampConnection.callError
train
public function callError($id, $errorUri, $desc = '', $details = null) { if ($errorUri instanceof Topic) { $errorUri = (string)$errorUri; } $data = array(WAMP::MSG_CALL_ERROR, $id, $errorUri, $desc); if (null !== $details) { $data[] = $details; } return $this->send(json_encode($data)); }
php
{ "resource": "" }
q14548
WampConnection.getUri
train
public function getUri($uri) { $curieSeperator = ':'; if (preg_match('/http(s*)\:\/\//', $uri) == false) { if (strpos($uri, $curieSeperator) !== false) { list($prefix, $action) = explode($curieSeperator, $uri); if(isset($this->WAMP->prefixes[$prefix]) === true){ return $this->WAMP->prefixes[$prefix] . '#' . $action; } } } return $uri; }
php
{ "resource": "" }
q14549
Parameter.setValue
train
public function setValue($value, $type = null) { $this->value = $value; $this->type = $type ?: ParameterTypeInferer::inferType($value); }
php
{ "resource": "" }
q14550
FileDriver.getElement
train
public function getElement($className) { if ($this->classCache === null) { $this->initialize(); } if (isset($this->classCache[$className])) { return $this->classCache[$className]; } $result = $this->loadMappingFile($this->locator->findMappingFile($className)); if (! isset($result[$className])) { throw MappingException::invalidMappingFile($className, str_replace('\\', '.', $className) . $this->locator->getFileExtension()); } $this->classCache[$className] = $result[$className]; return $result[$className]; }
php
{ "resource": "" }
q14551
FileDriver.initialize
train
protected function initialize() { $this->classCache = []; if ($this->globalBasename !== null) { foreach ($this->locator->getPaths() as $path) { $file = $path . '/' . $this->globalBasename . $this->locator->getFileExtension(); if (is_file($file)) { $this->classCache = array_merge( $this->classCache, $this->loadMappingFile($file) ); } } } }
php
{ "resource": "" }
q14552
QueryBuilder.findRootAlias
train
private function findRootAlias($alias, $parentAlias) { $rootAlias = null; if (in_array($parentAlias, $this->getRootAliases(), true)) { $rootAlias = $parentAlias; } elseif (isset($this->joinRootAliases[$parentAlias])) { $rootAlias = $this->joinRootAliases[$parentAlias]; } else { // Should never happen with correct joining order. Might be // thoughtful to throw exception instead. $rootAlias = $this->getRootAlias(); } $this->joinRootAliases[$alias] = $rootAlias; return $rootAlias; }
php
{ "resource": "" }
q14553
QueryBuilder.getRootAliases
train
public function getRootAliases() { $aliases = []; foreach ($this->dqlParts['from'] as &$fromClause) { if (is_string($fromClause)) { $spacePos = strrpos($fromClause, ' '); $from = substr($fromClause, 0, $spacePos); $alias = substr($fromClause, $spacePos + 1); $fromClause = new Query\Expr\From($from, $alias); } $aliases[] = $fromClause->getAlias(); } return $aliases; }
php
{ "resource": "" }
q14554
QueryBuilder.getRootEntities
train
public function getRootEntities() { $entities = []; foreach ($this->dqlParts['from'] as &$fromClause) { if (is_string($fromClause)) { $spacePos = strrpos($fromClause, ' '); $from = substr($fromClause, 0, $spacePos); $alias = substr($fromClause, $spacePos + 1); $fromClause = new Query\Expr\From($from, $alias); } $entities[] = $fromClause->getFrom(); } return $entities; }
php
{ "resource": "" }
q14555
QueryBuilder.update
train
public function update($update = null, $alias = null) { $this->type = self::UPDATE; if (! $update) { return $this; } return $this->add('from', new Expr\From($update, $alias)); }
php
{ "resource": "" }
q14556
QueryBuilder.from
train
public function from($from, $alias, $indexBy = null) { return $this->add('from', new Expr\From($from, $alias, $indexBy), true); }
php
{ "resource": "" }
q14557
QueryBuilder.set
train
public function set($key, $value) { return $this->add('set', new Expr\Comparison($key, Expr\Comparison::EQ, $value), true); }
php
{ "resource": "" }
q14558
QueryBuilder.addCriteria
train
public function addCriteria(Criteria $criteria) { $allAliases = $this->getAllAliases(); if (! isset($allAliases[0])) { throw new Query\QueryException('No aliases are set before invoking addCriteria().'); } $visitor = new QueryExpressionVisitor($this->getAllAliases()); $whereExpression = $criteria->getWhereExpression(); if ($whereExpression) { $this->andWhere($visitor->dispatch($whereExpression)); foreach ($visitor->getParameters() as $parameter) { $this->parameters->add($parameter); } } if ($criteria->getOrderings()) { foreach ($criteria->getOrderings() as $sort => $order) { $hasValidAlias = false; foreach ($allAliases as $alias) { if (strpos($sort . '.', $alias . '.') === 0) { $hasValidAlias = true; break; } } if (! $hasValidAlias) { $sort = $allAliases[0] . '.' . $sort; } $this->addOrderBy($sort, $order); } } $firstResult = $criteria->getFirstResult(); $maxResults = $criteria->getMaxResults(); // Overwrite limits only if they was set in criteria if ($firstResult !== null) { $this->setFirstResult($firstResult); } if ($maxResults !== null) { $this->setMaxResults($maxResults); } return $this; }
php
{ "resource": "" }
q14559
SchemaTool.createSchema
train
public function createSchema(array $classes) { $createSchemaSql = $this->getCreateSchemaSql($classes); $conn = $this->em->getConnection(); foreach ($createSchemaSql as $sql) { try { $conn->executeQuery($sql); } catch (Throwable $e) { throw ToolsException::schemaToolFailure($sql, $e); } } }
php
{ "resource": "" }
q14560
SchemaTool.getCreateSchemaSql
train
public function getCreateSchemaSql(array $classes) { $schema = $this->getSchemaFromMetadata($classes); return $schema->toSql($this->platform); }
php
{ "resource": "" }
q14561
SchemaTool.dropSchema
train
public function dropSchema(array $classes) { $dropSchemaSql = $this->getDropSchemaSQL($classes); $conn = $this->em->getConnection(); foreach ($dropSchemaSql as $sql) { try { $conn->executeQuery($sql); } catch (Throwable $e) { // ignored } } }
php
{ "resource": "" }
q14562
SchemaTool.dropDatabase
train
public function dropDatabase() { $dropSchemaSql = $this->getDropDatabaseSQL(); $conn = $this->em->getConnection(); foreach ($dropSchemaSql as $sql) { $conn->executeQuery($sql); } }
php
{ "resource": "" }
q14563
SchemaTool.getDropDatabaseSQL
train
public function getDropDatabaseSQL() { $sm = $this->em->getConnection()->getSchemaManager(); $schema = $sm->createSchema(); $visitor = new DropSchemaSqlCollector($this->platform); $schema->visit($visitor); return $visitor->getQueries(); }
php
{ "resource": "" }
q14564
SchemaTool.getDropSchemaSQL
train
public function getDropSchemaSQL(array $classes) { $visitor = new DropSchemaSqlCollector($this->platform); $schema = $this->getSchemaFromMetadata($classes); $sm = $this->em->getConnection()->getSchemaManager(); $fullSchema = $sm->createSchema(); foreach ($fullSchema->getTables() as $table) { if (! $schema->hasTable($table->getName())) { foreach ($table->getForeignKeys() as $foreignKey) { /** @var $foreignKey \Doctrine\DBAL\Schema\ForeignKeyConstraint */ if ($schema->hasTable($foreignKey->getForeignTableName())) { $visitor->acceptForeignKey($table, $foreignKey); } } } else { $visitor->acceptTable($table); foreach ($table->getForeignKeys() as $foreignKey) { $visitor->acceptForeignKey($table, $foreignKey); } } } if ($this->platform->supportsSequences()) { foreach ($schema->getSequences() as $sequence) { $visitor->acceptSequence($sequence); } foreach ($schema->getTables() as $table) { /** @var $sequence Table */ if ($table->hasPrimaryKey()) { $columns = $table->getPrimaryKey()->getColumns(); if (count($columns) === 1) { $checkSequence = $table->getName() . '_' . $columns[0] . '_seq'; if ($fullSchema->hasSequence($checkSequence)) { $visitor->acceptSequence($fullSchema->getSequence($checkSequence)); } } } } } return $visitor->getQueries(); }
php
{ "resource": "" }
q14565
SchemaTool.updateSchema
train
public function updateSchema(array $classes, $saveMode = false) { $updateSchemaSql = $this->getUpdateSchemaSql($classes, $saveMode); $conn = $this->em->getConnection(); foreach ($updateSchemaSql as $sql) { $conn->executeQuery($sql); } }
php
{ "resource": "" }
q14566
SchemaTool.getUpdateSchemaSql
train
public function getUpdateSchemaSql(array $classes, $saveMode = false) { $sm = $this->em->getConnection()->getSchemaManager(); $fromSchema = $sm->createSchema(); $toSchema = $this->getSchemaFromMetadata($classes); $comparator = new Comparator(); $schemaDiff = $comparator->compare($fromSchema, $toSchema); if ($saveMode) { return $schemaDiff->toSaveSql($this->platform); } return $schemaDiff->toSql($this->platform); }
php
{ "resource": "" }
q14567
AbstractQuery.setParameters
train
public function setParameters($parameters) { // BC compatibility with 2.3- if (is_array($parameters)) { $parameterCollection = new ArrayCollection(); foreach ($parameters as $key => $value) { $parameterCollection->add(new Parameter($key, $value)); } $parameters = $parameterCollection; } $this->parameters = $parameters; return $this; }
php
{ "resource": "" }
q14568
DefaultRepositoryFactory.createRepository
train
private function createRepository(EntityManagerInterface $entityManager, $entityName) { /** @var ClassMetadata $metadata */ $metadata = $entityManager->getClassMetadata($entityName); $repositoryClassName = $metadata->getCustomRepositoryClassName() ?: $entityManager->getConfiguration()->getDefaultRepositoryClassName(); return new $repositoryClassName($entityManager, $metadata); }
php
{ "resource": "" }
q14569
CommitOrderCalculator.sort
train
public function sort() { foreach ($this->nodeList as $vertex) { if ($vertex->state !== self::NOT_VISITED) { continue; } $this->visit($vertex); } $sortedList = $this->sortedNodeList; $this->nodeList = []; $this->sortedNodeList = []; return array_reverse($sortedList); }
php
{ "resource": "" }
q14570
ClassMetadata.validateLifecycleCallbacks
train
public function validateLifecycleCallbacks(ReflectionService $reflectionService) : void { foreach ($this->lifecycleCallbacks as $callbacks) { /** @var array $callbacks */ foreach ($callbacks as $callbackFuncName) { if (! $reflectionService->hasPublicMethod($this->className, $callbackFuncName)) { throw MappingException::lifecycleCallbackMethodNotFound($this->className, $callbackFuncName); } } } }
php
{ "resource": "" }
q14571
ClassMetadata.validateAndCompleteToOneAssociationMetadata
train
protected function validateAndCompleteToOneAssociationMetadata(ToOneAssociationMetadata $property) { $fieldName = $property->getName(); if ($property->isOwningSide()) { if (empty($property->getJoinColumns())) { // Apply default join column $property->addJoinColumn(new JoinColumnMetadata()); } $uniqueConstraintColumns = []; foreach ($property->getJoinColumns() as $joinColumn) { /** @var JoinColumnMetadata $joinColumn */ if ($property instanceof OneToOneAssociationMetadata && $this->inheritanceType !== InheritanceType::SINGLE_TABLE) { if (count($property->getJoinColumns()) === 1) { if (! $property->isPrimaryKey()) { $joinColumn->setUnique(true); } } else { $uniqueConstraintColumns[] = $joinColumn->getColumnName(); } } $joinColumn->setTableName(! $this->isMappedSuperclass ? $this->getTableName() : null); if (! $joinColumn->getColumnName()) { $joinColumn->setColumnName($this->namingStrategy->joinColumnName($fieldName, $this->className)); } if (! $joinColumn->getReferencedColumnName()) { $joinColumn->setReferencedColumnName($this->namingStrategy->referenceColumnName()); } $this->fieldNames[$joinColumn->getColumnName()] = $fieldName; } if ($uniqueConstraintColumns) { if (! $this->table) { throw new RuntimeException( 'ClassMetadata::setTable() has to be called before defining a one to one relationship.' ); } $this->table->addUniqueConstraint( [ 'name' => sprintf('%s_uniq', $fieldName), 'columns' => $uniqueConstraintColumns, 'options' => [], 'flags' => [], ] ); } } if ($property->isOrphanRemoval()) { $cascades = $property->getCascade(); if (! in_array('remove', $cascades, true)) { $cascades[] = 'remove'; $property->setCascade($cascades); } // @todo guilhermeblanco where is this used? // @todo guilhermeblanco Shouldn￿'t we iterate through JoinColumns to set non-uniqueness? //$property->setUnique(false); } if ($property->isPrimaryKey() && ! $property->isOwningSide()) { throw MappingException::illegalInverseIdentifierAssociation($this->className, $fieldName); } }
php
{ "resource": "" }
q14572
ClassMetadata.validateAndCompleteManyToOneMapping
train
protected function validateAndCompleteManyToOneMapping(ManyToOneAssociationMetadata $property) { // A many-to-one mapping is essentially a one-one backreference if ($property->isOrphanRemoval()) { throw MappingException::illegalOrphanRemoval($this->className, $property->getName()); } }
php
{ "resource": "" }
q14573
ClassMetadata.getSingleIdentifierFieldName
train
public function getSingleIdentifierFieldName() { if ($this->isIdentifierComposite()) { throw MappingException::singleIdNotAllowedOnCompositePrimaryKey($this->className); } if (! isset($this->identifier[0])) { throw MappingException::noIdDefined($this->className); } return $this->identifier[0]; }
php
{ "resource": "" }
q14574
ClassMetadata.getIdentifierColumns
train
public function getIdentifierColumns(EntityManagerInterface $em) : array { $columns = []; foreach ($this->identifier as $idProperty) { $property = $this->getProperty($idProperty); if ($property instanceof FieldMetadata) { $columns[$property->getColumnName()] = $property; continue; } /** @var AssociationMetadata $property */ // Association defined as Id field $targetClass = $em->getClassMetadata($property->getTargetEntity()); if (! $property->isOwningSide()) { $property = $targetClass->getProperty($property->getMappedBy()); $targetClass = $em->getClassMetadata($property->getTargetEntity()); } $joinColumns = $property instanceof ManyToManyAssociationMetadata ? $property->getJoinTable()->getInverseJoinColumns() : $property->getJoinColumns(); foreach ($joinColumns as $joinColumn) { /** @var JoinColumnMetadata $joinColumn */ $columnName = $joinColumn->getColumnName(); $referencedColumnName = $joinColumn->getReferencedColumnName(); if (! $joinColumn->getType()) { $joinColumn->setType(PersisterHelper::getTypeOfColumn($referencedColumnName, $targetClass, $em)); } $columns[$columnName] = $joinColumn; } } return $columns; }
php
{ "resource": "" }
q14575
ClassMetadata.getTemporaryIdTableName
train
public function getTemporaryIdTableName() : string { $schema = $this->getSchemaName() === null ? '' : $this->getSchemaName() . '_'; // replace dots with underscores because PostgreSQL creates temporary tables in a special schema return $schema . $this->getTableName() . '_id_tmp'; }
php
{ "resource": "" }
q14576
ClassMetadata.setPropertyOverride
train
public function setPropertyOverride(Property $property) : void { $fieldName = $property->getName(); if (! isset($this->declaredProperties[$fieldName])) { throw MappingException::invalidOverrideFieldName($this->className, $fieldName); } $originalProperty = $this->getProperty($fieldName); $originalPropertyClassName = get_class($originalProperty); // If moving from transient to persistent, assume it's a new property if ($originalPropertyClassName === TransientMetadata::class) { unset($this->declaredProperties[$fieldName]); $this->addProperty($property); return; } // Do not allow to change property type if ($originalPropertyClassName !== get_class($property)) { throw MappingException::invalidOverridePropertyType($this->className, $fieldName); } // Do not allow to change version property if ($originalProperty instanceof VersionFieldMetadata) { throw MappingException::invalidOverrideVersionField($this->className, $fieldName); } unset($this->declaredProperties[$fieldName]); if ($property instanceof FieldMetadata) { // Unset defined fieldName prior to override unset($this->fieldNames[$originalProperty->getColumnName()]); // Revert what should not be allowed to change $property->setDeclaringClass($originalProperty->getDeclaringClass()); $property->setPrimaryKey($originalProperty->isPrimaryKey()); } elseif ($property instanceof AssociationMetadata) { // Unset all defined fieldNames prior to override if ($originalProperty instanceof ToOneAssociationMetadata && $originalProperty->isOwningSide()) { foreach ($originalProperty->getJoinColumns() as $joinColumn) { unset($this->fieldNames[$joinColumn->getColumnName()]); } } // Override what it should be allowed to change if ($property->getInversedBy()) { $originalProperty->setInversedBy($property->getInversedBy()); } if ($property->getFetchMode() !== $originalProperty->getFetchMode()) { $originalProperty->setFetchMode($property->getFetchMode()); } if ($originalProperty instanceof ToOneAssociationMetadata && $property->getJoinColumns()) { $originalProperty->setJoinColumns($property->getJoinColumns()); } elseif ($originalProperty instanceof ManyToManyAssociationMetadata && $property->getJoinTable()) { $originalProperty->setJoinTable($property->getJoinTable()); } $property = $originalProperty; } $this->addProperty($property); }
php
{ "resource": "" }
q14577
ClassMetadata.isInheritedProperty
train
public function isInheritedProperty($fieldName) { $declaringClass = $this->declaredProperties[$fieldName]->getDeclaringClass(); return $declaringClass->className !== $this->className; }
php
{ "resource": "" }
q14578
ClassMetadata.addProperty
train
public function addProperty(Property $property) { $fieldName = $property->getName(); // Check for empty field name if (empty($fieldName)) { throw MappingException::missingFieldName($this->className); } $property->setDeclaringClass($this); switch (true) { case $property instanceof VersionFieldMetadata: $this->validateAndCompleteFieldMapping($property); $this->validateAndCompleteVersionFieldMapping($property); break; case $property instanceof FieldMetadata: $this->validateAndCompleteFieldMapping($property); break; case $property instanceof OneToOneAssociationMetadata: $this->validateAndCompleteAssociationMapping($property); $this->validateAndCompleteToOneAssociationMetadata($property); $this->validateAndCompleteOneToOneMapping($property); break; case $property instanceof OneToManyAssociationMetadata: $this->validateAndCompleteAssociationMapping($property); $this->validateAndCompleteToManyAssociationMetadata($property); $this->validateAndCompleteOneToManyMapping($property); break; case $property instanceof ManyToOneAssociationMetadata: $this->validateAndCompleteAssociationMapping($property); $this->validateAndCompleteToOneAssociationMetadata($property); $this->validateAndCompleteManyToOneMapping($property); break; case $property instanceof ManyToManyAssociationMetadata: $this->validateAndCompleteAssociationMapping($property); $this->validateAndCompleteToManyAssociationMetadata($property); $this->validateAndCompleteManyToManyMapping($property); break; default: // Transient properties are ignored on purpose here! =) break; } $this->addDeclaredProperty($property); }
php
{ "resource": "" }
q14579
ArrayHydrator.updateResultPointer
train
private function updateResultPointer(array &$coll, $index, $dqlAlias, $oneToOne) { if ($coll === null) { unset($this->resultPointers[$dqlAlias]); // Ticket #1228 return; } if ($oneToOne) { $this->resultPointers[$dqlAlias] =& $coll; return; } if ($index !== false) { $this->resultPointers[$dqlAlias] =& $coll[$index]; return; } if (! $coll) { return; } end($coll); $this->resultPointers[$dqlAlias] =& $coll[key($coll)]; }
php
{ "resource": "" }
q14580
LimitSubqueryOutputWalker.platformSupportsRowNumber
train
private function platformSupportsRowNumber() { return $this->platform instanceof PostgreSqlPlatform || $this->platform instanceof SQLServerPlatform || $this->platform instanceof OraclePlatform || $this->platform instanceof SQLAnywherePlatform || $this->platform instanceof DB2Platform || (method_exists($this->platform, 'supportsRowNumberFunction') && $this->platform->supportsRowNumberFunction()); }
php
{ "resource": "" }
q14581
LimitSubqueryOutputWalker.walkSelectStatement
train
public function walkSelectStatement(SelectStatement $AST) { if ($this->platformSupportsRowNumber()) { return $this->walkSelectStatementWithRowNumber($AST); } return $this->walkSelectStatementWithoutRowNumber($AST); }
php
{ "resource": "" }
q14582
LimitSubqueryOutputWalker.walkSelectStatementWithoutRowNumber
train
public function walkSelectStatementWithoutRowNumber(SelectStatement $AST, $addMissingItemsFromOrderByToSelect = true) { // We don't want to call this recursively! if ($AST->orderByClause instanceof OrderByClause && $addMissingItemsFromOrderByToSelect) { // In the case of ordering a query by columns from joined tables, we // must add those columns to the select clause of the query BEFORE // the SQL is generated. $this->addMissingItemsFromOrderByToSelect($AST); } // Remove order by clause from the inner query // It will be re-appended in the outer select generated by this method $orderByClause = $AST->orderByClause; $AST->orderByClause = null; $innerSql = $this->getInnerSQL($AST); $sqlIdentifier = $this->getSQLIdentifier($AST); $sqlAliasIdentifier = array_map(static function ($info) { return $info['alias']; }, $sqlIdentifier); // Build the counter query $sql = sprintf('SELECT DISTINCT %s FROM (%s) dctrn_result', implode(', ', $sqlAliasIdentifier), $innerSql); // http://www.doctrine-project.org/jira/browse/DDC-1958 $sql = $this->preserveSqlOrdering($sqlAliasIdentifier, $innerSql, $sql, $orderByClause); // Apply the limit and offset. $sql = $this->platform->modifyLimitQuery( $sql, $this->maxResults, $this->firstResult ?? 0 ); // Add the columns to the ResultSetMapping. It's not really nice but // it works. Preferably I'd clear the RSM or simply create a new one // but that is not possible from inside the output walker, so we dirty // up the one we have. foreach ($sqlIdentifier as $property => $propertyMapping) { $this->rsm->addScalarResult($propertyMapping['alias'], $property, $propertyMapping['type']); } // Restore orderByClause $AST->orderByClause = $orderByClause; return $sql; }
php
{ "resource": "" }
q14583
LimitSubqueryOutputWalker.addMissingItemsFromOrderByToSelect
train
private function addMissingItemsFromOrderByToSelect(SelectStatement $AST) { $this->orderByPathExpressions = []; // We need to do this in another walker because otherwise we'll end up // polluting the state of this one. $walker = clone $this; // This will populate $orderByPathExpressions via // LimitSubqueryOutputWalker::walkPathExpression, which will be called // as the select statement is walked. We'll end up with an array of all // path expressions referenced in the query. $walker->walkSelectStatementWithoutRowNumber($AST, false); $orderByPathExpressions = $walker->getOrderByPathExpressions(); // Get a map of referenced identifiers to field names. $selects = []; foreach ($orderByPathExpressions as $pathExpression) { $idVar = $pathExpression->identificationVariable; $field = $pathExpression->field; if (! isset($selects[$idVar])) { $selects[$idVar] = []; } $selects[$idVar][$field] = true; } // Loop the select clause of the AST and exclude items from $select // that are already being selected in the query. foreach ($AST->selectClause->selectExpressions as $selectExpression) { if ($selectExpression instanceof SelectExpression) { $idVar = $selectExpression->expression; if (! is_string($idVar)) { continue; } $field = $selectExpression->fieldIdentificationVariable; if ($field === null) { // No need to add this select, as we're already fetching the whole object. unset($selects[$idVar]); } else { unset($selects[$idVar][$field]); } } } // Add select items which were not excluded to the AST's select clause. foreach ($selects as $idVar => $fields) { $selectExpression = new SelectExpression(new PartialObjectExpression($idVar, array_keys($fields)), null, true); $AST->selectClause->selectExpressions[] = $selectExpression; } }
php
{ "resource": "" }
q14584
LimitSubqueryOutputWalker.recreateInnerSql
train
private function recreateInnerSql( OrderByClause $orderByClause, array $identifiers, string $innerSql ) : string { [$searchPatterns, $replacements] = $this->generateSqlAliasReplacements(); $orderByItems = []; foreach ($orderByClause->orderByItems as $orderByItem) { // Walk order by item to get string representation of it and // replace path expressions in the order by clause with their column alias $orderByItemString = preg_replace( $searchPatterns, $replacements, $this->walkOrderByItem($orderByItem) ); $orderByItems[] = $orderByItemString; $identifier = substr($orderByItemString, 0, strrpos($orderByItemString, ' ')); if (! in_array($identifier, $identifiers, true)) { $identifiers[] = $identifier; } } return $sql = sprintf( 'SELECT DISTINCT %s FROM (%s) dctrn_result_inner ORDER BY %s', implode(', ', $identifiers), $innerSql, implode(', ', $orderByItems) ); }
php
{ "resource": "" }
q14585
AbstractCollectionPersister.evictCollectionCache
train
protected function evictCollectionCache(PersistentCollection $collection) { $key = new CollectionCacheKey( $this->sourceEntity->getRootClassName(), $this->association->getName(), $this->uow->getEntityIdentifier($collection->getOwner()) ); $this->region->evict($key); if ($this->cacheLogger) { $this->cacheLogger->collectionCachePut($this->regionName, $key); } }
php
{ "resource": "" }
q14586
AnnotationDriver.convertJoinTableAnnotationToJoinTableMetadata
train
private function convertJoinTableAnnotationToJoinTableMetadata( Annotation\JoinTable $joinTableAnnot ) : Mapping\JoinTableMetadata { $joinTable = new Mapping\JoinTableMetadata(); if (! empty($joinTableAnnot->name)) { $joinTable->setName($joinTableAnnot->name); } if (! empty($joinTableAnnot->schema)) { $joinTable->setSchema($joinTableAnnot->schema); } foreach ($joinTableAnnot->joinColumns as $joinColumnAnnot) { $joinColumn = $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot); $joinTable->addJoinColumn($joinColumn); } foreach ($joinTableAnnot->inverseJoinColumns as $joinColumnAnnot) { $joinColumn = $this->convertJoinColumnAnnotationToJoinColumnMetadata($joinColumnAnnot); $joinTable->addInverseJoinColumn($joinColumn); } return $joinTable; }
php
{ "resource": "" }
q14587
AnnotationDriver.getCascade
train
private function getCascade(string $className, string $fieldName, array $originalCascades) { $cascadeTypes = ['remove', 'persist', 'refresh']; $cascades = array_map('strtolower', $originalCascades); if (in_array('all', $cascades, true)) { $cascades = $cascadeTypes; } if (count($cascades) !== count(array_intersect($cascades, $cascadeTypes))) { $diffCascades = array_diff($cascades, array_intersect($cascades, $cascadeTypes)); throw Mapping\MappingException::invalidCascadeOption($diffCascades, $className, $fieldName); } return $cascades; }
php
{ "resource": "" }
q14588
EntityManager.clear
train
public function clear($entityName = null) { $this->unitOfWork->clear(); $this->unitOfWork = new UnitOfWork($this); if ($this->eventManager->hasListeners(Events::onClear)) { $this->eventManager->dispatchEvent(Events::onClear, new Event\OnClearEventArgs($this)); } }
php
{ "resource": "" }
q14589
EntityManager.persist
train
public function persist($entity) { if (! is_object($entity)) { throw ORMInvalidArgumentException::invalidObject('EntityManager#persist()', $entity); } $this->errorIfClosed(); $this->unitOfWork->persist($entity); }
php
{ "resource": "" }
q14590
EntityManager.refresh
train
public function refresh($entity) { if (! is_object($entity)) { throw ORMInvalidArgumentException::invalidObject('EntityManager#refresh()', $entity); } $this->errorIfClosed(); $this->unitOfWork->refresh($entity); }
php
{ "resource": "" }
q14591
EntityManager.contains
train
public function contains($entity) { return $this->unitOfWork->isScheduledForInsert($entity) || ($this->unitOfWork->isInIdentityMap($entity) && ! $this->unitOfWork->isScheduledForDelete($entity)); }
php
{ "resource": "" }
q14592
EntityManager.createConnection
train
protected static function createConnection($connection, Configuration $config, ?EventManager $eventManager = null) { if (is_array($connection)) { return DriverManager::getConnection($connection, $config, $eventManager ?: new EventManager()); } if (! $connection instanceof Connection) { throw new InvalidArgumentException( sprintf( 'Invalid $connection argument of type %s given%s.', is_object($connection) ? get_class($connection) : gettype($connection), is_object($connection) ? '' : ': "' . $connection . '"' ) ); } if ($eventManager !== null && $connection->getEventManager() !== $eventManager) { throw MismatchedEventManager::create(); } return $connection; }
php
{ "resource": "" }
q14593
MappingDescribeCommand.getClassMetadata
train
private function getClassMetadata($entityName, EntityManagerInterface $entityManager) { try { return $entityManager->getClassMetadata($entityName); } catch (MappingException $e) { } $matches = array_filter( $this->getMappedEntities($entityManager), static function ($mappedEntity) use ($entityName) { return preg_match('{' . preg_quote($entityName) . '}', $mappedEntity); } ); if (! $matches) { throw new InvalidArgumentException(sprintf( 'Could not find any mapped Entity classes matching "%s"', $entityName )); } if (count($matches) > 1) { throw new InvalidArgumentException(sprintf( 'Entity name "%s" is ambiguous, possible matches: "%s"', $entityName, implode(', ', $matches) )); } return $entityManager->getClassMetadata(current($matches)); }
php
{ "resource": "" }
q14594
MappingDescribeCommand.formatValue
train
private function formatValue($value) { if ($value === '') { return ''; } if ($value === null) { return '<comment>Null</comment>'; } if (is_bool($value)) { return '<comment>' . ($value ? 'True' : 'False') . '</comment>'; } if (empty($value)) { return '<comment>Empty</comment>'; } if (is_array($value)) { return json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); } if (is_object($value)) { return sprintf('<%s>', get_class($value)); } if (is_scalar($value)) { return $value; } throw new InvalidArgumentException(sprintf('Do not know how to format value "%s"', print_r($value, true))); }
php
{ "resource": "" }
q14595
MappingDescribeCommand.formatField
train
private function formatField($label, $value) { if ($value === null) { $value = '<comment>None</comment>'; } return [sprintf('<info>%s</info>', $label), $this->formatValue($value)]; }
php
{ "resource": "" }
q14596
MappingDescribeCommand.formatPropertyMappings
train
private function formatPropertyMappings(iterable $propertyMappings) { $output = []; foreach ($propertyMappings as $propertyName => $property) { $output[] = $this->formatField(sprintf(' %s', $propertyName), ''); if ($property instanceof FieldMetadata) { $output = array_merge($output, $this->formatColumn($property)); } elseif ($property instanceof AssociationMetadata) { // @todo guilhermeblanco Fix me! We are trying to iterate through an AssociationMetadata instance foreach ($property as $field => $value) { $output[] = $this->formatField(sprintf(' %s', $field), $this->formatValue($value)); } } } return $output; }
php
{ "resource": "" }
q14597
Autoloader.resolveFile
train
public static function resolveFile(string $metadataDir, string $metadataNamespace, string $className) : string { if (strpos($className, $metadataNamespace) !== 0) { throw new InvalidArgumentException( sprintf('The class "%s" is not part of the metadata namespace "%s"', $className, $metadataNamespace) ); } // remove metadata namespace from class name $classNameRelativeToMetadataNamespace = substr($className, strlen($metadataNamespace)); // remove namespace separators from remaining class name $fileName = str_replace('\\', '', $classNameRelativeToMetadataNamespace); return $metadataDir . DIRECTORY_SEPARATOR . $fileName . '.php'; }
php
{ "resource": "" }
q14598
Autoloader.register
train
public static function register( string $metadataDir, string $metadataNamespace, ?callable $notFoundCallback = null ) : Closure { $metadataNamespace = ltrim($metadataNamespace, '\\'); if (! ($notFoundCallback === null || is_callable($notFoundCallback))) { $type = is_object($notFoundCallback) ? get_class($notFoundCallback) : gettype($notFoundCallback); throw new InvalidArgumentException( sprintf('Invalid \$notFoundCallback given: must be a callable, "%s" given', $type) ); } $autoloader = static function ($className) use ($metadataDir, $metadataNamespace, $notFoundCallback) { if (strpos($className, $metadataNamespace) === 0) { $file = Autoloader::resolveFile($metadataDir, $metadataNamespace, $className); if ($notFoundCallback && ! file_exists($file)) { call_user_func($notFoundCallback, $metadataDir, $metadataNamespace, $className); } require $file; } }; spl_autoload_register($autoloader); return $autoloader; }
php
{ "resource": "" }
q14599
HydrationCompleteHandler.deferPostLoadInvoking
train
public function deferPostLoadInvoking(ClassMetadata $class, $entity) { $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postLoad); if ($invoke === ListenersInvoker::INVOKE_NONE) { return; } $this->deferredPostLoadInvocations[] = [$class, $invoke, $entity]; }
php
{ "resource": "" }