idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
1,100
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 ; }
Remove all media in the given collection .
1,101
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 ; }
Remove all media in the given collection except some .
1,102
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 ( ) ; }
Delete the associated media with the given id . You may also pass a media object .
1,103
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 ( ) ; }
Cache the media on the object .
1,104
protected function cleanParams ( array $ params ) { $ values = [ ] ; foreach ( $ params as $ name => $ details ) { $ this -> cleanValueFrom ( $ name , $ details [ 'value' ] , $ values ) ; } return $ values ; }
Create proper arrays from dot - noted parameter names .
1,105
protected function cleanValueFrom ( $ name , $ value , array & $ values = [ ] ) { if ( str_contains ( $ name , '[' ) ) { $ name = str_replace ( [ '][' , '[' , ']' , '..' ] , [ '.' , '.' , '' , '.*.' ] , $ name ) ; } array_set ( $ values , str_replace ( '.*' , '.0' , $ name ) , $ value ) ; }
Converts dot notation names to arrays and sets the value at the right depth .
1,106
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 ) ; }
Get the response from the docblock if available .
1,107
protected function getFileResponses ( array $ tags ) { $ 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 ) ; }
Get the response from the file if available .
1,108
private function castToType ( string $ value , string $ type ) { $ casts = [ 'integer' => 'intval' , 'number' => 'floatval' , 'float' => 'floatval' , 'boolean' => 'boolval' , ] ; if ( $ value == 'false' && $ type == 'boolean' ) { return false ; } if ( isset ( $ casts [ $ type ] ) ) { return $ casts [ $ type ] ( $ value ) ; } return $ value ; }
Cast a value from a string to a specified type .
1,109
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 ; } }
Get a response from the transformer tags .
1,110
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 ; }
Get current lfm type .
1,111
public function translateFromUtf8 ( $ input ) { if ( $ this -> isRunningOnWindows ( ) ) { $ input = iconv ( 'UTF-8' , mb_detect_encoding ( $ input ) , $ input ) ; } return $ input ; }
Translate file name to make it compatible on Windows .
1,112
public static function routes ( ) { $ middleware = [ CreateDefaultFolder :: class , MultiUser :: class ] ; $ as = 'unisharp.lfm.' ; $ namespace = '\\UniSharp\\LaravelFilemanager\\Controllers\\' ; Route :: group ( compact ( 'middleware' , 'as' , 'namespace' ) , function ( ) { Route :: get ( '/' , [ 'uses' => 'LfmController@show' , 'as' => 'show' , ] ) ; Route :: get ( '/errors' , [ 'uses' => 'LfmController@getErrors' , 'as' => 'getErrors' , ] ) ; Route :: any ( '/upload' , [ 'uses' => 'UploadController@upload' , 'as' => 'upload' , ] ) ; Route :: get ( '/jsonitems' , [ 'uses' => 'ItemsController@getItems' , 'as' => 'getItems' , ] ) ; Route :: get ( '/move' , [ 'uses' => 'ItemsController@move' , 'as' => 'move' , ] ) ; Route :: get ( '/domove' , [ 'uses' => 'ItemsController@domove' , 'as' => 'domove' ] ) ; Route :: get ( '/newfolder' , [ 'uses' => 'FolderController@getAddfolder' , 'as' => 'getAddfolder' , ] ) ; Route :: get ( '/folders' , [ 'uses' => 'FolderController@getFolders' , 'as' => 'getFolders' , ] ) ; Route :: get ( '/crop' , [ 'uses' => 'CropController@getCrop' , 'as' => 'getCrop' , ] ) ; Route :: get ( '/cropimage' , [ 'uses' => 'CropController@getCropimage' , 'as' => 'getCropimage' , ] ) ; Route :: get ( '/cropnewimage' , [ 'uses' => 'CropController@getNewCropimage' , 'as' => 'getCropimage' , ] ) ; Route :: get ( '/rename' , [ 'uses' => 'RenameController@getRename' , 'as' => 'getRename' , ] ) ; Route :: get ( '/resize' , [ 'uses' => 'ResizeController@getResize' , 'as' => 'getResize' , ] ) ; Route :: get ( '/doresize' , [ 'uses' => 'ResizeController@performResize' , 'as' => 'performResize' , ] ) ; Route :: get ( '/download' , [ 'uses' => 'DownloadController@getDownload' , 'as' => 'getDownload' , ] ) ; Route :: get ( '/delete' , [ 'uses' => 'DeleteController@getDelete' , 'as' => 'getDelete' , ] ) ; Route :: get ( '/demo' , 'DemoController@index' ) ; } ) ; }
Generates routes of this package .
1,113
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' ) , ] ; }
Get the images to load for a selected folder .
1,114
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 ; }
Add a new folder .
1,115
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 ; }
Delete image and associated thumbnail .
1,116
public function createFolder ( ) { if ( $ this -> storage -> exists ( $ this ) ) { return false ; } $ this -> storage -> makeDirectory ( 0777 , true , true ) ; }
Create folder if not exist .
1,117
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 ; }
Sort files and directories .
1,118
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 ; }
Check if any extension or config is missing .
1,119
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 ) ; } } }
Overrides settings in php . ini .
1,120
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 ; 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 ) ; }
Dipsplay image for resizing .
1,121
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 ; }
Add a domain to an allowed access list .
1,122
public function setSiteControl ( $ permittedCrossDomainPolicies = 'all' ) { if ( ! $ this -> validateSiteControl ( $ permittedCrossDomainPolicies ) ) { throw new \ UnexpectedValueException ( 'Invalid site control set' ) ; } $ this -> _siteControl = $ permittedCrossDomainPolicies ; $ this -> _cacheValid = false ; return $ this ; }
site - control defines the meta - policy for the current domain . A meta - policy specifies acceptable domain policy files other than the master policy file located in the target domain s root and named crossdomain . xml .
1,123
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 ; }
Builds the crossdomain file based on the template policy
1,124
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 ; }
Send a message to all the connections in this topic
1,125
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 ) ; } ) ; }
Triggered when a new connection is received from React
1,126
public function handleData ( $ data , $ conn ) { try { $ this -> app -> onMessage ( $ conn -> decor , $ data ) ; } catch ( \ Exception $ e ) { $ this -> handleError ( $ e , $ conn ) ; } }
Data has been received from React
1,127
public function handleEnd ( $ conn ) { try { $ this -> app -> onClose ( $ conn -> decor ) ; } catch ( \ Exception $ e ) { $ this -> handleError ( $ e , $ conn ) ; } unset ( $ conn -> decor ) ; }
A connection has been closed by React
1,128
public function handleError ( \ Exception $ e , $ conn ) { $ this -> app -> onError ( $ conn -> decor , $ e ) ; }
An error has occurred let the listening application know
1,129
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 ( ) ; }
Close a connection with an HTTP response
1,130
private function parseCookie ( $ cookie , $ host = null , $ path = null , $ decode = false ) { $ pieces = array_filter ( array_map ( 'trim' , explode ( ';' , $ cookie ) ) ) ; if ( empty ( $ pieces ) || ! strpos ( $ pieces [ 0 ] , '=' ) ) { return false ; } $ 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 ; foreach ( $ pieces as $ part ) { $ cookieParts = explode ( '=' , $ part , 2 ) ; $ key = trim ( $ cookieParts [ 0 ] ) ; if ( count ( $ cookieParts ) == 1 ) { $ value = true ; } else { $ value = trim ( $ cookieParts [ 1 ] , " \n\r\t\0\x0B\"" ) ; if ( $ decode ) { $ value = urldecode ( $ value ) ; } } 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 ; } } } $ data [ $ foundNonCookies ? 'data' : 'cookies' ] [ $ key ] = $ value ; } if ( ! $ data [ 'expires' ] && $ data [ 'max_age' ] ) { $ data [ 'expires' ] = time ( ) + ( int ) $ data [ 'max_age' ] ; } return $ data ; }
Taken from Guzzle3
1,131
public function unblockAddress ( $ ip ) { if ( isset ( $ this -> _blacklist [ $ this -> filterAddress ( $ ip ) ] ) ) { unset ( $ this -> _blacklist [ $ this -> filterAddress ( $ ip ) ] ) ; } return $ this ; }
Unblock an address so they can access your application again
1,132
public function callResult ( $ id , $ data = array ( ) ) { return $ this -> send ( json_encode ( array ( WAMP :: MSG_CALL_RESULT , $ id , $ data ) ) ) ; }
Successfully respond to a call made by the client
1,133
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 ) ) ; }
Respond with an error to a client call
1,134
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 ; }
Get the full request URI from the connection object if a prefix has been established for it
1,135
public function setValue ( $ value , $ type = null ) { $ this -> value = $ value ; $ this -> type = $ type ? : ParameterTypeInferer :: inferType ( $ value ) ; }
Defines the Parameter value .
1,136
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 ] ; }
Gets the element of schema meta data for the class from the mapping file . This will lazily load the mapping file if it is not loaded yet .
1,137
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 ) ) ; } } } }
Initializes the class cache from all the global files .
1,138
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 { $ rootAlias = $ this -> getRootAlias ( ) ; } $ this -> joinRootAliases [ $ alias ] = $ rootAlias ; return $ rootAlias ; }
Finds the root entity alias of the joined entity .
1,139
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 ; }
Gets the root aliases of the query . This is the entity aliases involved in the construction of the query .
1,140
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 ; }
Gets the root entities of the query . This is the entity aliases involved in the construction of the query .
1,141
public function update ( $ update = null , $ alias = null ) { $ this -> type = self :: UPDATE ; if ( ! $ update ) { return $ this ; } return $ this -> add ( 'from' , new Expr \ From ( $ update , $ alias ) ) ; }
Turns the query being built into a bulk update query that ranges over a certain entity type .
1,142
public function from ( $ from , $ alias , $ indexBy = null ) { return $ this -> add ( 'from' , new Expr \ From ( $ from , $ alias , $ indexBy ) , true ) ; }
Creates and adds a query root corresponding to the entity identified by the given alias forming a cartesian product with any existing query roots .
1,143
public function set ( $ key , $ value ) { return $ this -> add ( 'set' , new Expr \ Comparison ( $ key , Expr \ Comparison :: EQ , $ value ) , true ) ; }
Sets a new value for a field in a bulk update query .
1,144
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 ( ) ; if ( $ firstResult !== null ) { $ this -> setFirstResult ( $ firstResult ) ; } if ( $ maxResults !== null ) { $ this -> setMaxResults ( $ maxResults ) ; } return $ this ; }
Adds criteria to the query .
1,145
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 ) ; } } }
Creates the database schema for the given array of ClassMetadata instances .
1,146
public function getCreateSchemaSql ( array $ classes ) { $ schema = $ this -> getSchemaFromMetadata ( $ classes ) ; return $ schema -> toSql ( $ this -> platform ) ; }
Gets the list of DDL statements that are required to create the database schema for the given list of ClassMetadata instances .
1,147
public function dropSchema ( array $ classes ) { $ dropSchemaSql = $ this -> getDropSchemaSQL ( $ classes ) ; $ conn = $ this -> em -> getConnection ( ) ; foreach ( $ dropSchemaSql as $ sql ) { try { $ conn -> executeQuery ( $ sql ) ; } catch ( Throwable $ e ) { } } }
Drops the database schema for the given classes .
1,148
public function dropDatabase ( ) { $ dropSchemaSql = $ this -> getDropDatabaseSQL ( ) ; $ conn = $ this -> em -> getConnection ( ) ; foreach ( $ dropSchemaSql as $ sql ) { $ conn -> executeQuery ( $ sql ) ; } }
Drops all elements in the database of the current connection .
1,149
public function getDropDatabaseSQL ( ) { $ sm = $ this -> em -> getConnection ( ) -> getSchemaManager ( ) ; $ schema = $ sm -> createSchema ( ) ; $ visitor = new DropSchemaSqlCollector ( $ this -> platform ) ; $ schema -> visit ( $ visitor ) ; return $ visitor -> getQueries ( ) ; }
Gets the SQL needed to drop the database schema for the connections database .
1,150
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 ) { 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 ) { 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 ( ) ; }
Gets SQL to drop the tables defined by the passed classes .
1,151
public function updateSchema ( array $ classes , $ saveMode = false ) { $ updateSchemaSql = $ this -> getUpdateSchemaSql ( $ classes , $ saveMode ) ; $ conn = $ this -> em -> getConnection ( ) ; foreach ( $ updateSchemaSql as $ sql ) { $ conn -> executeQuery ( $ sql ) ; } }
Updates the database schema of the given classes by comparing the ClassMetadata instances to the current database schema that is inspected .
1,152
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 ) ; }
Gets the sequence of SQL statements that need to be performed in order to bring the given class mappings in - synch with the relational schema .
1,153
public function setParameters ( $ parameters ) { 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 ; }
Sets a collection of query parameters .
1,154
private function createRepository ( EntityManagerInterface $ entityManager , $ entityName ) { $ metadata = $ entityManager -> getClassMetadata ( $ entityName ) ; $ repositoryClassName = $ metadata -> getCustomRepositoryClassName ( ) ? : $ entityManager -> getConfiguration ( ) -> getDefaultRepositoryClassName ( ) ; return new $ repositoryClassName ( $ entityManager , $ metadata ) ; }
Create a new repository instance for an entity class .
1,155
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 ) ; }
Return a valid order list of all current nodes . The desired topological sorting is the reverse post order of these searches .
1,156
public function validateLifecycleCallbacks ( ReflectionService $ reflectionService ) : void { foreach ( $ this -> lifecycleCallbacks as $ callbacks ) { foreach ( $ callbacks as $ callbackFuncName ) { if ( ! $ reflectionService -> hasPublicMethod ( $ this -> className , $ callbackFuncName ) ) { throw MappingException :: lifecycleCallbackMethodNotFound ( $ this -> className , $ callbackFuncName ) ; } } } }
Validates lifecycle callbacks .
1,157
protected function validateAndCompleteToOneAssociationMetadata ( ToOneAssociationMetadata $ property ) { $ fieldName = $ property -> getName ( ) ; if ( $ property -> isOwningSide ( ) ) { if ( empty ( $ property -> getJoinColumns ( ) ) ) { $ property -> addJoinColumn ( new JoinColumnMetadata ( ) ) ; } $ uniqueConstraintColumns = [ ] ; foreach ( $ property -> getJoinColumns ( ) as $ 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 ) ; } } if ( $ property -> isPrimaryKey ( ) && ! $ property -> isOwningSide ( ) ) { throw MappingException :: illegalInverseIdentifierAssociation ( $ this -> className , $ fieldName ) ; } }
Validates & completes a to - one association mapping .
1,158
protected function validateAndCompleteManyToOneMapping ( ManyToOneAssociationMetadata $ property ) { if ( $ property -> isOrphanRemoval ( ) ) { throw MappingException :: illegalOrphanRemoval ( $ this -> className , $ property -> getName ( ) ) ; } }
Validates & completes a many - to - one association mapping .
1,159
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 ] ; }
Gets the name of the single id field . Note that this only works on entity classes that have a single - field pk .
1,160
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 ; } $ 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 ) { $ columnName = $ joinColumn -> getColumnName ( ) ; $ referencedColumnName = $ joinColumn -> getReferencedColumnName ( ) ; if ( ! $ joinColumn -> getType ( ) ) { $ joinColumn -> setType ( PersisterHelper :: getTypeOfColumn ( $ referencedColumnName , $ targetClass , $ em ) ) ; } $ columns [ $ columnName ] = $ joinColumn ; } } return $ columns ; }
Returns an array with identifier column names and their corresponding ColumnMetadata .
1,161
public function getTemporaryIdTableName ( ) : string { $ schema = $ this -> getSchemaName ( ) === null ? '' : $ this -> getSchemaName ( ) . '_' ; return $ schema . $ this -> getTableName ( ) . '_id_tmp' ; }
Gets the table name to use for temporary identifier tables of this class .
1,162
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 ( $ originalPropertyClassName === TransientMetadata :: class ) { unset ( $ this -> declaredProperties [ $ fieldName ] ) ; $ this -> addProperty ( $ property ) ; return ; } if ( $ originalPropertyClassName !== get_class ( $ property ) ) { throw MappingException :: invalidOverridePropertyType ( $ this -> className , $ fieldName ) ; } if ( $ originalProperty instanceof VersionFieldMetadata ) { throw MappingException :: invalidOverrideVersionField ( $ this -> className , $ fieldName ) ; } unset ( $ this -> declaredProperties [ $ fieldName ] ) ; if ( $ property instanceof FieldMetadata ) { unset ( $ this -> fieldNames [ $ originalProperty -> getColumnName ( ) ] ) ; $ property -> setDeclaringClass ( $ originalProperty -> getDeclaringClass ( ) ) ; $ property -> setPrimaryKey ( $ originalProperty -> isPrimaryKey ( ) ) ; } elseif ( $ property instanceof AssociationMetadata ) { if ( $ originalProperty instanceof ToOneAssociationMetadata && $ originalProperty -> isOwningSide ( ) ) { foreach ( $ originalProperty -> getJoinColumns ( ) as $ joinColumn ) { unset ( $ this -> fieldNames [ $ joinColumn -> getColumnName ( ) ] ) ; } } 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 ) ; }
Sets the override property mapping for an entity relationship .
1,163
public function isInheritedProperty ( $ fieldName ) { $ declaringClass = $ this -> declaredProperties [ $ fieldName ] -> getDeclaringClass ( ) ; return $ declaringClass -> className !== $ this -> className ; }
Checks whether a mapped field is inherited from a superclass .
1,164
public function addProperty ( Property $ property ) { $ fieldName = $ property -> getName ( ) ; 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 : break ; } $ this -> addDeclaredProperty ( $ property ) ; }
Add a property mapping .
1,165
private function updateResultPointer ( array & $ coll , $ index , $ dqlAlias , $ oneToOne ) { if ( $ coll === null ) { unset ( $ this -> resultPointers [ $ dqlAlias ] ) ; 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 ) ] ; }
Updates the result pointer for an Entity . The result pointers point to the last seen instance of each Entity type . This is used for graph construction .
1,166
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 ( ) ) ; }
Check if the platform supports the ROW_NUMBER window function .
1,167
public function walkSelectStatement ( SelectStatement $ AST ) { if ( $ this -> platformSupportsRowNumber ( ) ) { return $ this -> walkSelectStatementWithRowNumber ( $ AST ) ; } return $ this -> walkSelectStatementWithoutRowNumber ( $ AST ) ; }
Walks down a SelectStatement AST node wrapping it in a SELECT DISTINCT .
1,168
public function walkSelectStatementWithoutRowNumber ( SelectStatement $ AST , $ addMissingItemsFromOrderByToSelect = true ) { if ( $ AST -> orderByClause instanceof OrderByClause && $ addMissingItemsFromOrderByToSelect ) { $ this -> addMissingItemsFromOrderByToSelect ( $ AST ) ; } $ orderByClause = $ AST -> orderByClause ; $ AST -> orderByClause = null ; $ innerSql = $ this -> getInnerSQL ( $ AST ) ; $ sqlIdentifier = $ this -> getSQLIdentifier ( $ AST ) ; $ sqlAliasIdentifier = array_map ( static function ( $ info ) { return $ info [ 'alias' ] ; } , $ sqlIdentifier ) ; $ sql = sprintf ( 'SELECT DISTINCT %s FROM (%s) dctrn_result' , implode ( ', ' , $ sqlAliasIdentifier ) , $ innerSql ) ; $ sql = $ this -> preserveSqlOrdering ( $ sqlAliasIdentifier , $ innerSql , $ sql , $ orderByClause ) ; $ sql = $ this -> platform -> modifyLimitQuery ( $ sql , $ this -> maxResults , $ this -> firstResult ?? 0 ) ; foreach ( $ sqlIdentifier as $ property => $ propertyMapping ) { $ this -> rsm -> addScalarResult ( $ propertyMapping [ 'alias' ] , $ property , $ propertyMapping [ 'type' ] ) ; } $ AST -> orderByClause = $ orderByClause ; return $ sql ; }
Walks down a SelectStatement AST node wrapping it in a SELECT DISTINCT . This method is for platforms which DO NOT support ROW_NUMBER .
1,169
private function addMissingItemsFromOrderByToSelect ( SelectStatement $ AST ) { $ this -> orderByPathExpressions = [ ] ; $ walker = clone $ this ; $ walker -> walkSelectStatementWithoutRowNumber ( $ AST , false ) ; $ orderByPathExpressions = $ walker -> getOrderByPathExpressions ( ) ; $ selects = [ ] ; foreach ( $ orderByPathExpressions as $ pathExpression ) { $ idVar = $ pathExpression -> identificationVariable ; $ field = $ pathExpression -> field ; if ( ! isset ( $ selects [ $ idVar ] ) ) { $ selects [ $ idVar ] = [ ] ; } $ selects [ $ idVar ] [ $ field ] = true ; } foreach ( $ AST -> selectClause -> selectExpressions as $ selectExpression ) { if ( $ selectExpression instanceof SelectExpression ) { $ idVar = $ selectExpression -> expression ; if ( ! is_string ( $ idVar ) ) { continue ; } $ field = $ selectExpression -> fieldIdentificationVariable ; if ( $ field === null ) { unset ( $ selects [ $ idVar ] ) ; } else { unset ( $ selects [ $ idVar ] [ $ field ] ) ; } } } foreach ( $ selects as $ idVar => $ fields ) { $ selectExpression = new SelectExpression ( new PartialObjectExpression ( $ idVar , array_keys ( $ fields ) ) , null , true ) ; $ AST -> selectClause -> selectExpressions [ ] = $ selectExpression ; } }
Finds all PathExpressions in an AST s OrderByClause and ensures that the referenced fields are present in the SelectClause of the passed AST .
1,170
private function recreateInnerSql ( OrderByClause $ orderByClause , array $ identifiers , string $ innerSql ) : string { [ $ searchPatterns , $ replacements ] = $ this -> generateSqlAliasReplacements ( ) ; $ orderByItems = [ ] ; foreach ( $ orderByClause -> orderByItems as $ orderByItem ) { $ 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 ) ) ; }
Generates a new SQL statement for the inner query to keep the correct sorting
1,171
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 ) ; } }
Clears cache entries related to the current collection
1,172
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 ; }
Parse the given JoinTable as JoinTableMetadata
1,173
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 ; }
Attempts to resolve the cascade modes .
1,174
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 ) ) ; } }
Clears the EntityManager . All entities that are currently managed by this EntityManager become detached .
1,175
public function persist ( $ entity ) { if ( ! is_object ( $ entity ) ) { throw ORMInvalidArgumentException :: invalidObject ( 'EntityManager#persist()' , $ entity ) ; } $ this -> errorIfClosed ( ) ; $ this -> unitOfWork -> persist ( $ entity ) ; }
Tells the EntityManager to make an instance managed and persistent .
1,176
public function refresh ( $ entity ) { if ( ! is_object ( $ entity ) ) { throw ORMInvalidArgumentException :: invalidObject ( 'EntityManager#refresh()' , $ entity ) ; } $ this -> errorIfClosed ( ) ; $ this -> unitOfWork -> refresh ( $ entity ) ; }
Refreshes the persistent state of an entity from the database overriding any local changes that have not yet been persisted .
1,177
public function contains ( $ entity ) { return $ this -> unitOfWork -> isScheduledForInsert ( $ entity ) || ( $ this -> unitOfWork -> isInIdentityMap ( $ entity ) && ! $ this -> unitOfWork -> isScheduledForDelete ( $ entity ) ) ; }
Determines whether an entity instance is managed in this EntityManager .
1,178
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 ; }
Factory method to create Connection instances .
1,179
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 ) ) ; }
Return the class metadata for the given entity name
1,180
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 ) ) ) ; }
Format the given value for console output
1,181
private function formatField ( $ label , $ value ) { if ( $ value === null ) { $ value = '<comment>None</comment>' ; } return [ sprintf ( '<info>%s</info>' , $ label ) , $ this -> formatValue ( $ value ) ] ; }
Add the given label and value to the two column table output
1,182
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 ) { foreach ( $ property as $ field => $ value ) { $ output [ ] = $ this -> formatField ( sprintf ( ' %s' , $ field ) , $ this -> formatValue ( $ value ) ) ; } } } return $ output ; }
Format the property mappings
1,183
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 ) ) ; } $ classNameRelativeToMetadataNamespace = substr ( $ className , strlen ( $ metadataNamespace ) ) ; $ fileName = str_replace ( '\\' , '' , $ classNameRelativeToMetadataNamespace ) ; return $ metadataDir . DIRECTORY_SEPARATOR . $ fileName . '.php' ; }
Resolves ClassMetadata class name to a filename based on the following pattern .
1,184
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 ; }
Registers and returns autoloader callback for the given metadata dir and namespace .
1,185
public function deferPostLoadInvoking ( ClassMetadata $ class , $ entity ) { $ invoke = $ this -> listenersInvoker -> getSubscribedSystems ( $ class , Events :: postLoad ) ; if ( $ invoke === ListenersInvoker :: INVOKE_NONE ) { return ; } $ this -> deferredPostLoadInvocations [ ] = [ $ class , $ invoke , $ entity ] ; }
Method schedules invoking of postLoad entity to the very end of current hydration cycle .
1,186
public function hydrationComplete ( ) { $ toInvoke = $ this -> deferredPostLoadInvocations ; $ this -> deferredPostLoadInvocations = [ ] ; foreach ( $ toInvoke as $ classAndEntity ) { [ $ class , $ invoke , $ entity ] = $ classAndEntity ; $ this -> listenersInvoker -> invoke ( $ class , Events :: postLoad , $ entity , new LifecycleEventArgs ( $ entity , $ this -> em ) , $ invoke ) ; } }
This method should me called after any hydration cycle completed .
1,187
private function getOrCreateClassMetadataDefinition ( string $ className , ? ClassMetadata $ parent ) : ClassMetadataDefinition { if ( ! isset ( $ this -> definitions [ $ className ] ) ) { $ this -> definitions [ $ className ] = $ this -> definitionFactory -> build ( $ className , $ parent ) ; } return $ this -> definitions [ $ className ] ; }
Create a class metadata definition for the given class name .
1,188
public function clearRegionStats ( $ regionName ) { $ this -> cachePutCountMap [ $ regionName ] = 0 ; $ this -> cacheHitCountMap [ $ regionName ] = 0 ; $ this -> cacheMissCountMap [ $ regionName ] = 0 ; }
Clear region statistics
1,189
protected function getSelectColumnSQL ( $ field , ClassMetadata $ class , $ alias = 'r' ) { $ property = $ class -> getProperty ( $ field ) ; $ columnAlias = $ this -> getSQLColumnAlias ( ) ; $ sql = sprintf ( '%s.%s' , $ this -> getSQLTableAlias ( $ property -> getTableName ( ) , ( $ alias === 'r' ? '' : $ alias ) ) , $ this -> platform -> quoteIdentifier ( $ property -> getColumnName ( ) ) ) ; $ this -> currentPersisterContext -> rsm -> addFieldResult ( $ alias , $ columnAlias , $ field , $ class -> getClassName ( ) ) ; return $ property -> getType ( ) -> convertToPHPValueSQL ( $ sql , $ this -> platform ) . ' AS ' . $ columnAlias ; }
Gets the SQL snippet of a qualified column name for the given field name .
1,190
protected function getSelectConditionCriteriaSQL ( Criteria $ criteria ) { $ expression = $ criteria -> getWhereExpression ( ) ; if ( $ expression === null ) { return '' ; } $ visitor = new SqlExpressionVisitor ( $ this , $ this -> class ) ; return $ visitor -> dispatch ( $ expression ) ; }
Gets the Select Where Condition from a Criteria object .
1,191
private function getIndividualValue ( $ value ) { if ( ! is_object ( $ value ) || ! $ this -> em -> getMetadataFactory ( ) -> hasMetadataFor ( StaticClassNameConverter :: getClass ( $ value ) ) ) { return $ value ; } return $ this -> em -> getUnitOfWork ( ) -> getSingleIdentifierValue ( $ value ) ; }
Retrieves an individual parameter value .
1,192
protected function getJoinSQLForAssociation ( AssociationMetadata $ association ) { if ( ! $ association -> isOwningSide ( ) ) { return 'LEFT JOIN' ; } foreach ( $ association -> getJoinColumns ( ) as $ joinColumn ) { if ( ! $ joinColumn -> isNullable ( ) ) { continue ; } return 'LEFT JOIN' ; } return 'INNER JOIN' ; }
Generates the appropriate join SQL for the given association .
1,193
public function setSQLTableAlias ( $ tableName , $ alias , $ dqlAlias = '' ) { $ tableName .= $ dqlAlias ? '@[' . $ dqlAlias . ']' : '' ; $ this -> tableAliasMap [ $ tableName ] = $ alias ; return $ alias ; }
Forces the SqlWalker to use a specific alias for a table name rather than generating an alias on its own .
1,194
public function walkIdentificationVariableDeclaration ( $ identificationVariableDecl ) { $ sql = $ this -> walkRangeVariableDeclaration ( $ identificationVariableDecl -> rangeVariableDeclaration ) ; if ( $ identificationVariableDecl -> indexBy ) { $ this -> walkIndexBy ( $ identificationVariableDecl -> indexBy ) ; } foreach ( $ identificationVariableDecl -> joins as $ join ) { $ sql .= $ this -> walkJoin ( $ join ) ; } return $ sql ; }
Walks down a IdentificationVariableDeclaration AST node thereby generating the appropriate SQL .
1,195
public function walkIndexBy ( $ indexBy ) { $ pathExpression = $ indexBy -> simpleStateFieldPathExpression ; $ alias = $ pathExpression -> identificationVariable ; $ field = $ pathExpression -> field ; if ( isset ( $ this -> scalarFields [ $ alias ] [ $ field ] ) ) { $ this -> rsm -> addIndexByScalar ( $ this -> scalarFields [ $ alias ] [ $ field ] ) ; return ; } $ this -> rsm -> addIndexBy ( $ alias , $ field ) ; }
Walks down a IndexBy AST node .
1,196
private function generateRangeVariableDeclarationSQL ( $ rangeVariableDeclaration , bool $ buildNestedJoins ) : string { $ class = $ this -> em -> getClassMetadata ( $ rangeVariableDeclaration -> abstractSchemaName ) ; $ dqlAlias = $ rangeVariableDeclaration -> aliasIdentificationVariable ; if ( $ rangeVariableDeclaration -> isRoot ) { $ this -> rootAliases [ ] = $ dqlAlias ; } $ tableName = $ class -> table -> getQuotedQualifiedName ( $ this -> platform ) ; $ tableAlias = $ this -> getSQLTableAlias ( $ class -> getTableName ( ) , $ dqlAlias ) ; $ sql = $ this -> platform -> appendLockHint ( $ tableName . ' ' . $ tableAlias , $ this -> query -> getHint ( Query :: HINT_LOCK_MODE ) ) ; if ( $ class -> inheritanceType !== InheritanceType :: JOINED ) { return $ sql ; } $ classTableInheritanceJoins = $ this -> generateClassTableInheritanceJoins ( $ class , $ dqlAlias ) ; if ( ! $ buildNestedJoins ) { return $ sql . $ classTableInheritanceJoins ; } return $ classTableInheritanceJoins === '' ? $ sql : '(' . $ sql . $ classTableInheritanceJoins . ')' ; }
Generate appropriate SQL for RangeVariableDeclaration AST node
1,197
public function walkCoalesceExpression ( $ coalesceExpression ) { $ sql = 'COALESCE(' ; $ scalarExpressions = [ ] ; foreach ( $ coalesceExpression -> scalarExpressions as $ scalarExpression ) { $ scalarExpressions [ ] = $ this -> walkSimpleArithmeticExpression ( $ scalarExpression ) ; } return $ sql . implode ( ', ' , $ scalarExpressions ) . ')' ; }
Walks down a CoalesceExpression AST node and generates the corresponding SQL .
1,198
public function walkNullIfExpression ( $ nullIfExpression ) { $ firstExpression = is_string ( $ nullIfExpression -> firstExpression ) ? $ this -> conn -> quote ( $ nullIfExpression -> firstExpression ) : $ this -> walkSimpleArithmeticExpression ( $ nullIfExpression -> firstExpression ) ; $ secondExpression = is_string ( $ nullIfExpression -> secondExpression ) ? $ this -> conn -> quote ( $ nullIfExpression -> secondExpression ) : $ this -> walkSimpleArithmeticExpression ( $ nullIfExpression -> secondExpression ) ; return 'NULLIF(' . $ firstExpression . ', ' . $ secondExpression . ')' ; }
Walks down a NullIfExpression AST node and generates the corresponding SQL .
1,199
public function walkGeneralCaseExpression ( AST \ GeneralCaseExpression $ generalCaseExpression ) { $ sql = 'CASE' ; foreach ( $ generalCaseExpression -> whenClauses as $ whenClause ) { $ sql .= ' WHEN ' . $ this -> walkConditionalExpression ( $ whenClause -> caseConditionExpression ) ; $ sql .= ' THEN ' . $ this -> walkSimpleArithmeticExpression ( $ whenClause -> thenScalarExpression ) ; } $ sql .= ' ELSE ' . $ this -> walkSimpleArithmeticExpression ( $ generalCaseExpression -> elseScalarExpression ) . ' END' ; return $ sql ; }
Walks down a GeneralCaseExpression AST node and generates the corresponding SQL .