idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
4,300
protected function createObject ( $ data , $ options = [ ] ) { $ object = null ; if ( $ data != null ) { $ id = isset ( $ data [ '_id' ] ) ? serialize ( $ data [ '_id' ] ) . $ this -> getCollection ( ) : null ; $ model = $ this -> getModelName ( ) ; $ softHydrate = false ; if ( null !== $ this -> documentManager -> getObject ( $ id ) ) { $ softHydrate = true ; $ object = $ this -> documentManager -> getObject ( $ id ) ; } else { $ object = new $ this -> modelName ( ) ; } $ this -> hydrator -> hydrate ( $ object , $ data , $ softHydrate ) ; $ this -> classMetadata -> getEventManager ( ) -> execute ( EventManager :: EVENT_POST_LOAD , $ object ) ; if ( ! isset ( $ options [ 'readOnly' ] ) || $ options [ 'readOnly' ] != true ) { $ oid = spl_object_hash ( $ object ) ; $ data = $ this -> hydrator -> unhydrate ( $ object ) ; $ id = isset ( $ data [ '_id' ] ) ? serialize ( $ data [ '_id' ] ) . $ this -> getCollection ( ) : $ oid ; $ projection = isset ( $ options [ 'projection' ] ) ? $ options [ 'projection' ] : [ ] ; $ this -> lastProjectionCache -> save ( $ id , $ projection ) ; $ this -> cacheObject ( $ object ) ; $ this -> documentManager -> addObject ( $ object , DocumentManager :: OBJ_MANAGED , $ this ) ; } return $ object ; } return $ object ; }
Create object based on provided data
4,301
protected function createOption ( $ projections , $ sort , $ otherOptions = [ ] ) { $ options = [ ] ; isset ( $ projections ) ? $ options [ "projection" ] = $ this -> castQuery ( $ projections ) : null ; isset ( $ sort ) ? $ options [ "sort" ] = $ this -> castQuery ( $ sort ) : null ; $ options = array_merge ( $ this -> documentManager -> getDefaultOptions ( ) , $ otherOptions , $ options ) ; return $ options ; }
Create options based on parameters
4,302
public static function WriteJsConnect ( $ User , $ Request , $ Secure = TRUE ) { $ User = array_change_key_case ( $ User ) ; $ ClientID = Config :: get ( "vanillasso.client_id" ) ; $ Secret = Config :: get ( "vanillasso.secret" ) ; if ( $ Secure ) { if ( ! isset ( $ Request [ 'client_id' ] ) ) $ Error = array ( 'error' => 'invalid_request' , 'message' => 'The client_id parameter is missing.' ) ; elseif ( $ Request [ 'client_id' ] != $ ClientID ) $ Error = array ( 'error' => 'invalid_client' , 'message' => "Unknown client {$Request['client_id']}." ) ; elseif ( ! isset ( $ Request [ 'timestamp' ] ) && ! isset ( $ Request [ 'signature' ] ) ) { if ( is_array ( $ User ) && count ( $ User ) > 0 ) { $ Error = array ( 'name' => $ User [ 'name' ] , 'photourl' => @ $ User [ 'photourl' ] ) ; } else { $ Error = array ( 'name' => '' , 'photourl' => '' ) ; } } elseif ( ! isset ( $ Request [ 'timestamp' ] ) || ! is_numeric ( $ Request [ 'timestamp' ] ) ) $ Error = array ( 'error' => 'invalid_request' , 'message' => 'The timestamp parameter is missing or invalid.' ) ; elseif ( ! isset ( $ Request [ 'signature' ] ) ) $ Error = array ( 'error' => 'invalid_request' , 'message' => 'Missing signature parameter.' ) ; elseif ( ( $ Diff = abs ( $ Request [ 'timestamp' ] - self :: JsTimestamp ( ) ) ) > JS_TIMEOUT ) $ Error = array ( 'error' => 'invalid_request' , 'message' => 'The timestamp is invalid.' ) ; else { $ Signature = self :: JsHash ( $ Request [ 'timestamp' ] . $ Secret , $ Secure ) ; if ( $ Signature != $ Request [ 'signature' ] ) $ Error = array ( 'error' => 'access_denied' , 'message' => 'Signature invalid.' ) ; } } if ( isset ( $ Error ) ) $ Result = $ Error ; elseif ( is_array ( $ User ) && count ( $ User ) > 0 ) { if ( $ Secure === NULL ) { $ Result = $ User ; } else { $ Result = self :: SignJsConnect ( $ User , $ ClientID , $ Secret , $ Secure , TRUE ) ; } } else $ Result = array ( 'name' => '' , 'photourl' => '' ) ; $ Json = json_encode ( $ Result ) ; if ( isset ( $ Request [ 'callback' ] ) ) return "{$Request['callback']}($Json)" ; else return $ Json ; }
Write the jsConnect string for single sign on .
4,303
protected static function JsHash ( $ String , $ Secure = TRUE ) { if ( $ Secure === TRUE ) $ Secure = 'md5' ; switch ( $ Secure ) { case 'sha1' : return sha1 ( $ String ) ; break ; case 'md5' : case FALSE : return md5 ( $ String ) ; default : return hash ( $ Secure , $ String ) ; } }
Return the hash of a string .
4,304
protected static function JsSSOString ( $ User , $ ClientID , $ Secret ) { if ( ! isset ( $ User [ 'client_id' ] ) ) $ User [ 'client_id' ] = $ ClientID ; $ String = base64_encode ( json_encode ( $ User ) ) ; $ Timestamp = time ( ) ; $ Hash = hash_hmac ( 'sha1' , "$String $Timestamp" , $ Secret ) ; $ Result = "$String $Hash $Timestamp hmacsha1" ; return $ Result ; }
Generate an SSO string suitible for passing in the url for embedded SSO .
4,305
public function getData ( ) { $ data = $ this -> data ; foreach ( $ data as $ key => $ value ) { if ( is_object ( $ value ) and $ this -> isWhitelisted ( $ value ) ) { continue ; } if ( $ this -> shouldBeFiltered ( $ key ) ) { if ( $ value instanceof Sanitize ) { $ data [ $ key ] = $ value -> sanitize ( ) ; } else { $ data [ $ key ] = $ this -> filter ( $ value ) ; } } } return $ data ; }
Retrieves all the view data
4,306
protected function shouldBeFiltered ( $ key ) { if ( isset ( $ this -> filterIndex [ $ key ] ) ) { return $ this -> filterIndex [ $ key ] ; } return $ this -> autoFilter ; }
Checks if a key should be filtered or not
4,307
protected function isWhitelisted ( $ object ) { foreach ( $ this -> whitelist as $ whitelisted ) { if ( $ object instanceof $ whitelisted ) { return true ; } } return false ; }
Checks if an object is whitelisted
4,308
public function filter ( $ value ) { if ( is_array ( $ value ) or ( is_object ( $ value ) and $ value instanceof \ ArrayAccess ) ) { return array_map ( [ $ this , 'filter' ] , $ value ) ; } return htmlentities ( $ value , ENT_QUOTES | ENT_HTML5 ) ; }
Filters the output
4,309
public function set ( $ key , $ value = null , $ filter = null ) { parent :: set ( $ key , $ value ) ; if ( is_array ( $ key ) ) { if ( is_bool ( $ value ) ) { $ filter = $ value ; } foreach ( $ key as $ _key => $ _value ) { $ this -> filterIndex [ $ _key ] = $ filter ; } } else { $ this -> filterIndex [ $ key ] = $ filter ; } return $ this ; }
Sets view data
4,310
public function replaceData ( array $ data , $ filter = null ) { $ this -> clearData ( ) ; return $ this -> set ( $ data , $ filter ) ; }
Overwrites all the view data
4,311
public function order ( $ direction = null ) { if ( is_null ( $ direction ) ) { $ direction = $ this -> getOrderDirection ( ) ; } else { $ this -> setOrderDirection ( $ direction ) ; } if ( ! empty ( $ direction ) ) { if ( ! is_string ( $ this -> order ) && is_callable ( $ this -> order ) ) { call_user_func_array ( $ this -> order , $ this ) ; } else { $ table = $ this -> getTable ( ) ; if ( ! $ table -> isSourceQueryBuilder ( ) ) { throw new \ Exception ( 'Table source is not an instance of query builder' ) ; } $ table -> getSource ( ) -> orderBy ( $ this -> order , $ direction ) ; } } return $ this ; }
Order process for the column
4,312
public function isVisible ( $ row = null ) { $ callable = ! is_bool ( $ this -> visible ) && ! is_string ( $ this -> visible ) && is_callable ( $ this -> visible ) ; return ( bool ) ( $ callable ? call_user_func ( $ this -> visible , $ this , $ row ) : $ this -> visible ) ; }
Return if the columns is visible
4,313
protected function checkRequiredTables ( ) { foreach ( [ config ( 'pxlcms.tables.meta.modules' ) , config ( 'pxlcms.tables.meta.fields' ) , config ( 'pxlcms.tables.meta.field_options_choices' ) , config ( 'pxlcms.tables.languages' ) , config ( 'pxlcms.tables.categories' ) , config ( 'pxlcms.tables.files' ) , config ( 'pxlcms.tables.images' ) , config ( 'pxlcms.tables.references' ) , config ( 'pxlcms.tables.checkboxes' ) , ] as $ checkTable ) { if ( ! in_array ( $ checkTable , $ this -> tables ) ) { throw new Exception ( "Could not find expected CMS table in database: '{$checkTable}'" ) ; } } }
Checks if all required tables are present
4,314
protected function detectSlugStructure ( ) { $ this -> context -> slugStructurePresent = false ; $ slugsTable = config ( 'pxlcms.slugs.table' ) ; if ( ! in_array ( $ slugsTable , $ this -> tables ) ) { $ this -> context -> log ( "No slugs table detected." ) ; return ; } $ columns = $ this -> loadColumnListForTable ( $ slugsTable ) ; foreach ( [ config ( 'pxlcms.slugs.keys.module' ) , config ( 'pxlcms.slugs.keys.entry' ) , config ( 'pxlcms.slugs.keys.language' ) , ] as $ requiredColumn ) { if ( in_array ( $ requiredColumn , $ columns ) ) continue ; $ this -> context -> log ( "Slugs table detected but not usable for Sluggable handling!" . " Missing required column '{$requiredColumn}'." , Generator :: LOG_LEVEL_WARNING ) ; return ; } $ this -> context -> slugStructurePresent = true ; $ this -> context -> log ( "Slugs table detected and considered usable for Sluggable handling." ) ; }
Detects whether this CMS has the typical slug table setup
4,315
protected function loadTableList ( ) { if ( $ this -> getDatabaseDriver ( ) === 'sqlite' ) { $ statement = "SELECT name FROM sqlite_master WHERE type='table';" ; } else { $ statement = 'SHOW TABLES' ; } $ tables = DB :: select ( $ statement ) ; $ this -> tables = [ ] ; foreach ( $ tables as $ tableObject ) { $ this -> tables [ ] = array_get ( array_values ( ( array ) $ tableObject ) , '0' ) ; } }
Caches the list of tables in the database
4,316
protected function loadColumnListForTable ( $ table ) { if ( $ this -> getDatabaseDriver ( ) === 'sqlite' ) { $ statement = "PRAGMA table_info(`{$table}`)" ; } else { $ statement = "SHOW columns FROM `{$table}`" ; } $ columnResults = DB :: select ( $ statement ) ; $ columns = [ ] ; foreach ( $ columnResults as $ columnObject ) { $ columns [ ] = array_get ( array_values ( ( array ) $ columnObject ) , '0' ) ; } return $ columns ; }
Returns the column names for a table
4,317
private function prepareBuilder ( ) : void { if ( ! file_exists ( $ this -> getReportCacheDir ( ) ) ) { @ mkdir ( $ this -> getReportCacheDir ( ) , 0777 , true ) ; } $ this -> builder -> setCacheDir ( $ this -> getReportCacheDir ( ) ) -> initialise ( ) ; return ; }
Prepares the builders and creates the cache directory if it doesn t exist .
4,318
public function generate ( $ unlinkFlag = true ) { if ( $ this -> getReportType ( ) === self :: REPORT_EXCEL ) { $ this -> generateExcel ( ) ; header ( 'Pragma: public' ) ; header ( 'Expires: 0' ) ; header ( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' ) ; header ( 'Content-Type: application/force-download' ) ; header ( 'Content-Type: application/octet-stream' ) ; header ( 'Content-Type: application/download' ) ; header ( 'Content-Disposition: attachment;filename=' . $ this -> getFilename ( ) . '.xlsx' ) ; header ( 'Content-Transfer-Encoding: binary ' ) ; readfile ( $ this -> builder -> getTempName ( ) ) ; unlink ( $ this -> builder -> getTempName ( ) ) ; exit ; } throw new UnexpectedValueException ( 'Attempted to generate a report in an unsupported format.' ) ; }
Generate the final report using whatever the set format is .
4,319
public function generateExcel ( ) : void { $ this -> builder -> setCreator ( $ this -> getCreator ( ) ) -> setLastModifiedBy ( $ this -> getCreator ( ) ) -> setTitle ( $ this -> getTitle ( ) ) -> setSubject ( $ this -> getTitle ( ) ) -> setDescription ( $ this -> getDescription ( ) ) ; if ( $ this -> hasSheets ( ) ) { $ this -> createSheets ( ) ; } else { $ headers = $ this -> getHeaders ( ) ; $ reportArray = $ this -> getData ( ) ; $ sheetTitle = $ this -> getSheetTitles ( ) ; $ this -> builder -> setActiveSheetIndex ( 0 ) ; $ this -> createSheet ( $ headers , $ reportArray , $ sheetTitle ) ; } $ this -> builder -> closeAndWrite ( ) ; return ; }
Generates an Excel document .
4,320
public function setApiClient ( $ api_client ) { if ( ! class_exists ( $ api_client ) || ! method_exists ( $ api_client , 'call' ) ) { throw new DataSift_Exception_InvalidData ( 'Class "' . $ api_client . '" does not exist' ) ; } $ this -> _api_client = $ api_client ; }
Set the class to use when calling the API
4,321
public function createHistoric ( $ hash , $ start , $ end , $ sources , $ name , $ sample = DataSift_Historic :: DEFAULT_SAMPLE ) { return new DataSift_Historic ( $ this , $ hash , $ start , $ end , $ sources , $ name , $ sample ) ; }
Create a historic query based on a stream hash .
4,322
public function getConsumer ( $ type , $ hash , $ eventHandler ) { return DataSift_StreamConsumer :: factory ( $ this , $ type , new DataSift_Definition ( $ this , false , $ hash ) , $ eventHandler ) ; }
Returns a DataSift_StreamConsumer - derived object for the given hash for the given type .
4,323
public function getMultiConsumer ( $ type , $ hashes , $ eventHandler ) { return DataSift_StreamConsumer :: factory ( $ this , $ type , $ hashes , $ eventHandler ) ; }
Returns a DataSift_StreamConsumer - derived object for the given hashes for the given type .
4,324
public function listPushSubscriptions ( $ page = 1 , $ per_page = 100 , $ order_by = DataSift_Push_Subscription :: ORDERBY_CREATED_AT , $ order_dir = DataSift_Push_Subscription :: ORDERDIR_ASC , $ include_finished = false ) { return DataSift_Push_Subscription :: listSubscriptions ( $ this , $ page , $ per_page , $ order_by , $ order_dir , $ include_finished ) ; }
Get a list of push subscriptions in your account .
4,325
public function get ( $ endpoint , $ params = array ( ) , $ headers = array ( ) ) { $ res = call_user_func ( array ( $ this -> _api_client , 'call' ) , $ this , $ endpoint , 'get' , array ( ) , $ headers , $ this -> getUserAgent ( ) , $ params ) ; $ this -> _rate_limit = $ res [ 'rate_limit' ] ; $ this -> _rate_limit_remaining = $ res [ 'rate_limit_remaining' ] ; return $ this -> handleResponse ( $ res ) ; }
Make a GET call to a DataSift API endpoint .
4,326
public function supports ( $ className ) { return ( strpos ( $ className , ucfirst ( $ this -> classSuffix ) ) === strlen ( $ className ) - strlen ( $ this -> classSuffix ) ) ; }
Returns true if class has been generated
4,327
public function createGenerator ( $ className ) { $ factory = $ this -> generatorFactory ; $ sourceClass = rtrim ( substr ( $ className , 0 , strpos ( $ className , ucfirst ( $ this -> classSuffix ) ) ) , '\\' ) ; $ entityGenerator = $ factory ( $ sourceClass , $ className ) ; return $ entityGenerator ; }
Creates a generator
4,328
public function listMonetaryAccounts ( $ userId ) { $ monetaryAccounts = $ this -> client -> get ( $ this -> getResourceEndpoint ( $ userId ) ) ; return $ monetaryAccounts ; }
Lists all the Monetary accounts for the current user .
4,329
public function getMonetaryAccount ( $ userId , $ id ) { $ monetaryAccount = $ this -> client -> get ( $ this -> getResourceEndpoint ( $ userId ) . '/' . ( int ) $ id ) ; return $ monetaryAccount [ 'Response' ] [ 0 ] [ 'MonetaryAccountBank' ] ; }
Gets a Monetary Account by its identifier .
4,330
protected function run ( Request $ request ) { if ( ! $ this -> routesConfigured ) { $ this -> adaptor -> configureRoutes ( $ this -> routeProvider ) ; $ this -> routesConfigured = true ; } $ handler = $ this -> adaptor -> route ( $ request ) ; if ( $ handler === false ) { return $ this -> chain ( $ request ) ; } $ request = $ request -> withAttribute ( 'dispatch.handler' , $ this -> resolver -> shift ( $ handler ) ) ; $ dispatchable = $ this -> resolver -> resolve ( $ handler , $ resolutionType ) ; $ parameters = [ $ dispatchable , $ resolutionType , DispatchAdaptorInterface :: SOURCE_ROUTER , $ request ] ; $ response = $ this -> getResponseObject ( ) ; if ( $ response !== null ) { $ parameters [ ] = $ response ; } return $ this -> dispatcher -> dispatch ( ... $ parameters ) ? : $ this -> chain ( $ request ) ; }
Configure and then attempt to route and dispatch for the supplied Request .
4,331
public function setCacheStorage ( WURFL_Storage_Base $ cache ) { if ( ! $ this -> supportsSecondaryCaching ( ) ) { throw new WURFL_Storage_Exception ( "The storage provider " . get_class ( $ cache ) . " cannot be used as a cache for " . get_class ( $ this ) ) ; } $ this -> cache = $ cache ; }
Sets the cache provider for the persistence provider ; this is used to cache data in a volatile storage system like APC in front of a slow persistence provider like the filesystem .
4,332
public function setWURFLLoaded ( $ loaded = true ) { $ this -> save ( self :: WURFL_LOADED , $ loaded ) ; $ this -> cacheSave ( self :: WURFL_LOADED , new StorageObject ( $ loaded , 0 ) ) ; }
Sets the WURFL Loaded flag
4,333
public function findAll ( $ projections = array ( ) , $ sorts = array ( ) , $ options = array ( ) ) { $ options = $ this -> createOption ( $ projections , $ sorts , $ options ) ; if ( ! isset ( $ options [ 'iterator' ] ) || $ options [ 'iterator' ] === false ) { $ objects = parent :: findAll ( $ projections , $ sorts , $ options ) ; foreach ( $ objects as $ object ) { if ( $ this -> getStreamProjection ( $ projections ) ) { $ data [ "stream" ] = $ this -> bucket -> openDownloadStream ( $ object -> getId ( ) ) ; } $ this -> hydrator -> hydrate ( $ object , $ data , true ) ; } return $ objects ; } else { if ( ! is_string ( $ options [ 'iterator' ] ) ) { $ options [ 'iterator' ] = GridFSDocumentIterator :: class ; } return parent :: findAll ( $ projections , $ sorts , $ options ) ; } }
Get all documents of collection
4,334
public function cacheObject ( $ object ) { if ( is_object ( $ object ) ) { $ unhyd = $ this -> hydrator -> unhydrate ( $ object ) ; unset ( $ unhyd [ "stream" ] ) ; $ this -> objectCache -> save ( spl_object_hash ( $ object ) , $ unhyd ) ; } }
Store object in cache to see changes
4,335
public function insertOne ( $ document , $ options = [ ] ) { $ objectDatas = $ this -> hydrator -> unhydrate ( $ document ) ; $ stream = $ objectDatas [ "stream" ] ; unset ( $ objectDatas [ "stream" ] ) ; if ( ! isset ( $ objectDatas [ "filename" ] ) ) { $ filename = stream_get_meta_data ( $ stream ) [ "uri" ] ; } else { $ filename = $ objectDatas [ "filename" ] ; } unset ( $ objectDatas [ "filename" ] ) ; $ id = $ this -> bucket -> uploadFromStream ( $ filename , $ stream , $ objectDatas ) ; $ data [ '_id' ] = $ id ; $ data [ "stream" ] = $ this -> bucket -> openDownloadStream ( $ data [ '_id' ] ) ; $ this -> hydrator -> hydrate ( $ document , $ data , true ) ; $ this -> documentManager -> setObjectState ( $ document , ObjectManager :: OBJ_MANAGED ) ; $ this -> cacheObject ( $ document ) ; return true ; }
Insert a GridFS document
4,336
public function insertMany ( $ documents , $ options = [ ] ) { foreach ( $ documents as $ document ) { if ( ! $ this -> insertOne ( $ document ) ) { return false ; } } return true ; }
Insert multiple GridFS documents
4,337
public function deleteOne ( $ document , $ options = [ ] ) { $ unhydratedObject = $ this -> hydrator -> unhydrate ( $ document ) ; $ id = $ unhydratedObject [ "_id" ] ; $ this -> bucket -> delete ( $ id ) ; $ this -> documentManager -> removeObject ( $ document ) ; }
Delete a document form gr
4,338
public function getUpdateQuery ( $ document ) { $ updateQuery = [ ] ; $ old = $ this -> uncacheObject ( $ document ) ; $ new = $ this -> hydrator -> unhydrate ( $ document ) ; unset ( $ new [ "stream" ] ) ; return $ this -> updateQueryCreator -> createUpdateQuery ( $ old , $ new ) ; }
Create the update query from object diff
4,339
private function getStreamProjection ( $ projections ) { if ( isset ( $ projections [ 'stream' ] ) ) { return $ projections [ 'stream' ] ; } elseif ( empty ( $ projections ) ) { return true ; } else { if ( isset ( $ projections [ '_id' ] ) ) { unset ( $ projections [ '_id' ] ) ; } return reset ( $ projections ) ? false : true ; } }
Get the stream projection
4,340
public function useDefaultPanel ( $ title = '' ) { $ panel = configurator ( ) -> get ( 'panel.class' ) ; $ panel = new $ panel ; $ panel -> setTitle ( strval ( $ title ) ) ; return $ this -> setPanel ( $ panel ) ; }
Set default panel
4,341
protected function isDrupalRoot ( $ directory ) { if ( ! empty ( $ directory ) && is_dir ( $ directory ) && file_exists ( $ directory . DIRECTORY_SEPARATOR . '/index.php' ) ) { return ( file_exists ( $ directory . DIRECTORY_SEPARATOR . 'includes/common.inc' ) && file_exists ( $ directory . DIRECTORY_SEPARATOR . 'misc/drupal.js' ) && file_exists ( $ directory . DIRECTORY_SEPARATOR . 'modules/field/field.module' ) ) ; } return FALSE ; }
Checks if the passed directory is the Drupal root .
4,342
public function run ( ServerRequestInterface $ request , ResponseInterface $ response ) { $ route = $ request -> getAttribute ( 'route' ) ; $ file = ! empty ( $ route -> file ) ? ltrim ( $ route -> file , '/' ) : '' ; if ( $ file [ 0 ] === '~' || strpos ( $ file , '..' ) !== false ) { trigger_error ( "Won't route to '$file': '~', '..' are not allowed in filename" , E_USER_NOTICE ) ; return $ this -> notFound ( $ request , $ response ) ; } if ( ! file_exists ( $ file ) ) { trigger_error ( "Failed to route using '$file': File doesn't exist" , E_USER_NOTICE ) ; return $ this -> notFound ( $ request , $ response ) ; } $ result = $ this -> includeScript ( $ file , $ request , $ response ) ; return $ result === true || $ result === 1 ? $ response : $ result ; }
Route to a file
4,343
public function setDependOn ( $ selector , $ url ) { return $ this -> addAttribute ( 'data-parent-url' , $ url ) -> addAttribute ( 'data-parent-selector' , $ selector ) -> addAttribute ( 'data-populate' , function ( Element $ element ) { return $ element -> getValue ( ) ; } ) -> addClass ( 'select-remote' ) ; }
Set Options from parent selection
4,344
public function toHString ( $ glue = '' ) { if ( empty ( $ this -> arr ) ) { return new HString ( ) ; } $ str = new ArrayToString ( $ this -> arr , $ glue ) ; return new HString ( $ str -> toString ( ) ) ; }
Alias to PHP function implode
4,345
public function paginate ( array $ params ) { if ( isset ( $ params [ $ this -> getParamPage ( ) ] ) ) { $ this -> setPage ( $ params [ $ this -> getParamPage ( ) ] ) ; } return $ this ; }
Fast pagination setup
4,346
public function run ( ) : SendableResponse { $ request = WebRequest :: fromRawSource ( ) ; $ response = new WebResponse ( $ request ) ; if ( $ response -> isFixed ( ) ) { return $ response ; } try { $ requestUri = $ request -> uri ( ) ; } catch ( MalformedUri $ mue ) { $ response -> status ( ) -> badRequest ( ) ; return $ response ; } $ this -> configureRouting ( $ this -> routing ) ; $ uriResource = $ this -> routing -> findResource ( $ requestUri , $ request -> method ( ) ) ; if ( $ this -> switchToHttps ( $ request , $ uriResource ) ) { $ response -> redirect ( $ uriResource -> httpsUri ( ) ) ; return $ response ; } try { if ( ! $ uriResource -> negotiateMimeType ( $ request , $ response ) ) { return $ response ; } $ this -> sessionHandshake ( $ request , $ response ) ; if ( $ uriResource -> applyPreInterceptors ( $ request , $ response ) ) { $ response -> write ( $ uriResource -> resolve ( $ request , $ response ) ) ; $ uriResource -> applyPostInterceptors ( $ request , $ response ) ; } } catch ( \ Exception $ e ) { $ this -> injector -> getInstance ( ExceptionLogger :: class ) -> log ( $ e ) ; $ response -> write ( $ response -> internalServerError ( $ e -> getMessage ( ) ) ) ; } return $ response ; }
runs the application but does not send the response
4,347
private function sessionHandshake ( Request $ request , Response $ response ) { $ session = $ this -> createSession ( $ request , $ response ) ; if ( null !== $ session ) { $ this -> injector -> setSession ( $ request -> attachSession ( $ session ) , Session :: class ) ; } }
ensures session is present when created
4,348
protected function switchToHttps ( Request $ request , UriResource $ uriResource ) : bool { return ! $ request -> isSsl ( ) && $ uriResource -> requiresHttps ( ) ; }
checks whether a switch to https must be made
4,349
public static function humanize ( $ sql , array $ parameters ) { $ parameters = array_map ( __NAMESPACE__ . '\Compiler::quoteValue' , $ parameters ) ; return preg_replace_callback ( '/\?/' , function ( ) use ( & $ parameters ) { return current ( each ( $ parameters ) ) ; } , $ sql ) ; }
Replace placeholders with parameters
4,350
public static function parameters ( array $ items ) { $ parameters = array ( ) ; $ items = array_filter ( Arr :: flatten ( $ items ) ) ; foreach ( $ items as $ item ) { $ itemParams = $ item -> getParameters ( ) ; if ( $ itemParams !== null ) { $ parameters [ ] = $ itemParams ; } } return Arr :: flatten ( $ parameters ) ; }
Get parameters from Parametrised objects
4,351
public static function fromString ( string $ input , string $ locale ) : Resource { $ data = json_decode ( $ input , true ) ; if ( json_last_error ( ) !== \ JSON_ERROR_NONE ) { if ( function_exists ( 'json_last_error_msg' ) ) { throw new \ InvalidArgumentException ( json_last_error_msg ( ) , json_last_error ( ) ) ; } throw new \ InvalidArgumentException ( "Error parsing JSON." , json_last_error ( ) ) ; } return static :: fromArray ( $ data , $ locale ) ; }
Creates a Resource from a JSON string
4,352
public static function fromFile ( string $ file , string $ locale ) : Resource { if ( ! is_file ( $ file ) ) { throw new \ InvalidArgumentException ( "$file is not a file" ) ; } $ contents = file_get_contents ( $ file ) ; if ( $ contents === false ) { throw new \ RuntimeException ( "Error reading file at $file." ) ; } return static :: fromString ( $ contents , $ locale ) ; }
Creates a Resource from a file
4,353
public function toUrl ( $ rawData ) : string { $ data = $ this -> processRawData ( $ rawData ) ; if ( \ is_object ( $ data ) && $ data instanceof \ DateTimeInterface ) { return $ data -> format ( static :: DATE_FORMAT ) ; } if ( \ is_int ( $ data ) ) { return ( new \ DateTime ( ) ) -> setTimestamp ( $ data ) -> format ( static :: DATE_FORMAT ) ; } if ( \ is_string ( $ data ) && $ this -> match ( $ data ) ) { $ sData = ( string ) $ data ; if ( $ this -> checkDate ( $ sData ) ) { return $ sData ; } } throw $ this -> newInvalidToUrl ( $ data ) ; }
Convert passed argument to date in format YYYY - mm - dd
4,354
public function fromUrl ( string $ param ) { if ( $ this -> checkDate ( $ param ) ) { return new \ DateTimeImmutable ( $ param , $ this -> timezone ) ; } throw $ this -> newInvalidFromUrl ( $ param ) ; }
Convert date in format YYYY - mm - dd to \ DateTimeImmutable object
4,355
public function copyValuesFromInterface ( OrderAddressInterface $ from , OrderAddressInterface $ to ) { $ to -> setAccountName ( $ from -> getAccountName ( ) ) ; $ to -> setUid ( $ from -> getUid ( ) ) ; $ to -> setTitle ( $ from -> getTitle ( ) ) ; $ to -> setSalutation ( $ from -> getSalutation ( ) ) ; $ to -> setFirstName ( $ from -> getFirstName ( ) ) ; $ to -> setLastName ( $ from -> getLastName ( ) ) ; $ to -> setEmail ( $ from -> getEmail ( ) ) ; $ to -> setPhone ( $ from -> getPhone ( ) ) ; $ to -> setPhoneMobile ( $ from -> getPhoneMobile ( ) ) ; $ to -> setStreet ( $ from -> getStreet ( ) ) ; $ to -> setNumber ( $ from -> getNumber ( ) ) ; $ to -> setAddition ( $ from -> getAddition ( ) ) ; $ to -> setZip ( $ from -> getZip ( ) ) ; $ to -> setCity ( $ from -> getCity ( ) ) ; $ to -> setState ( $ from -> getState ( ) ) ; $ to -> setCountry ( $ from -> getCountry ( ) ) ; $ to -> setContactAddress ( $ from -> getContactAddress ( ) ) ; $ to -> setNote ( $ from -> getNote ( ) ) ; $ to -> setPostboxCity ( $ from -> getPostboxCity ( ) ) ; $ to -> setPostboxNumber ( $ from -> getPostboxNumber ( ) ) ; $ to -> setPostboxPostcode ( $ from -> getPostboxPostcode ( ) ) ; }
Copies address data from one order - address - interface to another
4,356
public function toArray ( ) { return array ( 'accountName' => $ this -> getAccountName ( ) , 'uid' => $ this -> getUid ( ) , 'title' => $ this -> getTitle ( ) , 'salutation' => $ this -> getSalutation ( ) , 'firstName' => $ this -> getFirstName ( ) , 'lastName' => $ this -> getLastName ( ) , 'email' => $ this -> getEmail ( ) , 'phone' => $ this -> getPhone ( ) , 'phoneMobile' => $ this -> getPhoneMobile ( ) , 'street' => $ this -> getStreet ( ) , 'number' => $ this -> getNumber ( ) , 'addition' => $ this -> getAddition ( ) , 'zip' => $ this -> getZip ( ) , 'city' => $ this -> getCity ( ) , 'state' => $ this -> getState ( ) , 'country' => $ this -> getCountry ( ) , 'note' => $ this -> getNote ( ) , 'contactAddress' => $ this -> getContactAddress ( ) ? array ( 'id' => $ this -> getContactAddress ( ) -> getId ( ) ) : null , 'postboxCity' => $ this -> getPostboxCity ( ) , 'postboxNumber' => $ this -> getPostboxNumber ( ) , 'postboxPostcode' => $ this -> getPostboxPostcode ( ) , ) ; }
Converts a BaseOrderAddress
4,357
public static function getStringRepresentation ( $ mode ) { $ permissions = '' ; if ( ( $ mode & 0xC000 ) == 0xC000 ) { $ permissions = 's' ; } elseif ( ( $ mode & 0xA000 ) == 0xA000 ) { $ permissions = 'l' ; } elseif ( ( $ mode & 0x8000 ) == 0x8000 ) { $ permissions = '-' ; } elseif ( ( $ mode & 0x6000 ) == 0x6000 ) { $ permissions = 'b' ; } elseif ( ( $ mode & 0x4000 ) == 0x4000 ) { $ permissions = 'd' ; } elseif ( ( $ mode & 0x2000 ) == 0x2000 ) { $ permissions = 'c' ; } elseif ( ( $ mode & 0x1000 ) == 0x1000 ) { $ permissions = 'p' ; } else { $ permissions = 'u' ; } $ permissions .= ( ( $ mode & 0x0100 ) ? 'r' : '-' ) ; $ permissions .= ( ( $ mode & 0x0080 ) ? 'w' : '-' ) ; $ permissions .= ( ( $ mode & 0x0040 ) ? ( ( $ mode & 0x0800 ) ? 's' : 'x' ) : ( ( $ mode & 0x0800 ) ? 'S' : '-' ) ) ; $ permissions .= ( ( $ mode & 0x0020 ) ? 'r' : '-' ) ; $ permissions .= ( ( $ mode & 0x0010 ) ? 'w' : '-' ) ; $ permissions .= ( ( $ mode & 0x0008 ) ? ( ( $ mode & 0x0400 ) ? 's' : 'x' ) : ( ( $ mode & 0x0400 ) ? 'S' : '-' ) ) ; $ permissions .= ( ( $ mode & 0x0004 ) ? 'r' : '-' ) ; $ permissions .= ( ( $ mode & 0x0002 ) ? 'w' : '-' ) ; $ permissions .= ( ( $ mode & 0x0001 ) ? ( ( $ mode & 0x0200 ) ? 't' : 'x' ) : ( ( $ mode & 0x0200 ) ? 'T' : '-' ) ) ; return $ permissions ; }
Gives a string representation of the permissions .
4,358
public static function getModeFromStringRepresentation ( $ permissions ) { if ( strlen ( $ permissions ) !== 10 ) { throw new InvalidArgumentException ( 'Please provide a 10 character long string' ) ; } $ mode = 0 ; if ( $ permissions [ 0 ] == 's' ) { $ mode = 0140000 ; } elseif ( $ permissions [ 0 ] == 'l' ) { $ mode = 0120000 ; } elseif ( $ permissions [ 0 ] == '-' ) { $ mode = 0100000 ; } elseif ( $ permissions [ 0 ] == 'b' ) { $ mode = 060000 ; } elseif ( $ permissions [ 0 ] == 'd' ) { $ mode = 040000 ; } elseif ( $ permissions [ 0 ] == 'c' ) { $ mode = 020000 ; } elseif ( $ permissions [ 0 ] == 'p' ) { $ mode = 010000 ; } elseif ( $ permissions [ 0 ] == 'u' ) { $ mode = 0 ; } if ( $ permissions [ 1 ] == 'r' ) { $ mode += 0400 ; } if ( $ permissions [ 2 ] == 'w' ) { $ mode += 0200 ; } if ( $ permissions [ 3 ] == 'x' ) { $ mode += 0100 ; } elseif ( $ permissions [ 3 ] == 's' ) { $ mode += 04100 ; } elseif ( $ permissions [ 3 ] == 'S' ) { $ mode += 04000 ; } if ( $ permissions [ 4 ] == 'r' ) { $ mode += 040 ; } if ( $ permissions [ 5 ] == 'w' ) { $ mode += 020 ; } if ( $ permissions [ 6 ] == 'x' ) { $ mode += 010 ; } elseif ( $ permissions [ 6 ] == 's' ) { $ mode += 02010 ; } elseif ( $ permissions [ 6 ] == 'S' ) { $ mode += 02000 ; } if ( $ permissions [ 7 ] == 'r' ) { $ mode += 04 ; } if ( $ permissions [ 8 ] == 'w' ) { $ mode += 02 ; } if ( $ permissions [ 9 ] == 'x' ) { $ mode += 01 ; } elseif ( $ permissions [ 9 ] == 't' ) { $ mode += 01001 ; } elseif ( $ permissions [ 9 ] == 'T' ) { $ mode += 01000 ; } return $ mode ; }
Converts the string representation to a mode .
4,359
public function setHeader ( $ key , $ value ) { $ this -> headers [ $ key ] = $ value ; $ tmpHeaders = array ( ) ; foreach ( $ this -> headers as $ tmpKey => $ tmpValue ) { $ tmpHeaders [ ] = "$tmpKey: $tmpValue" ; } curl_setopt ( $ this -> handle , CURLOPT_HTTPHEADER , $ tmpHeaders ) ; }
Set request header
4,360
public function identity ( $ title , $ description ) { $ this -> title ( $ title ) ; $ this -> meta ( 'description' , $ description ) ; return $ this ; }
Fast identity set
4,361
public function fb ( $ title = null , $ site = null , $ url = null , $ description = null , $ type = null , $ app = null ) { if ( ! is_null ( $ title ) ) { $ this -> property ( 'og:title' , $ title ) ; } if ( ! is_null ( $ site ) ) { $ this -> property ( 'og:site_name' , $ site ) ; } if ( ! is_null ( $ url ) ) { $ this -> property ( 'og:url' , $ url ) ; } if ( ! is_null ( $ description ) ) { $ this -> property ( 'og:description' , $ description ) ; } if ( ! is_null ( $ url ) ) { $ this -> property ( 'og:type' , $ type ) ; } if ( ! is_null ( $ app ) ) { $ this -> property ( 'fb:app_id' , $ app ) ; } }
Usefool facebook open graph
4,362
public function twitter ( $ title , $ site , $ description , $ image = null , $ card = 'summary' ) { $ this -> meta ( 'twitter:card' , $ card ) ; $ this -> meta ( 'twitter:site' , $ site ) ; $ this -> meta ( 'twitter:title' , $ title ) ; $ this -> meta ( 'twitter:description' , $ description ) ; $ this -> meta ( 'twitter:card' , $ title ) ; if ( ! is_null ( $ image ) ) { $ this -> meta ( 'twitter:image' , $ image ) ; } }
Set twitter meta
4,363
public static function register ( CodeGeneratorInterface $ codeGenerator ) { $ class = get_class ( $ codeGenerator ) ; if ( ! defined ( "$class::ENTITY_CLASS" ) ) { throw new \ Exception ( $ class . ' must define a ENTITY_CLASS constant.' ) ; } if ( ! defined ( "$class::ENTITY_FIELD" ) ) { throw new \ Exception ( $ class . ' must define a ENTITY_FIELD constant.' ) ; } self :: $ generators [ $ codeGenerator :: ENTITY_CLASS ] [ $ codeGenerator :: ENTITY_FIELD ] = $ codeGenerator ; }
Registers an entity code generator service .
4,364
public static function getCodeGenerator ( $ entityClass , $ entityField = 'code' ) { if ( ! isset ( self :: $ generators [ $ entityClass ] [ $ entityField ] ) ) { throw new \ Exception ( "There is no registered entity code generator for class $entityClass and field $entityField" ) ; } return self :: $ generators [ $ entityClass ] [ $ entityField ] ; }
Returns the last registered entity code generator service id for a given entity class and field .
4,365
public static function getCodeGenerators ( $ entityClass = null ) { if ( $ entityClass ) { if ( ! isset ( self :: $ generators [ $ entityClass ] ) ) { throw new \ Exception ( "There is no registered entity code generator for class $entityClass" ) ; } return self :: $ generators [ $ entityClass ] ; } else { return self :: $ generators ; } }
Returns registred code generators for specifyed entity class .
4,366
protected function getModuleData ( $ moduleId ) { $ this -> module_id = $ moduleId ; $ objBannerModule = \ Database :: getInstance ( ) -> prepare ( "SELECT banner_hideempty, banner_firstview, banner_categories, banner_template, banner_redirect, banner_useragent, cssID, space, headline FROM tl_module WHERE id=? AND type=?" ) -> execute ( $ moduleId , 'banner' ) ; if ( $ objBannerModule -> numRows == 0 ) { return false ; } $ this -> banner_hideempty = $ objBannerModule -> banner_hideempty ; $ this -> banner_firstview = $ objBannerModule -> banner_firstview ; $ this -> banner_categories = $ objBannerModule -> banner_categories ; $ this -> banner_template = $ objBannerModule -> banner_template ; $ this -> banner_redirect = $ objBannerModule -> banner_redirect ; $ this -> banner_useragent = $ objBannerModule -> banner_useragent ; $ this -> cssID = $ objBannerModule -> cssID ; $ this -> space = $ objBannerModule -> space ; $ this -> headline = $ objBannerModule -> headline ; return true ; }
Wrapper for backward compatibility
4,367
public function set ( $ csdl ) { if ( $ csdl === false ) { $ this -> _csdl = false ; } else { if ( ! is_string ( $ csdl ) ) { throw new DataSift_Exception_InvalidData ( 'Definitions must be strings.' ) ; } $ csdl = trim ( $ csdl ) ; if ( $ this -> _csdl != $ csdl ) { $ this -> clearHash ( ) ; } $ this -> _csdl = $ csdl ; } }
Sets the definition string .
4,368
protected function clearHash ( ) { if ( $ this -> _csdl === false ) { throw new DataSift_Exception_InvalidData ( 'Cannot clear the hash of a hash-only definition object' ) ; } $ this -> _hash = false ; $ this -> _created_at = false ; $ this -> _total_dpu = false ; }
Reset the hash to false . The effect of this is to mark the definition as requiring compilation . Also resets other variables that depend on the CSDL .
4,369
public function getCreatedAt ( ) { if ( $ this -> _csdl === false ) { throw new DataSift_Exception_InvalidData ( 'Created at date not available' ) ; } if ( $ this -> _created_at === false ) { try { $ this -> validate ( ) ; } catch ( DataSift_Exception_CompileFailed $ e ) { } } return $ this -> _created_at ; }
Returns the date when the stream was first created . If the created at date has not yet been obtained it validates the definition first .
4,370
public function getTotalDPU ( ) { if ( $ this -> _csdl === false ) { throw new DataSift_Exception_InvalidData ( 'Total DPU not available' ) ; } if ( $ this -> _total_dpu === false ) { try { $ this -> validate ( ) ; } catch ( DataSift_Exception_CompileFailed $ e ) { } } return $ this -> _total_dpu ; }
Returns the total DPU of the stream . If the DPU has not yet been obtained it validates the definition first .
4,371
public function compile ( ) { if ( strlen ( $ this -> _csdl ) == 0 ) { throw new DataSift_Exception_InvalidData ( 'Cannot compile an empty definition.' ) ; } try { $ res = $ this -> _user -> post ( 'compile' , array ( 'csdl' => $ this -> _csdl ) ) ; if ( isset ( $ res [ 'hash' ] ) ) { $ this -> _hash = $ res [ 'hash' ] ; } else { throw new DataSift_Exception_CompileFailed ( 'Compiled successfully but no hash in the response' ) ; } if ( isset ( $ res [ 'created_at' ] ) ) { $ this -> _created_at = strtotime ( $ res [ 'created_at' ] ) ; } else { throw new DataSift_Exception_CompileFailed ( 'Compiled successfully but no created_at in the response' ) ; } if ( isset ( $ res [ 'dpu' ] ) ) { $ this -> _total_dpu = $ res [ 'dpu' ] ; } else { throw new DataSift_Exception_CompileFailed ( 'Compiled successfully but no DPU in the response' ) ; } } catch ( DataSift_Exception_APIError $ e ) { $ this -> clearHash ( ) ; switch ( $ e -> getCode ( ) ) { case 400 : throw new DataSift_Exception_CompileFailed ( $ e -> getMessage ( ) ) ; break ; default : throw new DataSift_Exception_CompileFailed ( 'Unexpected APIError code: ' . $ e -> getCode ( ) . ' [' . $ e -> getMessage ( ) . ']' ) ; } } }
Call the DataSift API to compile this defintion . On success it will store the returned hash .
4,372
public function getDPUBreakdown ( ) { $ retval = false ; if ( strlen ( trim ( $ this -> _csdl ) ) == 0 ) { throw new DataSift_Exception_InvalidData ( 'Cannot get the DPU for an empty definition.' ) ; } $ retval = $ this -> _user -> post ( 'dpu' , array ( 'hash' => $ this -> getHash ( ) ) ) ; $ this -> _total_dpu = $ retval [ 'dpu' ] ; return $ retval ; }
Call the DataSift API to get the DPU for this definition . Returns an array containing ... dpu = > The breakdown of running the rule total = > The total dpu of the rule
4,373
public function getBuffered ( $ count = false , $ from_id = false ) { $ retval = false ; if ( strlen ( trim ( $ this -> _csdl ) ) == 0 ) { throw new DataSift_Exception_InvalidData ( 'Cannot get buffered interactions for an empty definition.' ) ; } $ params = array ( 'hash' => $ this -> getHash ( ) ) ; if ( $ count !== false ) { $ params [ 'count' ] = $ count ; } if ( $ from_id !== false ) { $ params [ 'interaction_id' ] = $ from_id ; } $ retval = $ this -> _user -> post ( 'stream' , $ params ) ; if ( isset ( $ retval [ 'stream' ] ) ) { $ retval = $ retval [ 'stream' ] ; } else { throw new DataSift_Exception_APIError ( 'No data in the response' ) ; } return $ retval ; }
Call the DataSift API to get buffered interactions .
4,374
public function createHistoric ( $ start , $ end , $ sources , $ name , $ sample = DataSift_Historic :: DEFAULT_SAMPLE ) { return new DataSift_Historic ( $ this -> _user , $ this -> getHash ( ) , $ start , $ end , $ sources , $ name , $ sample ) ; }
Create a historic based on this CSDL .
4,375
public function getConsumer ( $ type , $ eventHandler ) { return DataSift_StreamConsumer :: factory ( $ this -> _user , $ type , $ this , $ eventHandler ) ; }
Returns a DataSift_StreamConsumer - derived object for this definition for the given type .
4,376
public function prepareCreateTableStatement ( TypeInterface $ type ) { $ result = [ ] ; $ result [ ] = 'CREATE TABLE IF NOT EXISTS ' . $ this -> getConnection ( ) -> escapeTableName ( $ type -> getName ( ) ) . ' (' ; $ generaterd_field_indexes = [ ] ; foreach ( $ type -> getAllFields ( ) as $ field ) { if ( $ field instanceof ScalarField ) { $ result [ ] = ' ' . $ this -> prepareFieldStatement ( $ field ) . ',' ; } if ( $ field instanceof JsonFieldInterface ) { foreach ( $ field -> getValueExtractors ( ) as $ value_extractor ) { $ result [ ] = ' ' . $ this -> prepareGeneratedFieldStatement ( $ field , $ value_extractor ) . ',' ; if ( $ value_extractor -> getAddIndex ( ) ) { $ generaterd_field_indexes [ ] = new Index ( $ value_extractor -> getFieldName ( ) ) ; } } } } $ indexes = $ type -> getAllIndexes ( ) ; if ( ! empty ( $ generaterd_field_indexes ) ) { $ indexes = array_merge ( $ indexes , $ generaterd_field_indexes ) ; } foreach ( $ indexes as $ index ) { $ result [ ] = ' ' . $ this -> prepareIndexStatement ( $ index ) . ',' ; } $ last_line = count ( $ result ) - 1 ; $ result [ $ last_line ] = rtrim ( $ result [ $ last_line ] , ',' ) ; $ result [ ] = ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;' ; return implode ( "\n" , $ result ) ; }
Prepare CREATE TABLE statement for the given type .
4,377
private function prepareFieldStatement ( ScalarField $ field ) { $ result = $ this -> getConnection ( ) -> escapeFieldName ( $ field -> getName ( ) ) . ' ' . $ this -> prepareTypeDefinition ( $ field ) ; if ( $ field -> getDefaultValue ( ) !== null ) { $ result .= ' NOT NULL' ; } if ( ! ( $ field instanceof IntegerField && $ field -> getName ( ) == 'id' ) ) { $ result .= ' DEFAULT ' . $ this -> prepareDefaultValue ( $ field ) ; } return $ result ; }
Prepare field statement based on the field settings .
4,378
private function prepareTypeDefinition ( ScalarField $ field ) { if ( $ field instanceof IntegerField ) { switch ( $ field -> getSize ( ) ) { case FieldInterface :: SIZE_TINY : $ result = 'TINYINT' ; break ; case ScalarField :: SIZE_SMALL : $ result = 'SMALLINT' ; break ; case FieldInterface :: SIZE_MEDIUM : $ result = 'MEDIUMINT' ; break ; case FieldInterface :: SIZE_BIG : $ result = 'BIGINT' ; break ; default : $ result = 'INT' ; } if ( $ field -> isUnsigned ( ) ) { $ result .= ' UNSIGNED' ; } if ( $ field -> getName ( ) == 'id' ) { $ result .= ' AUTO_INCREMENT' ; } return $ result ; } elseif ( $ field instanceof BooleanField ) { return 'TINYINT(1) UNSIGNED' ; } elseif ( $ field instanceof DateField ) { return 'DATE' ; } elseif ( $ field instanceof DateTimeField ) { return 'DATETIME' ; } elseif ( $ field instanceof DecimalField ) { $ result = 'DECIMAL(' . $ field -> getLength ( ) . ', ' . $ field -> getScale ( ) . ')' ; if ( $ field -> isUnsigned ( ) ) { $ result .= ' UNSIGNED' ; } return $ result ; } elseif ( $ field instanceof EnumField ) { return 'ENUM(' . implode ( ',' , array_map ( function ( $ possibility ) { return $ this -> getConnection ( ) -> escapeValue ( $ possibility ) ; } , $ field -> getPossibilities ( ) ) ) . ')' ; } elseif ( $ field instanceof FloatField ) { $ result = 'FLOAT(' . $ field -> getLength ( ) . ', ' . $ field -> getScale ( ) . ')' ; if ( $ field -> isUnsigned ( ) ) { $ result .= ' UNSIGNED' ; } return $ result ; } elseif ( $ field instanceof JsonField ) { return 'JSON' ; } elseif ( $ field instanceof StringField ) { return 'VARCHAR(' . $ field -> getLength ( ) . ')' ; } elseif ( $ field instanceof TextField ) { switch ( $ field -> getSize ( ) ) { case FieldInterface :: SIZE_TINY : return 'TINYTEXT' ; case ScalarField :: SIZE_SMALL : return 'TEXT' ; case FieldInterface :: SIZE_MEDIUM : return 'MEDIUMTEXT' ; default : return 'LONGTEXT' ; } } elseif ( $ field instanceof TimeField ) { return 'TIME' ; } else { throw new InvalidArgumentException ( 'Field ' . get_class ( $ field ) . ' is not a support scalar field' ) ; } }
Prepare type definition for the given field .
4,379
public function prepareDefaultValue ( ScalarField $ field ) { $ default_value = $ field -> getDefaultValue ( ) ; if ( $ default_value === null ) { return 'NULL' ; } if ( $ field instanceof DateField || $ field instanceof DateTimeField ) { $ timestamp = is_int ( $ default_value ) ? $ default_value : strtotime ( $ default_value ) ; if ( $ field instanceof DateTimeField ) { return $ this -> getConnection ( ) -> escapeValue ( date ( 'Y-m-d H:i:s' , $ timestamp ) ) ; } else { return $ this -> getConnection ( ) -> escapeValue ( date ( 'Y-m-d' , $ timestamp ) ) ; } } return $ this -> getConnection ( ) -> escapeValue ( $ default_value ) ; }
Prepare default value .
4,380
public function prepareGeneratedFieldStatement ( FieldInterface $ source_field , ValueExtractorInterface $ extractor ) { $ generated_field_name = $ this -> getConnection ( ) -> escapeFieldName ( $ extractor -> getFieldName ( ) ) ; switch ( $ extractor -> getValueCaster ( ) ) { case ValueCasterInterface :: CAST_INT : $ field_type = 'INT' ; break ; case ValueCasterInterface :: CAST_FLOAT : $ field_type = 'DECIMAL(12, 2)' ; break ; case ValueCasterInterface :: CAST_BOOL : $ field_type = 'TINYINT(1) UNSIGNED' ; break ; case ValueCasterInterface :: CAST_DATE : $ field_type = 'DATE' ; break ; case ValueCasterInterface :: CAST_DATETIME : $ field_type = 'DATETIME' ; break ; case ValueCasterInterface :: CAST_JSON : $ field_type = 'JSON' ; break ; default : $ field_type = 'VARCHAR(191)' ; } $ expression = $ this -> prepareGeneratedFieldExpression ( $ this -> getConnection ( ) -> escapeFieldName ( $ source_field -> getName ( ) ) , var_export ( $ extractor -> getExpression ( ) , true ) , $ extractor -> getValueCaster ( ) , $ this -> getConnection ( ) -> escapeValue ( $ extractor -> getDefaultValue ( ) ) ) ; $ storage = $ extractor -> getStoreValue ( ) ? 'STORED' : 'VIRTUAL' ; return trim ( "$generated_field_name $field_type AS ($expression) $storage" ) ; }
Prpeare generated field statement .
4,381
private function prepareGeneratedFieldExpression ( $ escaped_field_name , $ escaped_expression , $ caster , $ escaped_default_value ) { $ value_extractor_expression = "{$escaped_field_name}->>{$escaped_expression}" ; switch ( $ caster ) { case ValueCasterInterface :: CAST_BOOL : return "IF({$value_extractor_expression} IS NULL, $escaped_default_value, IF({$value_extractor_expression} = 'true' OR ({$value_extractor_expression} REGEXP '^-?[0-9]+$' AND CAST({$value_extractor_expression} AS SIGNED) != 0), 1, 0))" ; case ValueCasterInterface :: CAST_DATE : return "IF({$value_extractor_expression} IS NULL, $escaped_default_value, CAST({$value_extractor_expression} AS DATE))" ; case ValueCasterInterface :: CAST_DATETIME : return "IF({$value_extractor_expression} IS NULL, $escaped_default_value, CAST({$value_extractor_expression} AS DATETIME))" ; case ValueCasterInterface :: CAST_INT : return "IF({$value_extractor_expression} IS NULL, $escaped_default_value, CAST({$value_extractor_expression} AS SIGNED INTEGER))" ; case ValueCasterInterface :: CAST_FLOAT : return "IF({$value_extractor_expression} IS NULL, $escaped_default_value, CAST({$value_extractor_expression} AS DECIMAL(12, 2)))" ; default : return "IF({$value_extractor_expression} IS NULL, $escaped_default_value, {$value_extractor_expression})" ; } }
Prepare extraction statement based on expression .
4,382
public function prepareIndexStatement ( IndexInterface $ index ) { switch ( $ index -> getIndexType ( ) ) { case IndexInterface :: PRIMARY : $ result = 'PRIMARY KEY' ; break ; case IndexInterface :: UNIQUE : $ result = 'UNIQUE ' . $ this -> getConnection ( ) -> escapeFieldName ( $ index -> getName ( ) ) ; break ; case IndexInterface :: FULLTEXT : $ result = 'FULLTEXT ' . $ this -> getConnection ( ) -> escapeFieldName ( $ index -> getName ( ) ) ; break ; default : $ result = 'INDEX ' . $ this -> getConnection ( ) -> escapeFieldName ( $ index -> getName ( ) ) ; break ; } return $ result . ' (' . implode ( ', ' , array_map ( function ( $ field_name ) { return $ this -> getConnection ( ) -> escapeFieldName ( $ field_name ) ; } , $ index -> getFields ( ) ) ) . ')' ; }
Prepare index statement .
4,383
public function prepareConnectionCreateTableStatement ( TypeInterface $ source , TypeInterface $ target , HasAndBelongsToManyAssociation $ association ) { $ result = [ ] ; $ result [ ] = 'CREATE TABLE IF NOT EXISTS ' . $ this -> getConnection ( ) -> escapeTableName ( $ association -> getConnectionTableName ( ) ) . ' (' ; $ left_field_name = $ association -> getLeftFieldName ( ) ; $ right_field_name = $ association -> getRightFieldName ( ) ; $ left_field = ( new IntegerField ( $ left_field_name , 0 ) ) -> unsigned ( true ) -> size ( $ source -> getIdField ( ) -> getSize ( ) ) ; $ right_field = ( new IntegerField ( $ right_field_name , 0 ) ) -> unsigned ( true ) -> size ( $ target -> getIdField ( ) -> getSize ( ) ) ; $ result [ ] = ' ' . $ this -> prepareFieldStatement ( $ left_field ) . ',' ; $ result [ ] = ' ' . $ this -> prepareFieldStatement ( $ right_field ) . ',' ; $ result [ ] = ' ' . $ this -> prepareIndexStatement ( new Index ( 'PRIMARY' , [ $ left_field -> getName ( ) , $ right_field -> getName ( ) ] , IndexInterface :: PRIMARY ) ) . ',' ; $ result [ ] = ' ' . $ this -> prepareIndexStatement ( new Index ( $ right_field -> getName ( ) ) ) ; $ result [ ] = ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;' ; return implode ( "\n" , $ result ) ; }
Prepare create connection table statement .
4,384
public function setComments ( $ comments ) { $ this -> comments = [ ] ; if ( ! is_array ( $ comments ) ) { $ comments = [ $ comments ] ; } foreach ( $ comments as $ comment ) { $ this -> addComment ( $ comment ) ; } return $ this ; }
Sets comments .
4,385
public function execute ( $ sqlQuery , $ params = [ ] , $ prefix = '' ) { if ( $ prefix !== '' ) $ this -> _testQueryStarts ( $ sqlQuery , $ prefix ) ; $ statement = $ this -> _executeQuery ( $ sqlQuery , $ params ) ; return $ statement -> rowCount ( ) ; }
Execute given SQL query . Please DON T use instead of other functions
4,386
private function checkConnection ( ) { if ( $ this -> _databaseServer !== self :: DB_MYSQL ) { return ; } $ interval = ( time ( ) - ( int ) $ this -> _lastCheckTime ) ; if ( $ interval >= self :: MYSQL_CONNECTION_TIMEOUT ) { $ this -> connect ( ) ; } }
if last query was too long time ago - reconnect
4,387
private function _getWarnings ( $ sqlQueryString , $ options = [ ] ) { if ( $ this -> _databaseServer === self :: DB_MYSQL ) { $ stm = $ this -> _pdo -> query ( 'SHOW WARNINGS' ) ; $ sqlWarnings = $ stm -> fetchAll ( \ PDO :: FETCH_ASSOC ) ; } else { $ sqlWarnings = [ [ 'Message' => 'WarningReporting not impl. for ' . $ this -> _pdo -> getAttribute ( \ PDO :: ATTR_DRIVER_NAME ) ] ] ; } if ( count ( $ sqlWarnings ) > 0 ) { $ warnings = "Query:\n{$sqlQueryString}\n" ; if ( ! empty ( $ options ) ) { $ warnings .= "Params: (" ; foreach ( $ options as $ key => $ value ) { $ warnings .= $ key . '=' . json_encode ( $ value ) . ', ' ; } $ warnings = substr ( $ warnings , 0 , - 2 ) . ")\n" ; } $ warnings .= "Produced Warnings:" ; foreach ( $ sqlWarnings as $ warn ) { $ warnings .= "\n* " . $ warn [ 'Message' ] ; } return $ warnings ; } return '' ; }
gathers Warning info from \ PDO
4,388
public function addExportData ( $ key , $ data = null ) : PrepareOrderExportEvent { if ( is_array ( $ key ) ) { $ this -> exportData = array_merge ( $ this -> exportData , $ key ) ; } else { $ this -> exportData [ $ key ] = $ data ; } return $ this ; }
Adds an exportable data .
4,389
public function factoryUser ( $ user , $ password , $ name , $ group , $ role , $ status , $ email = null , $ iduser = null , $ extra = [ ] ) { $ this -> user = $ user ; $ this -> password = $ password ; $ this -> fullName = $ name ; $ this -> group = $ group ; $ this -> role = $ role ; $ this -> status = $ status ; $ this -> email = $ email ; $ this -> iduser = $ iduser ; $ this -> extraFields = $ extra ; }
It sets the current user .
4,390
public function serialize ( ) { $ r = [ 'user' => $ this -> user , 'name' => $ this -> fullName , 'uid' => $ this -> uid , 'group' => $ this -> group , 'role' => $ this -> role ] ; if ( $ this -> email !== null ) $ r [ 'email' ] = $ this -> email ; if ( $ this -> iduser !== null ) $ r [ 'iduser' ] = $ this -> iduser ; $ r [ 'extrafields' ] = $ this -> extraFields ; return $ r ; }
Returns an associative array with the current user
4,391
public function deserialize ( $ array ) { $ this -> user = @ $ array [ 'user' ] ; $ this -> fullName = @ $ array [ 'name' ] ; $ this -> uid = @ $ array [ 'uid' ] ; $ this -> group = @ $ array [ 'group' ] ; $ this -> role = @ $ array [ 'role' ] ; $ this -> status = @ $ array [ 'status' ] ; $ this -> email = @ $ array [ 'email' ] ; $ this -> iduser = @ $ array [ 'iduser' ] ; $ this -> extraFields = @ $ array [ 'extrafields' ] ; }
Set the current user by using an associative array
4,392
public function login ( $ user , $ password , $ storeCookie = false ) { $ this -> user = $ user ; $ this -> password = $ this -> encrypt ( $ password ) ; $ this -> uid = $ this -> genUID ( ) ; if ( call_user_func ( $ this -> loginFn , $ this ) ) { $ this -> fixSession ( $ storeCookie && $ this -> useCookie ) ; return true ; } else { @ session_destroy ( ) ; @ session_write_close ( ) ; $ this -> isLogged = false ; return false ; } }
It s used when the user log with an user and password . So it must be used only in the login screen . After that the user is stored in the session .
4,393
public function logout ( ) { $ this -> user = "" ; $ this -> password = "" ; $ this -> isLogged = false ; if ( $ this -> useCookie ) { unset ( $ _COOKIE [ 'phpcookiesess' ] ) ; setcookie ( 'phpcookiesess' , null , - 1 , '/' ) ; } @ session_destroy ( ) ; @ session_write_close ( ) ; }
Logout and the session is destroyed . It doesn t redirect to the home page .
4,394
public function isLogged ( ) { if ( ! $ this -> isLogged ) return false ; if ( $ this -> genUID ( ) != $ this -> uid ) return false ; return true ; }
Returns true if the user is logged . False if not . It also returns false if the UID doesn t correspond .
4,395
public function getCurrent ( $ closeSession = false ) { if ( session_status ( ) === PHP_SESSION_ACTIVE ? TRUE : FALSE ) { $ b = @ session_start ( ) ; if ( ! $ b ) return false ; } $ obj = @ $ _SESSION [ '_user' ] ; if ( $ obj !== null ) $ this -> deserialize ( $ obj ) ; if ( $ closeSession ) @ session_write_close ( ) ; return $ obj ; }
Load current user . It returns an array
4,396
public function getByClass ( $ className ) { $ types = array_unique ( Arr :: wrap ( Arr :: get ( $ this -> classMapping , $ className , [ ] ) ) ) ; $ resolved = array_map ( [ $ this , 'get' ] , $ types ) ; return $ this -> firstOrAll ( Arr :: collapse ( $ resolved ) ) ; }
Get the resolved resource by type .
4,397
public function add ( $ key , $ value ) { parent :: add ( $ key , $ value ) ; if ( is_object ( $ value ) === false ) { return ; } $ this -> classMapping [ get_class ( $ value ) ] [ ] = $ key ; }
Add resolved resource to the collection .
4,398
public function read ( $ id ) { try { $ result = $ this -> db -> from ( $ this -> table ) -> where ( $ this -> columns [ 'id' ] ) -> eq ( $ id ) -> column ( $ this -> columns [ 'data' ] ) ; return $ result === false ? '' : $ result ; } catch ( PDOException $ e ) { return '' ; } }
Returns session data .
4,399
public function gc ( $ maxLifetime ) { try { return ( bool ) $ this -> db -> from ( $ this -> table ) -> where ( $ this -> columns [ 'expires' ] ) -> lt ( time ( ) ) -> delete ( ) ; } catch ( PDOException $ e ) { return false ; } }
Garbage collector .