idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
8,400
public static function normilizeScopeName ( $ name ) { foreach ( self :: $ reservedWordList as $ reservedWord ) { if ( $ reservedWord . 'Obj' == $ name ) { return $ reservedWord ; } } return $ name ; }
Remove Obj if name is reserved PHP word .
8,401
public static function getNaming ( $ name , $ prePostFix , $ type = 'prefix' , $ symbol = '_' ) { if ( $ type == 'prefix' ) { return static :: toCamelCase ( $ prePostFix . $ symbol . $ name , $ symbol ) ; } else if ( $ type == 'postfix' ) { return static :: toCamelCase ( $ name . $ symbol . $ prePostFix , $ symbol ) ; } return null ; }
Get Naming according to prefix or postfix type
8,402
public static function unsetInArray ( array $ content , $ unsets , $ unsetParentEmptyArray = false ) { if ( empty ( $ unsets ) ) { return $ content ; } if ( is_string ( $ unsets ) ) { $ unsets = ( array ) $ unsets ; } foreach ( $ unsets as $ rootKey => $ unsetItem ) { $ unsetItem = is_array ( $ unsetItem ) ? $ unsetItem : ( array ) $ unsetItem ; foreach ( $ unsetItem as $ unsetString ) { if ( is_string ( $ rootKey ) ) { $ unsetString = $ rootKey . '.' . $ unsetString ; } $ keyArr = explode ( '.' , $ unsetString ) ; $ keyChainCount = count ( $ keyArr ) - 1 ; $ elem = & $ content ; $ elementArr = [ ] ; $ elementArr [ ] = & $ elem ; for ( $ i = 0 ; $ i <= $ keyChainCount ; $ i ++ ) { if ( is_array ( $ elem ) && array_key_exists ( $ keyArr [ $ i ] , $ elem ) ) { if ( $ i == $ keyChainCount ) { unset ( $ elem [ $ keyArr [ $ i ] ] ) ; if ( $ unsetParentEmptyArray ) { for ( $ j = count ( $ elementArr ) ; $ j > 0 ; $ j -- ) { $ pointer = & $ elementArr [ $ j ] ; if ( is_array ( $ pointer ) && empty ( $ pointer ) ) { $ previous = & $ elementArr [ $ j - 1 ] ; unset ( $ previous [ $ keyArr [ $ j - 1 ] ] ) ; } } } } else if ( is_array ( $ elem [ $ keyArr [ $ i ] ] ) ) { $ elem = & $ elem [ $ keyArr [ $ i ] ] ; $ elementArr [ ] = & $ elem ; } } } } } return $ content ; }
Unset content items defined in the unset . json
8,403
public static function getClassName ( $ filePath ) { $ className = preg_replace ( '/\.php$/i' , '' , $ filePath ) ; $ className = preg_replace ( '/^(application|custom)(\/|\\\)/i' , '' , $ className ) ; $ className = '\\' . static :: toFormat ( $ className , '\\' ) ; return $ className ; }
Get class name from the file path
8,404
public static function isEquals ( $ var1 , $ var2 ) { if ( is_array ( $ var1 ) ) { static :: ksortRecursive ( $ var1 ) ; } if ( is_array ( $ var2 ) ) { static :: ksortRecursive ( $ var2 ) ; } return ( $ var1 === $ var2 ) ; }
Check if two variables are equals
8,405
public static function ksortRecursive ( & $ array ) { if ( ! is_array ( $ array ) ) { return false ; } ksort ( $ array ) ; foreach ( $ array as $ key => $ value ) { static :: ksortRecursive ( $ array [ $ key ] ) ; } return true ; }
Sort array recursively
8,406
public static function arrayDiff ( array $ array1 , array $ array2 ) { $ diff = array ( ) ; foreach ( $ array1 as $ key1 => $ value1 ) { if ( array_key_exists ( $ key1 , $ array2 ) ) { if ( $ value1 !== $ array2 [ $ key1 ] ) { $ diff [ $ key1 ] = $ array2 [ $ key1 ] ; } continue ; } $ diff [ $ key1 ] = $ value1 ; } $ diff = array_merge ( $ diff , array_diff_key ( $ array2 , $ array1 ) ) ; return $ diff ; }
Improved computing the difference of arrays
8,407
public static function fillArrayKeys ( $ keys , $ value ) { $ arrayKeys = is_array ( $ keys ) ? $ keys : explode ( '.' , $ keys ) ; $ array = array ( ) ; foreach ( array_reverse ( $ arrayKeys ) as $ i => $ key ) { $ array = array ( $ key => ( $ i == 0 ) ? $ value : $ array , ) ; } return $ array ; }
Fill array with specified keys
8,408
public function rebuild ( $ entityList = null ) { $ this -> populateConfigParameters ( ) ; $ result = $ this -> clearCache ( ) ; $ result &= $ this -> rebuildMetadata ( ) ; $ result &= $ this -> rebuildDatabase ( $ entityList ) ; $ this -> rebuildScheduledJobs ( ) ; return $ result ; }
Rebuild the system with metadata database and cache clearing
8,409
public function clearCache ( ) { $ result = $ this -> getContainer ( ) -> get ( 'fileManager' ) -> removeInDir ( $ this -> cachePath ) ; if ( $ result != true ) { throw new Exceptions \ Error ( "Error while clearing cache" ) ; } $ this -> updateCacheTimestamp ( ) ; return $ result ; }
Clear a cache
8,410
public function setDefaultPermissions ( $ path , $ recurse = false ) { if ( ! file_exists ( $ path ) ) { return false ; } $ permission = $ this -> getDefaultPermissions ( ) ; $ result = $ this -> chmod ( $ path , array ( $ permission [ 'file' ] , $ permission [ 'dir' ] ) , $ recurse ) ; if ( ! empty ( $ permission [ 'user' ] ) ) { $ result &= $ this -> chown ( $ path , $ permission [ 'user' ] , $ recurse ) ; } if ( ! empty ( $ permission [ 'group' ] ) ) { $ result &= $ this -> chgrp ( $ path , $ permission [ 'group' ] , $ recurse ) ; } return $ result ; }
Set default permission
8,411
public function getCurrentPermission ( $ filePath ) { if ( ! file_exists ( $ filePath ) ) { return false ; } $ fileInfo = stat ( $ filePath ) ; return substr ( base_convert ( $ fileInfo [ 'mode' ] , 10 , 8 ) , - 4 ) ; }
Get current permissions
8,412
public function chown ( $ path , $ user = '' , $ recurse = false ) { if ( ! file_exists ( $ path ) ) { return false ; } if ( empty ( $ user ) ) { $ user = $ this -> getDefaultOwner ( ) ; } if ( ! $ recurse ) { return $ this -> chownReal ( $ path , $ user ) ; } return $ this -> chownRecurse ( $ path , $ user ) ; }
Change owner permission
8,413
protected function chownRecurse ( $ path , $ user ) { if ( ! file_exists ( $ path ) ) { return false ; } if ( ! is_dir ( $ path ) ) { return $ this -> chownReal ( $ path , $ user ) ; } $ result = $ this -> chownReal ( $ path , $ user ) ; $ allFiles = $ this -> getFileManager ( ) -> getFileList ( $ path ) ; foreach ( $ allFiles as $ item ) { $ result &= $ this -> chownRecurse ( $ path . Utils \ Util :: getSeparator ( ) . $ item , $ user ) ; } return ( bool ) $ result ; }
Change owner permission recursive
8,414
public function chgrp ( $ path , $ group = null , $ recurse = false ) { if ( ! file_exists ( $ path ) ) { return false ; } if ( ! isset ( $ group ) ) { $ group = $ this -> getDefaultGroup ( ) ; } if ( ! $ recurse ) { return $ this -> chgrpReal ( $ path , $ group ) ; } return $ this -> chgrpRecurse ( $ path , $ group ) ; }
Change group permission
8,415
protected function chgrpRecurse ( $ path , $ group ) { if ( ! file_exists ( $ path ) ) { return false ; } if ( ! is_dir ( $ path ) ) { return $ this -> chgrpReal ( $ path , $ group ) ; } $ result = $ this -> chgrpReal ( $ path , $ group ) ; $ allFiles = $ this -> getFileManager ( ) -> getFileList ( $ path ) ; foreach ( $ allFiles as $ item ) { $ result &= $ this -> chgrpRecurse ( $ path . Utils \ Util :: getSeparator ( ) . $ item , $ group ) ; } return ( bool ) $ result ; }
Change group permission recursive
8,416
public function getDefaultOwner ( $ usePosix = false ) { $ defaultPermissions = $ this -> getDefaultPermissions ( ) ; $ owner = $ defaultPermissions [ 'user' ] ; if ( empty ( $ owner ) && $ usePosix ) { $ owner = function_exists ( 'posix_getuid' ) ? posix_getuid ( ) : null ; } if ( empty ( $ owner ) ) { return false ; } return $ owner ; }
Get default owner user
8,417
public function getDefaultGroup ( $ usePosix = false ) { $ defaultPermissions = $ this -> getDefaultPermissions ( ) ; $ group = $ defaultPermissions [ 'group' ] ; if ( empty ( $ group ) && $ usePosix ) { $ group = function_exists ( 'posix_getegid' ) ? posix_getegid ( ) : null ; } if ( empty ( $ group ) ) { return false ; } return $ group ; }
Get default group user
8,418
public function setMapPermission ( $ mode = null ) { $ this -> permissionError = array ( ) ; $ this -> permissionErrorRules = array ( ) ; $ params = $ this -> getParams ( ) ; $ permissionRules = $ this -> permissionRules ; if ( isset ( $ mode ) ) { foreach ( $ permissionRules as & $ value ) { $ value = $ mode ; } } $ result = true ; foreach ( $ params [ 'permissionMap' ] as $ type => $ items ) { $ permission = $ permissionRules [ $ type ] ; foreach ( $ items as $ item ) { if ( file_exists ( $ item ) ) { try { $ this -> chmod ( $ item , $ permission , true ) ; } catch ( \ Exception $ e ) { } $ res = is_readable ( $ item ) ; if ( $ type == 'writable' ) { $ res &= is_writable ( $ item ) ; if ( is_dir ( $ item ) ) { $ name = uniqid ( ) ; try { $ res &= $ this -> getFileManager ( ) -> putContents ( array ( $ item , $ name ) , 'test' ) ; $ res &= $ this -> getFileManager ( ) -> removeFile ( $ name , $ item ) ; } catch ( \ Exception $ e ) { $ res = false ; } } } if ( ! $ res ) { $ result = false ; $ this -> permissionError [ ] = $ item ; $ this -> permissionErrorRules [ $ item ] = $ permission ; } } } } return $ result ; }
Set permission regarding defined in permissionMap
8,419
protected function getSearchCount ( $ search , array $ array ) { $ search = $ this -> getPregQuote ( $ search ) ; $ number = 0 ; foreach ( $ array as $ value ) { if ( preg_match ( '/^' . $ search . '/' , $ value ) ) { $ number ++ ; } } return $ number ; }
Get count of a search string in a array
8,420
protected function normalizeDefs ( $ scope , $ fieldName , array $ fieldDefs ) { $ defs = new \ stdClass ( ) ; $ normalizedFieldDefs = $ this -> prepareFieldDefs ( $ scope , $ fieldName , $ fieldDefs ) ; if ( ! empty ( $ normalizedFieldDefs ) ) { $ defs -> fields = ( object ) array ( $ fieldName => ( object ) $ normalizedFieldDefs , ) ; } $ linkDefs = isset ( $ fieldDefs [ 'linkDefs' ] ) ? $ fieldDefs [ 'linkDefs' ] : null ; $ metaLinkDefs = $ this -> getMetadataHelper ( ) -> getLinkDefsInFieldMeta ( $ scope , $ fieldDefs ) ; if ( isset ( $ linkDefs ) || isset ( $ metaLinkDefs ) ) { $ metaLinkDefs = isset ( $ metaLinkDefs ) ? $ metaLinkDefs : array ( ) ; $ linkDefs = isset ( $ linkDefs ) ? $ linkDefs : array ( ) ; $ normalizedLinkdDefs = Util :: merge ( $ metaLinkDefs , $ linkDefs ) ; if ( ! empty ( $ normalizedLinkdDefs ) ) { $ defs -> links = ( object ) array ( $ fieldName => ( object ) $ normalizedLinkdDefs , ) ; } } return $ defs ; }
Add all needed block for a field defenition
8,421
protected function isCore ( $ scope , $ name ) { $ existingField = $ this -> getFieldDefs ( $ scope , $ name ) ; if ( isset ( $ existingField ) && ( ! isset ( $ existingField [ 'isCustom' ] ) || ! $ existingField [ 'isCustom' ] ) ) { return true ; } return false ; }
Check if a field is core field
8,422
public function getData ( $ paths , $ cacheFile = false ) { $ data = null ; if ( is_string ( $ paths ) ) { $ paths = array ( 'corePath' => $ paths , ) ; } if ( $ cacheFile && file_exists ( $ cacheFile ) && $ this -> getConfig ( ) -> get ( 'useCache' ) ) { $ data = $ this -> getFileManager ( ) -> getPhpContents ( $ cacheFile ) ; } else { $ data = $ this -> getClassNameHash ( $ paths [ 'corePath' ] ) ; if ( isset ( $ paths [ 'modulePath' ] ) ) { foreach ( $ this -> getMetadata ( ) -> getModuleList ( ) as $ moduleName ) { $ path = str_replace ( '{*}' , $ moduleName , $ paths [ 'modulePath' ] ) ; $ data = array_merge ( $ data , $ this -> getClassNameHash ( $ path ) ) ; } } if ( isset ( $ paths [ 'customPath' ] ) ) { $ data = array_merge ( $ data , $ this -> getClassNameHash ( $ paths [ 'customPath' ] ) ) ; } if ( $ cacheFile && $ this -> getConfig ( ) -> get ( 'useCache' ) ) { $ result = $ this -> getFileManager ( ) -> putPhpContents ( $ cacheFile , $ data ) ; if ( $ result == false ) { throw new \ Espo \ Core \ Exceptions \ Error ( ) ; } } } return $ data ; }
Return path data of classes
8,423
public function createNotification ( $ message , $ userId = '1' ) { $ notification = $ this -> getEntityManager ( ) -> getEntity ( 'Notification' ) ; $ notification -> set ( array ( 'type' => 'message' , 'data' => array ( 'userId' => $ userId , ) , 'userId' => $ userId , 'message' => $ message ) ) ; $ this -> getEntityManager ( ) -> saveEntity ( $ notification ) ; }
Create EspoCRM notification for a user
8,424
protected function getData ( ) { if ( empty ( $ this -> data ) || ! is_array ( $ this -> data ) ) { $ this -> init ( ) ; } return $ this -> data ; }
Get metadata array
8,425
public function getAll ( $ isJSON = false , $ reload = false ) { if ( $ reload ) { $ this -> init ( $ reload ) ; } if ( $ isJSON ) { return Json :: encode ( $ this -> data ) ; } return $ this -> data ; }
Get All Metadata context
8,426
public function getObjects ( $ key = null , $ default = null ) { $ objData = $ this -> getObjData ( ) ; return Util :: getValueByKey ( $ objData , $ key , $ default ) ; }
Get Object Metadata
8,427
public function getCustom ( $ key1 , $ key2 , $ default = null ) { $ filePath = array ( $ this -> paths [ 'customPath' ] , $ key1 , $ key2 . '.json' ) ; $ fileContent = $ this -> getFileManager ( ) -> getContents ( $ filePath ) ; if ( $ fileContent ) { return Json :: decode ( $ fileContent ) ; } return $ default ; }
Get metadata definition in custom directory
8,428
public function delete ( $ key1 , $ key2 , $ unsets = null ) { if ( ! is_array ( $ unsets ) ) { $ unsets = ( array ) $ unsets ; } switch ( $ key1 ) { case 'entityDefs' : $ fieldDefinitionList = $ this -> get ( 'fields' ) ; $ unsetList = $ unsets ; foreach ( $ unsetList as $ unsetItem ) { if ( preg_match ( '/fields\.([^\.]+)/' , $ unsetItem , $ matches ) && isset ( $ matches [ 1 ] ) ) { $ fieldName = $ matches [ 1 ] ; $ fieldPath = [ $ key1 , $ key2 , 'fields' , $ fieldName ] ; $ additionalFields = $ this -> getMetadataHelper ( ) -> getAdditionalFieldList ( $ fieldName , $ this -> get ( $ fieldPath , [ ] ) , $ fieldDefinitionList ) ; if ( is_array ( $ additionalFields ) ) { foreach ( $ additionalFields as $ additionalFieldName => $ additionalFieldParams ) { $ unsets [ ] = 'fields.' . $ additionalFieldName ; } } } } break ; } $ normalizedData = array ( '__APPEND__' , ) ; $ metadataUnsetData = array ( ) ; foreach ( $ unsets as $ unsetItem ) { $ normalizedData [ ] = $ unsetItem ; $ metadataUnsetData [ ] = implode ( '.' , array ( $ key1 , $ key2 , $ unsetItem ) ) ; } $ unsetData = array ( $ key1 => array ( $ key2 => $ normalizedData ) ) ; $ this -> deletedData = Util :: merge ( $ this -> deletedData , $ unsetData ) ; $ this -> deletedData = Util :: unsetInArrayByValue ( '__APPEND__' , $ this -> deletedData , true ) ; $ this -> data = Util :: unsetInArray ( $ this -> getData ( ) , $ metadataUnsetData , true ) ; }
Unset some fields and other stuff in metadat
8,429
protected function undelete ( $ key1 , $ key2 , $ data ) { if ( isset ( $ this -> deletedData [ $ key1 ] [ $ key2 ] ) ) { foreach ( $ this -> deletedData [ $ key1 ] [ $ key2 ] as $ unsetIndex => $ unsetItem ) { $ value = Util :: getValueByKey ( $ data , $ unsetItem ) ; if ( isset ( $ value ) ) { unset ( $ this -> deletedData [ $ key1 ] [ $ key2 ] [ $ unsetIndex ] ) ; } } } }
Undelete the deleted items
8,430
public function getEntityPath ( $ entityName , $ delim = '\\' ) { $ path = $ this -> getScopePath ( $ entityName , $ delim ) ; return implode ( $ delim , array ( $ path , 'Entities' , Util :: normilizeClassName ( ucfirst ( $ entityName ) ) ) ) ; }
Get Entity path ex . Espo . Entities . Account or Modules \ Crm \ Entities \ MyModule
8,431
public function removePendingJobDuplicates ( ) { $ pdo = $ this -> getEntityManager ( ) -> getPDO ( ) ; $ query = " SELECT scheduled_job_id FROM job WHERE scheduled_job_id IS NOT NULL AND `status` = '" . CronManager :: PENDING . "' AND execute_time <= '" . date ( 'Y-m-d H:i:s' ) . "' AND target_id IS NULL AND deleted = 0 GROUP BY scheduled_job_id HAVING count( * ) > 1 ORDER BY MAX(execute_time) ASC " ; $ sth = $ pdo -> prepare ( $ query ) ; $ sth -> execute ( ) ; $ duplicateJobList = $ sth -> fetchAll ( PDO :: FETCH_ASSOC ) ; foreach ( $ duplicateJobList as $ row ) { if ( ! empty ( $ row [ 'scheduled_job_id' ] ) ) { $ query = " SELECT id FROM `job` WHERE scheduled_job_id = " . $ pdo -> quote ( $ row [ 'scheduled_job_id' ] ) . " AND `status` = '" . CronManager :: PENDING . "' ORDER BY execute_time DESC LIMIT 1, 100000 " ; $ sth = $ pdo -> prepare ( $ query ) ; $ sth -> execute ( ) ; $ jobIdList = $ sth -> fetchAll ( PDO :: FETCH_COLUMN ) ; if ( empty ( $ jobIdList ) ) { continue ; } $ quotedJobIdList = [ ] ; foreach ( $ jobIdList as $ jobId ) { $ quotedJobIdList [ ] = $ pdo -> quote ( $ jobId ) ; } $ update = " UPDATE job SET deleted = 1 WHERE id IN (" . implode ( ", " , $ quotedJobIdList ) . ") " ; $ sth = $ pdo -> prepare ( $ update ) ; $ sth -> execute ( ) ; } } }
Remove pending duplicate jobs no need to run twice the same job
8,432
public function updateFailedJobAttempts ( ) { $ query = " SELECT * FROM job WHERE `status` = '" . CronManager :: FAILED . "' AND deleted = 0 AND execute_time <= '" . date ( 'Y-m-d H:i:s' ) . "' AND attempts > 0 " ; $ pdo = $ this -> getEntityManager ( ) -> getPDO ( ) ; $ sth = $ pdo -> prepare ( $ query ) ; $ sth -> execute ( ) ; $ rows = $ sth -> fetchAll ( PDO :: FETCH_ASSOC ) ; if ( $ rows ) { foreach ( $ rows as $ row ) { $ row [ 'failed_attempts' ] = isset ( $ row [ 'failed_attempts' ] ) ? $ row [ 'failed_attempts' ] : 0 ; $ attempts = $ row [ 'attempts' ] - 1 ; $ failedAttempts = $ row [ 'failed_attempts' ] + 1 ; $ update = " UPDATE job SET `status` = '" . CronManager :: PENDING . "', attempts = " . $ pdo -> quote ( $ attempts ) . ", failed_attempts = " . $ pdo -> quote ( $ failedAttempts ) . " WHERE id = " . $ pdo -> quote ( $ row [ 'id' ] ) . " " ; $ pdo -> prepare ( $ update ) -> execute ( ) ; } } }
Mark job attempts
8,433
protected function getEntityParams ( $ entityName = null , $ isOrmEntityDefs = false , $ returns = null ) { if ( ! isset ( $ entityName ) ) { $ entityName = $ this -> getEntityName ( ) ; } $ entityDefs = $ this -> getDefs ( $ isOrmEntityDefs ) ; if ( isset ( $ entityDefs [ $ entityName ] ) ) { return $ entityDefs [ $ entityName ] ; } return $ returns ; }
Get entity params by name
8,434
protected function getFieldParams ( $ fieldName = null , $ entityName = null , $ isOrmEntityDefs = false , $ returns = null ) { if ( ! isset ( $ fieldName ) ) { $ fieldName = $ this -> getFieldName ( ) ; } if ( ! isset ( $ entityName ) ) { $ entityName = $ this -> getEntityName ( ) ; } $ entityDefs = $ this -> getDefs ( $ isOrmEntityDefs ) ; if ( isset ( $ entityDefs [ $ entityName ] ) && isset ( $ entityDefs [ $ entityName ] [ 'fields' ] [ $ fieldName ] ) ) { return $ entityDefs [ $ entityName ] [ 'fields' ] [ $ fieldName ] ; } return $ returns ; }
Get field params by name for a specified entity
8,435
protected function getLinkParams ( $ linkName = null , $ entityName = null , $ isOrmEntityDefs = false , $ returns = null ) { if ( ! isset ( $ linkName ) ) { $ linkName = $ this -> getLinkName ( ) ; } if ( ! isset ( $ entityName ) ) { $ entityName = $ this -> getEntityName ( ) ; } $ entityDefs = $ this -> getDefs ( $ isOrmEntityDefs ) ; $ relationKeyName = $ isOrmEntityDefs ? 'relations' : 'links' ; if ( isset ( $ entityDefs [ $ entityName ] ) && isset ( $ entityDefs [ $ entityName ] [ $ relationKeyName ] [ $ linkName ] ) ) { return $ entityDefs [ $ entityName ] [ $ relationKeyName ] [ $ linkName ] ; } return $ returns ; }
Get relation params by name for a specified entity
8,436
protected function getForeignField ( $ name , $ entityName ) { $ foreignField = $ this -> getMetadata ( ) -> get ( 'entityDefs.' . $ entityName . '.fields.' . $ name ) ; if ( $ foreignField [ 'type' ] != 'varchar' ) { if ( $ foreignField [ 'type' ] == 'personName' ) { return array ( 'first' . ucfirst ( $ name ) , ' ' , 'last' . ucfirst ( $ name ) ) ; } } return $ name ; }
Get Foreign field
8,437
public function getPermissionCommands ( $ path , $ permissions = array ( '644' , '755' ) , $ isSudo = false , $ isFile = null , $ changeOwner = true ) { if ( is_string ( $ path ) ) { $ path = array_fill ( 0 , 2 , $ path ) ; } list ( $ chmodPath , $ chownPath ) = $ path ; $ commands = array ( ) ; $ commands [ ] = $ this -> getChmodCommand ( $ chmodPath , $ permissions , $ isSudo , $ isFile ) ; if ( $ changeOwner ) { $ chown = $ this -> getChownCommand ( $ chownPath , $ isSudo , false ) ; if ( isset ( $ chown ) ) { $ commands [ ] = $ chown ; } } return implode ( ' ' . $ this -> combineOperator . ' ' , $ commands ) . ';' ; }
Get permission commands
8,438
public function getFileList ( $ path , $ recursively = false , $ filter = '' , $ onlyFileType = null , $ isReturnSingleArray = false ) { $ path = $ this -> concatPaths ( $ path ) ; $ result = array ( ) ; if ( ! file_exists ( $ path ) || ! is_dir ( $ path ) ) { return $ result ; } $ cdir = scandir ( $ path ) ; foreach ( $ cdir as $ key => $ value ) { if ( ! in_array ( $ value , array ( "." , ".." ) ) ) { $ add = false ; if ( is_dir ( $ path . Utils \ Util :: getSeparator ( ) . $ value ) ) { if ( $ recursively || ( is_int ( $ recursively ) && $ recursively != 0 ) ) { $ nextRecursively = is_int ( $ recursively ) ? ( $ recursively - 1 ) : $ recursively ; $ result [ $ value ] = $ this -> getFileList ( $ path . Utils \ Util :: getSeparator ( ) . $ value , $ nextRecursively , $ filter , $ onlyFileType ) ; } else if ( ! isset ( $ onlyFileType ) || ! $ onlyFileType ) { $ add = true ; } } else if ( ! isset ( $ onlyFileType ) || $ onlyFileType ) { $ add = true ; } if ( $ add ) { if ( ! empty ( $ filter ) ) { if ( preg_match ( '/' . $ filter . '/i' , $ value ) ) { $ result [ ] = $ value ; } } else { $ result [ ] = $ value ; } } } } if ( $ isReturnSingleArray ) { return $ this -> getSingeFileList ( $ result , $ onlyFileType , $ path ) ; } return $ result ; }
Get a list of files in specified directory
8,439
protected function getSingeFileList ( array $ fileList , $ onlyFileType = null , $ basePath = null , $ parentDirName = '' ) { $ singleFileList = array ( ) ; foreach ( $ fileList as $ dirName => $ fileName ) { if ( is_array ( $ fileName ) ) { $ currentDir = Utils \ Util :: concatPath ( $ parentDirName , $ dirName ) ; if ( ! isset ( $ onlyFileType ) || $ onlyFileType == $ this -> isFile ( $ currentDir , $ basePath ) ) { $ singleFileList [ ] = $ currentDir ; } $ singleFileList = array_merge ( $ singleFileList , $ this -> getSingeFileList ( $ fileName , $ onlyFileType , $ basePath , $ currentDir ) ) ; } else { $ currentFileName = Utils \ Util :: concatPath ( $ parentDirName , $ fileName ) ; if ( ! isset ( $ onlyFileType ) || $ onlyFileType == $ this -> isFile ( $ currentFileName , $ basePath ) ) { $ singleFileList [ ] = $ currentFileName ; } } } return $ singleFileList ; }
Convert file list to a single array
8,440
public function getPhpContents ( $ path ) { $ fullPath = $ this -> concatPaths ( $ path ) ; if ( file_exists ( $ fullPath ) && strtolower ( substr ( $ fullPath , - 4 ) ) == '.php' ) { $ phpContents = include ( $ fullPath ) ; return $ phpContents ; } return false ; }
Get PHP array from PHP file
8,441
public function putContents ( $ path , $ data , $ flags = 0 ) { $ fullPath = $ this -> concatPaths ( $ path ) ; if ( $ this -> checkCreateFile ( $ fullPath ) === false ) { throw new Error ( 'Permission denied for ' . $ fullPath ) ; } $ res = ( file_put_contents ( $ fullPath , $ data , $ flags ) !== FALSE ) ; if ( $ res && function_exists ( 'opcache_invalidate' ) ) { @ opcache_invalidate ( $ fullPath ) ; } return $ res ; }
Write data to a file
8,442
public function putPhpContents ( $ path , $ data , $ withObjects = false ) { return $ this -> putContents ( $ path , $ this -> wrapForDataExport ( $ data , $ withObjects ) , LOCK_EX ) ; }
Save PHP content to file
8,443
public function putContentsJson ( $ path , $ data ) { if ( ! Utils \ Json :: isJSON ( $ data ) ) { $ data = Utils \ Json :: encode ( $ data , JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ) ; } return $ this -> putContents ( $ path , $ data , LOCK_EX ) ; }
Save JSON content to file
8,444
public function mergeContents ( $ path , $ content , $ isReturnJson = false , $ removeOptions = null , $ isPhp = false ) { if ( $ isPhp ) { $ fileContent = $ this -> getPhpContents ( $ path ) ; } else { $ fileContent = $ this -> getContents ( $ path ) ; } $ fullPath = $ this -> concatPaths ( $ path ) ; if ( file_exists ( $ fullPath ) && ( $ fileContent === false || empty ( $ fileContent ) ) ) { throw new Error ( 'FileManager: Failed to read file [' . $ fullPath . '].' ) ; } $ savedDataArray = Utils \ Json :: getArrayData ( $ fileContent ) ; $ newDataArray = Utils \ Json :: getArrayData ( $ content ) ; if ( isset ( $ removeOptions ) ) { $ savedDataArray = Utils \ Util :: unsetInArray ( $ savedDataArray , $ removeOptions ) ; $ newDataArray = Utils \ Util :: unsetInArray ( $ newDataArray , $ removeOptions ) ; } $ data = Utils \ Util :: merge ( $ savedDataArray , $ newDataArray ) ; if ( $ isReturnJson ) { $ data = Utils \ Json :: encode ( $ data , JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ) ; } if ( $ isPhp ) { return $ this -> putPhpContents ( $ path , $ data ) ; } return $ this -> putContents ( $ path , $ data ) ; }
Merge file content and save it to a file
8,445
public function mergePhpContents ( $ path , $ content , $ removeOptions = null ) { return $ this -> mergeContents ( $ path , $ content , false , $ removeOptions , true ) ; }
Merge PHP content and save it to a file
8,446
public function unsetContents ( $ path , $ unsets , $ isJSON = true ) { $ currentData = $ this -> getContents ( $ path ) ; if ( ! isset ( $ currentData ) || ! $ currentData ) { return true ; } $ currentDataArray = Utils \ Json :: getArrayData ( $ currentData ) ; $ unsettedData = Utils \ Util :: unsetInArray ( $ currentDataArray , $ unsets , true ) ; if ( is_null ( $ unsettedData ) || ( is_array ( $ unsettedData ) && empty ( $ unsettedData ) ) ) { $ fullPath = $ this -> concatPaths ( $ path ) ; if ( ! file_exists ( $ fullPath ) ) { return true ; } return $ this -> unlink ( $ fullPath ) ; } if ( $ isJSON ) { return $ this -> putContentsJson ( $ path , $ unsettedData ) ; } return $ this -> putContents ( $ path , $ unsettedData ) ; }
Unset some element of content data
8,447
public function mkdir ( $ path , $ permission = null , $ recursive = false ) { $ fullPath = $ this -> concatPaths ( $ path ) ; if ( file_exists ( $ fullPath ) && is_dir ( $ path ) ) { return true ; } $ defaultPermissions = $ this -> getPermissionUtils ( ) -> getDefaultPermissions ( ) ; if ( ! isset ( $ permission ) ) { $ permission = ( string ) $ defaultPermissions [ 'dir' ] ; $ permission = base_convert ( $ permission , 8 , 10 ) ; } try { $ result = mkdir ( $ fullPath , $ permission , true ) ; if ( ! empty ( $ defaultPermissions [ 'user' ] ) ) { $ this -> getPermissionUtils ( ) -> chown ( $ fullPath ) ; } if ( ! empty ( $ defaultPermissions [ 'group' ] ) ) { $ this -> getPermissionUtils ( ) -> chgrp ( $ fullPath ) ; } } catch ( \ Exception $ e ) { $ GLOBALS [ 'log' ] -> critical ( 'Permission denied: unable to create the folder on the server - ' . $ fullPath ) ; } return isset ( $ result ) ? $ result : false ; }
Create a new dir
8,448
public function checkCreateFile ( $ filePath ) { $ defaultPermissions = $ this -> getPermissionUtils ( ) -> getDefaultPermissions ( ) ; if ( file_exists ( $ filePath ) ) { if ( ! is_writable ( $ filePath ) && ! in_array ( $ this -> getPermissionUtils ( ) -> getCurrentPermission ( $ filePath ) , array ( $ defaultPermissions [ 'file' ] , $ defaultPermissions [ 'dir' ] ) ) ) { return $ this -> getPermissionUtils ( ) -> setDefaultPermissions ( $ filePath , true ) ; } return true ; } $ pathParts = pathinfo ( $ filePath ) ; if ( ! file_exists ( $ pathParts [ 'dirname' ] ) ) { $ dirPermission = $ defaultPermissions [ 'dir' ] ; $ dirPermission = is_string ( $ dirPermission ) ? base_convert ( $ dirPermission , 8 , 10 ) : $ dirPermission ; if ( ! $ this -> mkdir ( $ pathParts [ 'dirname' ] , $ dirPermission , true ) ) { throw new Error ( 'Permission denied: unable to create a folder on the server - ' . $ pathParts [ 'dirname' ] ) ; } } if ( touch ( $ filePath ) ) { return $ this -> getPermissionUtils ( ) -> setDefaultPermissions ( $ filePath , true ) ; } return false ; }
Create a new file if not exists with all folders in the path .
8,449
public function removeInDir ( $ dirPath , $ removeWithDir = false ) { $ fileList = $ this -> getFileList ( $ dirPath , false ) ; $ result = true ; if ( is_array ( $ fileList ) ) { foreach ( $ fileList as $ file ) { $ fullPath = Utils \ Util :: concatPath ( $ dirPath , $ file ) ; if ( is_dir ( $ fullPath ) ) { $ result &= $ this -> removeInDir ( $ fullPath , true ) ; } else if ( file_exists ( $ fullPath ) ) { $ result &= unlink ( $ fullPath ) ; } } } if ( $ removeWithDir && $ this -> isDirEmpty ( $ dirPath ) ) { $ result &= $ this -> rmdir ( $ dirPath ) ; } return ( bool ) $ result ; }
Remove all files inside given path
8,450
protected function removeEmptyDirs ( $ path ) { $ parentDirName = $ this -> getParentDirName ( $ path ) ; $ res = true ; if ( $ this -> isDirEmpty ( $ parentDirName ) ) { $ res &= $ this -> rmdir ( $ parentDirName ) ; $ res &= $ this -> removeEmptyDirs ( $ parentDirName ) ; } return ( bool ) $ res ; }
Remove empty parent directories if they are empty
8,451
public function isDirEmpty ( $ path ) { if ( is_dir ( $ path ) ) { $ fileList = $ this -> getFileList ( $ path , true ) ; if ( is_array ( $ fileList ) && empty ( $ fileList ) ) { return true ; } } return false ; }
Check if directory is empty
8,452
public function getFileName ( $ fileName , $ ext = '' ) { if ( empty ( $ ext ) ) { $ fileName = substr ( $ fileName , 0 , strrpos ( $ fileName , '.' , - 1 ) ) ; } else { if ( substr ( $ ext , 0 , 1 ) != '.' ) { $ ext = '.' . $ ext ; } if ( substr ( $ fileName , - ( strlen ( $ ext ) ) ) == $ ext ) { $ fileName = substr ( $ fileName , 0 , - ( strlen ( $ ext ) ) ) ; } } $ exFileName = explode ( '/' , Utils \ Util :: toFormat ( $ fileName , '/' ) ) ; return end ( $ exFileName ) ; }
Get a filename without the file extension
8,453
public function getDirName ( $ path , $ isFullPath = true , $ useIsDir = true ) { $ dirName = preg_replace ( '/\/$/i' , '' , $ path ) ; $ dirName = ( $ useIsDir && is_dir ( $ dirName ) ) ? $ dirName : pathinfo ( $ dirName , PATHINFO_DIRNAME ) ; if ( ! $ isFullPath ) { $ pieces = explode ( '/' , $ dirName ) ; $ dirName = $ pieces [ count ( $ pieces ) - 1 ] ; } return $ dirName ; }
Get a directory name from the path
8,454
public function wrapForDataExport ( $ content , $ withObjects = false ) { if ( ! isset ( $ content ) ) { return false ; } if ( ! $ withObjects ) { return "<?php\n" . "return " . var_export ( $ content , true ) . ";\n" . "?>" ; } else { return "<?php\n" . "return " . $ this -> varExport ( $ content ) . ";\n" . "?>" ; } }
Return content of PHP file
8,455
public static function getIdFor ( $ object , $ type ) { if ( is_null ( $ object ) ) { return null ; } elseif ( is_object ( $ object ) ) { return $ object -> getKey ( ) ; } elseif ( is_array ( $ object ) ) { return $ object [ 'id' ] ; } elseif ( is_numeric ( $ object ) ) { return $ object ; } elseif ( is_string ( $ object ) ) { return call_user_func_array ( [ Config :: get ( "laratrust.models.{$type}" ) , 'where' ] , [ 'name' , $ object ] ) -> firstOrFail ( ) -> getKey ( ) ; } throw new InvalidArgumentException ( 'getIdFor function only accepts an integer, a Model object or an array with an "id" key' ) ; }
Gets the it from an array object or integer .
8,456
public static function fetchTeam ( $ team = null ) { if ( is_null ( $ team ) || ! Config :: get ( 'laratrust.use_teams' ) ) { return null ; } return static :: getIdFor ( $ team , 'team' ) ; }
Fetch the team model from the name .
8,457
public static function assignRealValuesTo ( $ team , $ requireAllOrOptions , $ method ) { return [ ( $ method ( $ team ) ? null : $ team ) , ( $ method ( $ team ) ? $ team : $ requireAllOrOptions ) , ] ; }
Assing the real values to the team and requireAllOrOptions parameters .
8,458
public static function standardize ( $ value , $ toArray = false ) { if ( is_array ( $ value ) || ( ( strpos ( $ value , '|' ) === false ) && ! $ toArray ) ) { return $ value ; } return explode ( '|' , $ value ) ; }
Checks if the string passed contains a pipe | and explodes the string to an array .
8,459
public static function isInSameTeam ( $ rolePermission , $ team ) { if ( ! Config :: get ( 'laratrust.use_teams' ) || ( ! Config :: get ( 'laratrust.teams_strict_check' ) && is_null ( $ team ) ) ) { return true ; } $ teamForeignKey = static :: teamForeignKey ( ) ; return $ rolePermission [ 'pivot' ] [ $ teamForeignKey ] == $ team ; }
Check if a role or permission is attach to the user in a same team .
8,460
public static function checkOrSet ( $ option , $ array , $ possibleValues ) { if ( ! isset ( $ array [ $ option ] ) ) { $ array [ $ option ] = $ possibleValues [ 0 ] ; return $ array ; } $ ignoredOptions = [ 'team' , 'foreignKeyName' ] ; if ( ! in_array ( $ option , $ ignoredOptions ) && ! in_array ( $ array [ $ option ] , $ possibleValues , true ) ) { throw new InvalidArgumentException ( ) ; } return $ array ; }
Checks if the option exists inside the array otherwise it sets the first option inside the default values array .
8,461
public static function hidrateModel ( $ class , $ data ) { if ( $ data instanceof Model ) { return $ data ; } if ( ! isset ( $ data [ 'pivot' ] ) ) { throw new \ Exception ( "The 'pivot' attribute in the {$class} is hidden" ) ; } $ model = new $ class ; $ primaryKey = $ model -> getKeyName ( ) ; $ model -> setAttribute ( $ primaryKey , $ data [ $ primaryKey ] ) -> setAttribute ( 'name' , $ data [ 'name' ] ) ; $ model -> setRelation ( 'pivot' , MorphPivot :: fromRawAttributes ( $ model , $ data [ 'pivot' ] , 'pivot_table' ) ) ; return $ model ; }
Creates a model from an array filled with the class data .
8,462
public static function getPermissionWithAndWithoutWildcards ( $ permissions ) { $ wildcard = [ ] ; $ noWildcard = [ ] ; foreach ( $ permissions as $ permission ) { if ( strpos ( $ permission , '*' ) === false ) { $ noWildcard [ ] = $ permission ; } else { $ wildcard [ ] = str_replace ( '*' , '%' , $ permission ) ; } } return [ $ wildcard , $ noWildcard ] ; }
Return two arrays with the filtered permissions between the permissions with wildcard and the permissions without it .
8,463
public static function bootLaratrustRoleTrait ( ) { $ flushCache = function ( $ role ) { $ role -> flushCache ( ) ; } ; if ( method_exists ( static :: class , 'restored' ) ) { static :: restored ( $ flushCache ) ; } static :: deleted ( $ flushCache ) ; static :: saved ( $ flushCache ) ; static :: deleting ( function ( $ role ) { if ( method_exists ( $ role , 'bootSoftDeletes' ) && ! $ role -> forceDeleting ) { return ; } $ role -> permissions ( ) -> sync ( [ ] ) ; foreach ( array_keys ( Config :: get ( 'laratrust.user_models' ) ) as $ key ) { $ role -> $ key ( ) -> sync ( [ ] ) ; } } ) ; }
Boots the role model and attaches event listener to remove the many - to - many records when trying to delete . Will NOT delete any records if the role model uses soft deletes .
8,464
public function permissions ( ) { return $ this -> belongsToMany ( Config :: get ( 'laratrust.models.permission' ) , Config :: get ( 'laratrust.tables.permission_role' ) , Config :: get ( 'laratrust.foreign_keys.role' ) , Config :: get ( 'laratrust.foreign_keys.permission' ) ) ; }
Many - to - Many relations with the permission model .
8,465
public function detachPermissions ( $ permissions = null ) { if ( ! $ permissions ) { $ permissions = $ this -> permissions ( ) -> get ( ) ; } foreach ( $ permissions as $ permission ) { $ this -> detachPermission ( $ permission ) ; } return $ this ; }
Detach multiple permissions from current role
8,466
public static function bootLaratrustTeamTrait ( ) { static :: deleting ( function ( $ team ) { if ( method_exists ( $ team , 'bootSoftDeletes' ) && ! $ team -> forceDeleting ) { return ; } foreach ( array_keys ( Config :: get ( 'laratrust.user_models' ) ) as $ key ) { $ team -> $ key ( ) -> sync ( [ ] ) ; } } ) ; }
Boots the team model and attaches event listener to remove the many - to - many records when trying to delete . Will NOT delete any records if the team model uses soft deletes .
8,467
public function hasRole ( $ role , $ team = null , $ requireAll = false ) { if ( $ user = $ this -> user ( ) ) { return $ user -> hasRole ( $ role , $ team , $ requireAll ) ; } return false ; }
Checks if the current user has a role by its name .
8,468
public function ability ( $ roles , $ permissions , $ team = null , $ options = [ ] ) { if ( $ user = $ this -> user ( ) ) { return $ user -> ability ( $ roles , $ permissions , $ team , $ options ) ; } return false ; }
Check if the current user has a role or permission by its name .
8,469
public function scopeWherePermissionIs ( $ query , $ permission = '' , $ boolean = 'and' ) { $ method = $ boolean == 'and' ? 'where' : 'orWhere' ; return $ query -> $ method ( function ( $ query ) use ( $ permission ) { $ query -> whereHas ( 'roles.permissions' , function ( $ permissionQuery ) use ( $ permission ) { $ permissionQuery -> where ( 'name' , $ permission ) ; } ) -> orWhereHas ( 'permissions' , function ( $ permissionQuery ) use ( $ permission ) { $ permissionQuery -> where ( 'name' , $ permission ) ; } ) ; } ) ; }
This scope allows to retrieve the users with a specific permission .
8,470
public static function laratrustObserve ( $ class ) { $ className = is_string ( $ class ) ? $ class : get_class ( $ class ) ; foreach ( self :: $ laratrustObservables as $ event ) { if ( method_exists ( $ class , $ event ) ) { static :: registerLaratrustEvent ( Str :: snake ( $ event , '.' ) , $ className . '@' . $ event ) ; } } }
Register an observer to the Laratrust events .
8,471
protected function registerMiddlewares ( ) { if ( ! $ this -> app [ 'config' ] -> get ( 'laratrust.middleware.register' ) ) { return ; } $ router = $ this -> app [ 'router' ] ; if ( method_exists ( $ router , 'middleware' ) ) { $ registerMethod = 'middleware' ; } elseif ( method_exists ( $ router , 'aliasMiddleware' ) ) { $ registerMethod = 'aliasMiddleware' ; } else { return ; } foreach ( $ this -> middlewares as $ key => $ class ) { $ router -> $ registerMethod ( $ key , $ class ) ; } }
Register the middlewares automatically .
8,472
protected function userCachedRoles ( ) { $ cacheKey = 'laratrust_roles_for_user_' . $ this -> user -> getKey ( ) ; if ( ! Config :: get ( 'laratrust.cache.enabled' ) ) { return $ this -> user -> roles ( ) -> get ( ) ; } return Cache :: remember ( $ cacheKey , Config :: get ( 'laratrust.cache.expiration_time' , 60 ) , function ( ) { return $ this -> user -> roles ( ) -> get ( ) -> toArray ( ) ; } ) ; }
Tries to return all the cached roles of the user . If it can t bring the roles from the cache it brings them back from the DB .
8,473
public function userCachedPermissions ( ) { $ cacheKey = 'laratrust_permissions_for_user_' . $ this -> user -> getKey ( ) ; if ( ! Config :: get ( 'laratrust.cache.enabled' ) ) { return $ this -> user -> permissions ( ) -> get ( ) ; } return Cache :: remember ( $ cacheKey , Config :: get ( 'laratrust.cache.expiration_time' , 60 ) , function ( ) { return $ this -> user -> permissions ( ) -> get ( ) -> toArray ( ) ; } ) ; }
Tries to return all the cached permissions of the user and if it can t bring the permissions from the cache it brings them back from the DB .
8,474
public static function bootLaratrustPermissionTrait ( ) { static :: deleting ( function ( $ permission ) { if ( ! method_exists ( Config :: get ( 'laratrust.models.permission' ) , 'bootSoftDeletes' ) ) { $ permission -> roles ( ) -> sync ( [ ] ) ; } } ) ; static :: deleting ( function ( $ permission ) { if ( method_exists ( $ permission , 'bootSoftDeletes' ) && ! $ permission -> forceDeleting ) { return ; } $ permission -> roles ( ) -> sync ( [ ] ) ; foreach ( array_keys ( Config :: get ( 'laratrust.user_models' ) ) as $ key ) { $ permission -> $ key ( ) -> sync ( [ ] ) ; } } ) ; }
Boots the permission model and attaches event listener to remove the many - to - many records when trying to delete . Will NOT delete any records if the permission model uses soft deletes .
8,475
public function roles ( ) { return $ this -> belongsToMany ( Config :: get ( 'laratrust.models.role' ) , Config :: get ( 'laratrust.tables.permission_role' ) , Config :: get ( 'laratrust.foreign_keys.permission' ) , Config :: get ( 'laratrust.foreign_keys.role' ) ) ; }
Many - to - Many relations with role model .
8,476
public function getMorphByUserRelation ( $ relationship ) { return $ this -> morphedByMany ( Config :: get ( 'laratrust.user_models' ) [ $ relationship ] , 'user' , Config :: get ( 'laratrust.tables.permission_user' ) , Config :: get ( 'laratrust.foreign_keys.permission' ) , Config :: get ( 'laratrust.foreign_keys.user' ) ) ; }
Morph by Many relationship between the permission and the one of the possible user models .
8,477
public function currentRoleCachedPermissions ( ) { $ cacheKey = 'laratrust_permissions_for_role_' . $ this -> role -> getKey ( ) ; if ( ! Config :: get ( 'laratrust.cache.enabled' ) ) { return $ this -> role -> permissions ( ) -> get ( ) ; } return Cache :: remember ( $ cacheKey , Config :: get ( 'laratrust.cache.expiration_time' , 60 ) , function ( ) { return $ this -> role -> permissions ( ) -> get ( ) -> toArray ( ) ; } ) ; }
Tries to return all the cached permissions of the role . If it can t bring the permissions from the cache it brings them back from the DB .
8,478
public function handle ( $ laravelVersion = '5.3.0' ) { if ( version_compare ( strtolower ( $ laravelVersion ) , '5.3.0-dev' , '>=' ) ) { $ this -> registerWithParenthesis ( ) ; } else { $ this -> registerWithoutParenthesis ( ) ; } $ this -> registerClosingDirectives ( ) ; }
Handles the registration of the blades directives .
8,479
protected function registerWithParenthesis ( ) { Blade :: directive ( 'role' , function ( $ expression ) { return "<?php if (app('laratrust')->hasRole({$expression})) : ?>" ; } ) ; Blade :: directive ( 'permission' , function ( $ expression ) { return "<?php if (app('laratrust')->can({$expression})) : ?>" ; } ) ; Blade :: directive ( 'ability' , function ( $ expression ) { return "<?php if (app('laratrust')->ability({$expression})) : ?>" ; } ) ; Blade :: directive ( 'canAndOwns' , function ( $ expression ) { return "<?php if (app('laratrust')->canAndOwns({$expression})) : ?>" ; } ) ; Blade :: directive ( 'hasRoleAndOwns' , function ( $ expression ) { return "<?php if (app('laratrust')->hasRoleAndOwns({$expression})) : ?>" ; } ) ; }
Registers the directives with parenthesis .
8,480
protected function registerWithoutParenthesis ( ) { Blade :: directive ( 'role' , function ( $ expression ) { return "<?php if (app('laratrust')->hasRole{$expression}) : ?>" ; } ) ; Blade :: directive ( 'permission' , function ( $ expression ) { return "<?php if (app('laratrust')->can{$expression}) : ?>" ; } ) ; Blade :: directive ( 'ability' , function ( $ expression ) { return "<?php if (app('laratrust')->ability{$expression}) : ?>" ; } ) ; Blade :: directive ( 'canAndOwns' , function ( $ expression ) { return "<?php if (app('laratrust')->canAndOwns{$expression}) : ?>" ; } ) ; Blade :: directive ( 'hasRoleAndOwns' , function ( $ expression ) { return "<?php if (app('laratrust')->hasRoleAndOwns{$expression}) : ?>" ; } ) ; }
Registers the directives without parenthesis .
8,481
protected function authorization ( $ type , $ rolesPermissions , $ team , $ options ) { list ( $ team , $ requireAll , $ guard ) = $ this -> assignRealValuesTo ( $ team , $ options ) ; $ method = $ type == 'roles' ? 'hasRole' : 'hasPermission' ; if ( ! is_array ( $ rolesPermissions ) ) { $ rolesPermissions = explode ( self :: DELIMITER , $ rolesPermissions ) ; } return ! Auth :: guard ( $ guard ) -> guest ( ) && Auth :: guard ( $ guard ) -> user ( ) -> $ method ( $ rolesPermissions , $ team , $ requireAll ) ; }
Check if the request has authorization to continue .
8,482
protected function assignRealValuesTo ( $ team , $ options ) { return [ ( Str :: contains ( $ team , [ 'require_all' , 'guard:' ] ) ? null : $ team ) , ( Str :: contains ( $ team , 'require_all' ) ? : Str :: contains ( $ options , 'require_all' ) ) , ( Str :: contains ( $ team , 'guard:' ) ? $ this -> extractGuard ( $ team ) : ( Str :: contains ( $ options , 'guard:' ) ? $ this -> extractGuard ( $ options ) : Config :: get ( 'auth.defaults.guard' ) ) ) , ] ; }
Generate an array with the real values of the parameters given to the middleware .
8,483
protected function extractGuard ( $ string ) { $ options = Collection :: make ( explode ( '|' , $ string ) ) ; return $ options -> reject ( function ( $ option ) { return strpos ( $ option , 'guard:' ) === false ; } ) -> map ( function ( $ option ) { return explode ( ':' , $ option ) [ 1 ] ; } ) -> first ( ) ; }
Extract the guard type from the given string .
8,484
protected function getExistingMigrationsWarning ( array $ existingMigrations ) { if ( count ( $ existingMigrations ) > 1 ) { $ base = "Laratrust upgrade migrations already exist.\nFollowing files were found: " ; } else { $ base = "Laratrust upgrade migration already exists.\nFollowing file was found: " ; } return $ base . array_reduce ( $ existingMigrations , function ( $ carry , $ fileName ) { return $ carry . "\n - " . $ fileName ; } ) ; }
Build a warning regarding possible duplication due to already existing migrations .
8,485
protected function alreadyExistingMigrations ( ) { $ matchingFiles = glob ( $ this -> getMigrationPath ( '*' ) ) ; return array_map ( function ( $ path ) { return basename ( $ path ) ; } , $ matchingFiles ) ; }
Check if there is another migration with the same suffix .
8,486
protected function generateMigrationMessage ( ) { $ tables = Collection :: make ( Config :: get ( 'laratrust.tables' ) ) -> reject ( function ( $ value , $ key ) { return $ key == 'teams' && ! Config :: get ( 'laratrust.use_teams' ) ; } ) -> sort ( ) ; return "A migration that creates {$tables->implode(', ')} " . "tables will be created in database/migrations directory" ; }
Generate the message to display when running the console command showing what tables are going to be created .
8,487
protected function createSeeder ( ) { $ permission = Config :: get ( 'laratrust.models.permission' , 'App\Permission' ) ; $ role = Config :: get ( 'laratrust.models.role' , 'App\Role' ) ; $ rolePermissions = Config :: get ( 'laratrust.tables.permission_role' ) ; $ roleUsers = Config :: get ( 'laratrust.tables.role_user' ) ; $ user = new Collection ( Config :: get ( 'laratrust.user_models' , [ 'App\User' ] ) ) ; $ user = $ user -> first ( ) ; $ output = $ this -> laravel -> view -> make ( 'laratrust::seeder' ) -> with ( compact ( [ 'role' , 'permission' , 'user' , 'rolePermissions' , 'roleUsers' , ] ) ) -> render ( ) ; if ( $ fs = fopen ( $ this -> seederPath ( ) , 'x' ) ) { fwrite ( $ fs , $ output ) ; fclose ( $ fs ) ; return true ; } return false ; }
Create the seeder
8,488
public static function bootLaratrustUserTrait ( ) { $ flushCache = function ( $ user ) { $ user -> flushCache ( ) ; } ; if ( method_exists ( static :: class , 'restored' ) ) { static :: restored ( $ flushCache ) ; } static :: deleted ( $ flushCache ) ; static :: saved ( $ flushCache ) ; static :: deleting ( function ( $ user ) { if ( method_exists ( $ user , 'bootSoftDeletes' ) && ! $ user -> forceDeleting ) { return ; } $ user -> roles ( ) -> sync ( [ ] ) ; $ user -> permissions ( ) -> sync ( [ ] ) ; } ) ; }
Boots the user model and attaches event listener to remove the many - to - many records when trying to delete . Will NOT delete any records if the user model uses soft deletes .
8,489
public function rolesTeams ( ) { if ( ! Config :: get ( 'laratrust.use_teams' ) ) { return null ; } return $ this -> morphToMany ( Config :: get ( 'laratrust.models.team' ) , 'user' , Config :: get ( 'laratrust.tables.role_user' ) , Config :: get ( 'laratrust.foreign_keys.user' ) , Config :: get ( 'laratrust.foreign_keys.team' ) ) -> withPivot ( Config :: get ( 'laratrust.foreign_keys.role' ) ) ; }
Many - to - Many relations with Team associated through the roles .
8,490
public function permissions ( ) { $ permissions = $ this -> morphToMany ( Config :: get ( 'laratrust.models.permission' ) , 'user' , Config :: get ( 'laratrust.tables.permission_user' ) , Config :: get ( 'laratrust.foreign_keys.user' ) , Config :: get ( 'laratrust.foreign_keys.permission' ) ) ; if ( Config :: get ( 'laratrust.use_teams' ) ) { $ permissions -> withPivot ( Config :: get ( 'laratrust.foreign_keys.team' ) ) ; } return $ permissions ; }
Many - to - Many relations with Permission .
8,491
public function attachRoles ( $ roles = [ ] , $ team = null ) { foreach ( $ roles as $ role ) { $ this -> attachRole ( $ role , $ team ) ; } return $ this ; }
Attach multiple roles to a user .
8,492
public function syncRoles ( $ roles = [ ] , $ team = null , $ detaching = true ) { return $ this -> syncModels ( 'roles' , $ roles , $ team , $ detaching ) ; }
Sync roles to the user .
8,493
public function attachPermissions ( $ permissions = [ ] , $ team = null ) { foreach ( $ permissions as $ permission ) { $ this -> attachPermission ( $ permission , $ team ) ; } return $ this ; }
Attach multiple permissions to a user .
8,494
public function syncPermissions ( $ permissions = [ ] , $ team = null , $ detaching = true ) { return $ this -> syncModels ( 'permissions' , $ permissions , $ team , $ detaching ) ; }
Sync permissions to the user .
8,495
public function allPermissions ( ) { $ roles = $ this -> roles ( ) -> with ( 'permissions' ) -> get ( ) ; $ roles = $ roles -> flatMap ( function ( $ role ) { return $ role -> permissions ; } ) ; return $ this -> permissions ( ) -> get ( ) -> merge ( $ roles ) -> unique ( 'name' ) ; }
Return all the user permissions .
8,496
private static function buildAndDisplayAdUnitTree ( AdUnit $ root , array $ adUnits ) { if ( is_null ( $ root ) ) { print "No root unit found.\n" ; return ; } $ treeMap = [ ] ; foreach ( $ adUnits as $ adUnit ) { $ parentId = $ adUnit -> getParentId ( ) ; if ( ! is_null ( $ parentId ) ) { if ( ! array_key_exists ( $ parentId , $ treeMap ) ) { $ treeMap [ $ parentId ] = [ ] ; } $ treeMap [ $ parentId ] [ ] = $ adUnit ; } } self :: displayInventoryTree ( $ root , $ treeMap ) ; }
Builds and displays an ad unit tree from ad units underneath the root ad unit .
8,497
private static function displayInventoryTreeHelper ( AdUnit $ root , array $ treeMap , $ depth ) { $ rootId = $ root -> getId ( ) ; printf ( "%s%s(%s)%s" , self :: generateTab ( $ depth ) , $ root -> getName ( ) , $ rootId , PHP_EOL ) ; if ( ! array_key_exists ( $ rootId , $ treeMap ) || empty ( $ treeMap [ $ rootId ] ) ) { return ; } foreach ( $ treeMap [ $ rootId ] as $ child ) { self :: displayInventoryTreeHelper ( $ child , $ treeMap , $ depth + 1 ) ; } }
Helper for displaying inventory units .
8,498
private static function generateTab ( $ depth ) { $ builder = '' ; if ( $ depth > 0 ) { $ builder .= ' ' ; } for ( $ i = 1 ; $ i < $ depth ; $ i ++ ) { $ builder .= '| ' ; } $ builder .= '+--' ; return $ builder ; }
Generates tabs to represent branching to children .
8,499
private static function uploadImage ( MediaService $ mediaService , $ url ) { $ image = new Image ( ) ; $ image -> setData ( file_get_contents ( $ url ) ) ; $ image -> setType ( MediaMediaType :: IMAGE ) ; return $ mediaService -> upload ( [ $ image ] ) [ 0 ] ; }
Uploads an image to the server .