idx
int64
0
60.3k
question
stringlengths
92
4.62k
target
stringlengths
7
635
100
protected function buildBulkInsert ( $ data , $ set_timestamps ) { $ fields = array ( ) ; $ values = array ( ) ; $ template = "INSERT INTO %s (%s) VALUES %s" ; $ fieldsArray = $ data [ 0 ] ; foreach ( $ fieldsArray as $ field => $ value ) { $ fields [ ] = $ field ; } $ count = sizeof ( $ data ) ; for ( $ i = 0 ; $ i < $ count ; $ i ++ ) { $ array = $ data [ $ i ] ; $ valuesArray = array ( ) ; foreach ( $ array as $ field => $ value ) { $ valuesArray [ ] = $ this -> quote ( $ value ) ; } $ values [ ] = '(' . join ( ", " , $ valuesArray ) . ')' ; } $ fields = join ( ", " , $ fields ) ; $ values = join ( ", " , $ values ) ; return sprintf ( $ template , $ this -> froms , $ fields , $ values ) ; }
This method builds the insert query for more than one row of data .
101
protected function buildUpdate ( $ data , $ set_timestamps ) { $ parts = array ( ) ; $ where = $ limit = '' ; $ template = "UPDATE %s SET %s %s %s" ; if ( $ set_timestamps ) $ data [ 'date_modified' ] = date ( 'Y-m-d h:i:s' ) ; foreach ( $ data as $ field => $ value ) { $ parts [ ] = "{$field}=" . $ this -> quote ( $ value ) ; } $ parts = join ( ", " , $ parts ) ; $ queryWhere = $ this -> wheres ; if ( ! empty ( $ queryWhere ) ) { $ joined = join ( " AND " , $ queryWhere ) ; $ where = "WHERE {$joined}" ; } $ queryLimit = $ this -> limits ; if ( ! empty ( $ queryLimit ) ) { $ limitOffset = $ this -> offset ; $ limit = "LIMIT {$queryLimit} {$limitOffset}" ; } return sprintf ( $ template , $ this -> froms , $ parts , $ where , $ limit ) ; }
This method builds an update query for a single record of data .
102
protected function buildBulkUpdate ( $ data , $ fields , $ ids , $ key ) { $ parts = array ( ) ; $ template = "UPDATE %s SET %s WHERE %s IN (%s) " ; foreach ( $ fields as $ index => $ field ) { $ subparts = $ field . ' = (CASE ' . $ key . ' ' ; foreach ( $ data as $ id => $ info ) { if ( ! empty ( $ info ) ) { $ subparts .= ' WHEN ' . $ id . ' THEN ' . $ this -> quote ( $ info [ $ field ] ) . ' ' ; } } $ subparts .= ' END) ' ; $ parts [ ] = $ subparts ; } $ parts = join ( ", " , $ parts ) ; $ queryWhere = $ ids ; if ( ! empty ( $ queryWhere ) ) { $ where = join ( ", " , $ queryWhere ) ; } return sprintf ( $ template , $ this -> froms , $ parts , $ key , $ where ) ; }
This method builds the SQL query string for updating large amounts of data .
103
protected function buildDelete ( ) { $ where = $ limit = '' ; $ template = "DELETE FROM %s %s %s" ; $ queryWhere = $ this -> wheres ; if ( ! empty ( $ queryWhere ) ) { $ joined = join ( " AND " , $ queryWhere ) ; $ where = "WHERE {$joined}" ; } $ queryLimit = $ this -> limits ; if ( ! empty ( $ queryLimit ) ) { $ limitOffset = $ this -> offset ; $ limit = "LIMIT {$queryLimit} {$limitOffset}" ; } return sprintf ( $ template , $ this -> froms , $ where , $ limit ) ; }
This method builds the SQL query string to perform a delete query .
104
public function delete ( ) { $ sql = $ this -> buildDelete ( ) ; $ this -> responseObject -> setQueryString ( $ sql ) ; $ query_start_time = microtime ( true ) ; $ result = $ this -> connector -> execute ( $ sql ) ; $ query_stop_time = microtime ( true ) ; $ query_excec_time = $ query_stop_time - $ query_start_time ; $ this -> responseObject -> setQueryTime ( $ query_excec_time ) ; try { if ( $ result === false ) { throw new MySQLException ( get_class ( new MySQLException ) . ' ' . $ this -> connector -> lastError ( ) . '<span class="query-string"> (' . $ sql . ') </span>' ) ; } } catch ( MySQLException $ MySQLExceptionObject ) { $ MySQLExceptionObject -> errorShow ( ) ; } $ this -> responseObject -> setAffectedRows ( $ this -> connector -> affectedRows ( ) ) ; return $ this -> responseObject ; }
This method deletes a set of rows that match the query parameters provided .
105
public function first ( ) { $ limit = $ this -> limits ; $ limitOffset = $ this -> offset ; $ this -> limit ( 1 ) ; $ all = $ this -> all ( ) ; $ first = ArrayUtility :: first ( $ all -> result_array ( ) ) -> get ( ) ; if ( $ limit ) { $ this -> limits = $ limit ; } if ( $ limitOffset ) { $ this -> offset = $ limitOffset ; } $ this -> responseObject -> setResultArray ( $ first ) ; return $ this -> responseObject ; }
This method returns the first row match in a query .
106
public function count ( ) { $ limit = $ this -> limits ; $ limitOffset = $ this -> offset ; $ fields = $ this -> fields ; $ this -> fields = array ( $ this -> froms => array ( "COUNT(1)" => "rows" ) ) ; $ this -> limit ( 1 ) ; $ row = $ this -> first ( ) -> result_array ( ) ; $ this -> fields = $ fields ; if ( $ fields ) { $ this -> fields = $ fields ; } if ( $ limit ) { $ this -> limits = $ limit ; } if ( $ limitOffset ) { $ this -> offset = $ limitOffset ; } $ this -> responseObject -> setNumRows ( $ row [ 0 ] [ 'rows' ] ) -> setResultArray ( $ row ) ; return $ this -> responseObject ; }
This method counts the number of rows returned by query .
107
public function all ( ) { $ sql = $ this -> buildSelect ( ) ; $ this -> query_string = $ sql ; $ query_start_time = microtime ( true ) ; $ result = $ this -> connector -> execute ( $ sql ) ; $ query_stop_time = microtime ( true ) ; $ query_excec_time = $ query_stop_time - $ query_start_time ; try { if ( $ result === false ) { $ error = $ this -> connector -> lastError ( ) ; throw new MySQLException ( get_class ( new MySQLException ) . ' ' . $ this -> connector -> lastError ( ) . '<span class="query-string"> (' . $ sql . ') </span>' ) ; } } catch ( MySQLException $ MySQLExceptionObject ) { $ MySQLExceptionObject -> errorShow ( ) ; } $ result_array = array ( ) ; while ( $ row = $ result -> fetch_array ( MYSQLI_ASSOC ) ) { $ result_array [ ] = $ row ; } $ this -> responseObject -> setQueryString ( $ this -> query_string ) -> setQueryTime ( $ query_excec_time ) -> setFieldCount ( $ result -> field_count ) -> setNumRows ( $ result -> num_rows ) -> setQueryFields ( $ result -> fetch_fields ( ) ) -> setResultArray ( $ result_array ) ; return $ this -> responseObject ; }
This method returns all rows that match the query parameters .
108
public function rawQuery ( $ query_string ) { try { $ result = $ this -> connector -> execute ( $ query_string ) ; if ( $ result === false ) { throw new MySQLException ( get_class ( new MySQLException ) . ' ' . $ this -> connector -> lastError ( ) . '<span class="query-string"> (' . $ query_string . ') </span>' ) ; } else return $ result ; } catch ( MySQLException $ MySQLExceptionObject ) { $ MySQLExceptionObject -> errorShow ( ) ; } }
This method executes a raw query in the database .
109
public function initialize ( ) { $ this -> engine = $ this -> initEngine ( ) ; foreach ( $ this -> application -> config ( 'renderer.initializers.*' ) as $ initializer ) { $ initializer ( $ this -> application , $ this ) ; } }
initialize method .
110
public function createUploadedFiles ( array $ files ) { $ instances = [ ] ; foreach ( $ files as $ name => $ value ) { if ( $ value instanceof UploadedFileInterface ) { $ instances [ $ name ] = $ value ; continue ; } if ( ! is_array ( $ value ) ) { $ class = UploadedFileInterface :: class ; throw new \ InvalidArgumentException ( "The file list must be an associative array whose value is" . " an instance of a class implementing {$class} or an array" . " having file information." . " But the value of index A does not apply to them." ) ; } $ instances [ $ name ] = isset ( $ value [ "error" ] ) && isset ( $ value [ "tmp_name" ] ) ? $ this -> createUploadedFileWithNest ( $ value ) : $ this -> createUploadedFiles ( $ value ) ; } return $ instances ; }
Create a new uploaded files .
111
public function find ( ) { $ criteria = call_user_func_array ( array ( $ this , 'argsToCriteria' ) , func_get_args ( ) ) ; $ criteria -> limit ( 1 ) ; $ entities = $ this -> findAll ( $ criteria ) ; return $ entities -> first ( ) ; }
find by id or criteria . return first entity .
112
public function findAll ( ) { $ criteria = call_user_func_array ( array ( $ this , 'argsToCriteria' ) , func_get_args ( ) ) ; $ schema = $ this -> getSchema ( ) ; if ( $ schema -> hasColumn ( 'active' ) ) { $ criteria -> where ( 'active = ?' , 1 ) ; } $ sql = $ criteria -> toSQL ( ) ; $ sth = $ this -> query ( $ sql , $ criteria -> getParams ( ) , Database :: TARGET_SLAVE ) ; $ entities = new Entities ( $ this ) ; $ entities -> setCriteria ( $ criteria ) ; foreach ( $ sth -> fetchAll ( Connection :: FETCH_ASSOC ) as $ row ) { $ entities -> add ( $ this -> build ( $ row , true ) ) ; } return $ entities ; }
find by criteria . return all entities .
113
public function destroy ( Entity $ entity ) { if ( $ entity -> isExists ( ) ) { if ( $ entity -> hasAttribute ( 'active' ) ) { $ attributes = [ ] ; $ attributes [ 'active' ] = 0 ; if ( $ entity -> hasAttribute ( 'deleted_at' ) ) $ attributes [ 'deleted_at' ] = time ( ) ; $ this -> update ( $ attributes , $ entity -> getPrimaryValue ( ) ) ; } else { $ this -> delete ( $ entity -> getPrimaryValue ( ) ) ; } } }
destroy entity .
114
public function update ( ) { $ args = func_get_args ( ) ; $ attributes = array_shift ( $ args ) ; $ criteria = call_user_func_array ( array ( $ this , 'argsToCriteria' ) , $ args ) ; $ sql = $ criteria -> toUpdateSQL ( $ attributes ) ; $ sth = $ this -> query ( $ sql , $ criteria -> getParams ( ) , Database :: TARGET_MASTER ) ; return $ sth -> isSuccess ( ) ; }
update by criteria .
115
public function criteria ( Criteria \ Criteria $ cri = null ) { if ( ! $ cri ) $ cri = new Criteria \ Criteria ( $ this ) ; $ cri -> setTable ( $ this ) ; return $ cri ; }
get criteria instance .
116
public function argsToCriteria ( ) { $ args = func_get_args ( ) ; $ first = array_shift ( $ args ) ; $ criteria = $ this -> criteria ( ) ; if ( $ first instanceof Criteria \ Criteria ) { return $ first ; } elseif ( $ first instanceof Criteria \ BaseCondition ) { return $ first -> getCriteria ( ) ; } if ( is_numeric ( $ first ) ) { $ criteria -> where ( sprintf ( '%s = ?' , $ this -> getPrimaryKey ( ) ) , $ first ) ; } elseif ( is_string ( $ first ) ) { array_unshift ( $ args , $ first ) ; call_user_func_array ( array ( $ criteria , 'where' ) , $ args ) ; } return $ criteria ; }
args convert to criteria .
117
public function initializePager ( SimplePager $ pager , Criteria \ Criteria $ criteria ) { if ( $ criteria -> offset !== null && $ criteria -> limit !== null ) { $ pager -> setNow ( floor ( $ criteria -> offset / $ criteria -> limit ) + 1 ) ; $ pager -> setPerPage ( $ criteria -> limit ) ; } elseif ( $ criteria -> limit !== null ) { $ pager -> setPerPage ( $ criteria -> limit ) ; } $ criteria -> columns ( 'COUNT(1)' ) -> limit ( null ) -> offset ( null ) ; $ pager -> setTotal ( $ this -> getOne ( $ criteria ) ) ; return $ pager ; }
initialize paging helper
118
public function toArray ( ) { $ params = array ( ) ; foreach ( $ this -> getParams ( ) as $ param ) { $ params [ $ param -> getName ( ) ] = $ param -> toArray ( ) ; } $ m = array ( 'parameters' => $ params , ) ; if ( $ this -> use_canonical ) { $ m [ 'target' ] = $ this -> smd -> getTarget ( ) . '/' . $ this -> service -> getDottedClassname ( ) . '.' . $ this -> getName ( ) ; } return $ m ; }
Return un array description of the method .
119
public function executeOrFail ( $ message = 'Timed out attempting to execute callback' ) { $ result = $ this -> execute ( ) ; if ( empty ( $ result ) ) { throw new RuntimeException ( $ message ) ; } return $ result ; }
Like normal execute but throw RuntimeException on time out
120
public function shutdown ( Event $ event ) { $ action = $ event -> subject ( ) -> request -> action ; if ( ! isset ( $ event -> subject ( ) -> viewVars [ '_ws' ] ) ) { return ; } $ _ws = $ event -> subject ( ) -> viewVars [ '_ws' ] ; $ data = ( isset ( $ _ws ) && isset ( $ _ws [ 'data' ] ) ) ? $ _ws [ 'data' ] : null ; $ users = ( isset ( $ _ws ) && isset ( $ _ws [ 'users' ] ) ) ? $ _ws [ 'users' ] : null ; if ( get_class ( $ users ) === 'Cake\ORM\ResultSet' ) { $ users = $ users -> extract ( 'id' ) -> toArray ( ) ; } else { } $ trigger = new Trigger ( $ this -> _controller ) ; $ trigger -> publish ( $ data , $ users ) ; }
Callback fired before the output is sent to the browser and launches the event on websockets if need be .
121
public function setRoot ( $ inDataOrNode ) { $ this -> __root = $ inDataOrNode instanceof Node ? $ inDataOrNode : new Node ( $ inDataOrNode ) ; return $ this ; }
Set the root node of the tree .
122
static public function fromArray ( array $ inArray , callable $ inOptDeserializer = null , $ inOptDataTag = 'data' , $ inOptChildrenTag = 'children' ) { if ( is_null ( $ inOptDeserializer ) ) { $ inOptDeserializer = function ( $ inSerialised ) { return $ inSerialised ; } ; } self :: $ __dataTag = $ inOptDataTag ; self :: $ __childrenTag = $ inOptChildrenTag ; $ result = [ 'tree' => new Tree ( ) , 'index' => [ ] , 'id' => 0 ] ; $ builder = function ( array & $ inCurrentNode , $ isLeaf , & $ inParentNode , array & $ inOutData ) use ( $ inOptDeserializer , $ inOptDataTag , $ inOptChildrenTag ) { if ( ! array_key_exists ( $ inOptDataTag , $ inCurrentNode ) ) { throw new \ Exception ( "The given array is not valid. No data defined for the current node!" ) ; } if ( ! array_key_exists ( $ inOptChildrenTag , $ inCurrentNode ) ) { throw new \ Exception ( "The given array is not valid. No children defined for the current node!" ) ; } if ( ! is_array ( $ inCurrentNode [ $ inOptChildrenTag ] ) ) { throw new \ Exception ( "This given array in not a valid tree. Key $inOptChildrenTag is not an array!" ) ; } $ currentNodeId = $ inOutData [ 'id' ] ; $ inOutData [ 'id' ] += 1 ; $ inCurrentNode [ 'id' ] = $ currentNodeId ; if ( is_null ( $ inParentNode ) ) { $ tree = $ inOutData [ 'tree' ] ; $ root = new Node ( $ inOptDeserializer ( $ inCurrentNode [ $ inOptDataTag ] ) ) ; $ tree -> setRoot ( $ root ) ; $ inOutData [ 'index' ] [ $ currentNodeId ] = $ root ; return ; } $ parent = $ inOutData [ 'index' ] [ $ inParentNode [ 'id' ] ] ; $ newNode = $ parent -> addChild ( $ inOptDeserializer ( $ inCurrentNode [ $ inOptDataTag ] ) ) ; $ inOutData [ 'index' ] [ $ currentNodeId ] = $ newNode ; } ; self :: arrayTraverse ( $ inArray , $ builder , $ result ) ; return $ result [ 'tree' ] ; }
Create a tree from an array .
123
public function search ( $ inData , $ inOptLimit = 0 , callable $ inOptDataComparator = null ) { if ( is_null ( $ inOptDataComparator ) ) { $ inOptDataComparator = $ this -> __dataComparator ; } $ result = [ 'found' => [ ] , 'count' => 0 , 'continue' => true ] ; $ find = function ( Node $ inNode , array & $ inOutResult ) use ( $ inData , $ inOptLimit , $ inOptDataComparator ) { if ( ! $ inOutResult [ 'continue' ] ) { return ; } if ( $ inOptDataComparator ( $ inData , $ inNode -> getData ( ) ) ) { $ inOutResult [ 'found' ] [ ] = $ inNode ; $ inOutResult [ 'count' ] += 1 ; if ( $ inOptLimit > 0 ) { if ( $ inOutResult [ 'count' ] >= $ inOptLimit ) { $ inOutResult [ 'continue' ] = false ; } } } } ; $ this -> traverse ( $ find , $ result ) ; return $ result [ 'found' ] ; }
Search for nodes that have a given data value within the tree .
124
public function select ( callable $ inSelector , $ inOptLimit = 0 ) { $ result = [ 'found' => [ ] , 'count' => 0 , 'continue' => true ] ; $ find = function ( Node $ inNode , array & $ inOutResult ) use ( $ inOptLimit , $ inSelector ) { if ( ! $ inOutResult [ 'continue' ] ) { return ; } if ( $ inSelector ( $ inNode -> getData ( ) ) ) { $ inOutResult [ 'found' ] [ ] = $ inNode ; $ inOutResult [ 'count' ] += 1 ; if ( $ inOptLimit > 0 ) { if ( $ inOutResult [ 'count' ] >= $ inOptLimit ) { $ inOutResult [ 'continue' ] = false ; } } } } ; $ this -> traverse ( $ find , $ result ) ; return $ result [ 'found' ] ; }
Select all nodes that verify a criterion .
125
public function index ( callable $ inOptDataIndexBuilder = null , $ inOptUnique = true ) { if ( is_null ( $ inOptDataIndexBuilder ) ) { $ inOptDataIndexBuilder = $ this -> __dataIndexBuilder ; } $ index = [ ] ; $ dataMaker = function ( Node $ inNode , array & $ inOutResult ) use ( $ inOptDataIndexBuilder , $ inOptUnique ) { if ( $ inOptUnique ) { $ inOutResult [ $ inOptDataIndexBuilder ( $ inNode -> getData ( ) ) ] = $ inNode ; } else { $ inOutResult [ $ inOptDataIndexBuilder ( $ inNode -> getData ( ) ) ] [ ] = $ inNode ; } } ; $ this -> getRoot ( ) -> traverse ( $ dataMaker , $ index ) ; return $ index ; }
This method creates an index of all the nodes in the tree .
126
public function toDot ( callable $ inOptDataToStringConverter = null ) { if ( is_null ( $ inOptDataToStringConverter ) ) { $ inOptDataToStringConverter = $ this -> __dataToStringConverter ; } $ data = [ 'nodes' => [ ] , 'edges' => [ ] ] ; $ toDot = function ( Node $ inNode , array & $ inOutResult ) use ( $ inOptDataToStringConverter ) { $ nodeId = spl_object_hash ( $ inNode ) ; $ nodeLabel = $ inOptDataToStringConverter ( $ inNode -> getData ( ) ) ; $ inOutResult [ 'nodes' ] [ ] = ' "' . $ nodeId . '" [label="' . $ nodeLabel . '"];' ; if ( $ inNode -> isRoot ( ) ) { return ; } $ parentId = spl_object_hash ( $ inNode -> getParent ( ) ) ; $ inOutResult [ 'edges' ] [ ] = ' "' . $ parentId . '" -> "' . $ nodeId . '";' ; } ; $ this -> getRoot ( ) -> traverse ( $ toDot , $ data ) ; $ dot = [ "digraph mytree {" ] ; foreach ( $ data [ 'nodes' ] as $ node ) { array_push ( $ dot , $ node ) ; } foreach ( $ data [ 'edges' ] as $ edge ) { array_push ( $ dot , $ edge ) ; } array_push ( $ dot , "}" ) ; array_push ( $ dot , "/* Usage: dot -Tgif -Ograph graph.dot */" ) ; return implode ( "\n" , $ dot ) ; }
Generate the DOT representation of the tree .
127
static public function arrayTraverse ( array $ inNode , callable $ inFunction , array & $ inOutResult , array $ inOptParent = null ) { if ( ! array_key_exists ( self :: $ __dataTag , $ inNode ) ) { throw new \ Exception ( "This given array in not a valid tree. Key '" . self :: $ __dataTag . "' is missing!" ) ; } if ( ! array_key_exists ( self :: $ __childrenTag , $ inNode ) ) { throw new \ Exception ( "This given array in not a valid tree. Key '" . self :: $ __childrenTag . "' is missing!" ) ; } if ( ! is_array ( $ inNode [ self :: $ __childrenTag ] ) ) { throw new \ Exception ( "This given array in not a valid tree. Key '" . self :: $ __childrenTag . "' is not an array!" ) ; } $ inFunction ( $ inNode , count ( $ inNode [ self :: $ __childrenTag ] ) > 0 , $ inOptParent , $ inOutResult ) ; foreach ( $ inNode [ self :: $ __childrenTag ] as $ _child ) { if ( count ( $ _child [ self :: $ __childrenTag ] ) > 0 ) { self :: arrayTraverse ( $ _child , $ inFunction , $ inOutResult , $ inNode ) ; continue ; } $ inFunction ( $ _child , true , $ inNode , $ inOutResult ) ; } }
Walk through a tree defined as a combination of associative arrays .
128
public function compile ( LocalFile $ _bap_path , array $ _bap_data = [ ] ) : string { if ( ! $ _bap_path -> exists ) { throw new TemplateNotFoundException ( $ _bap_path ) ; } $ _bap_level = ob_get_level ( ) ; ob_start ( ) ; if ( extract ( $ _bap_data , EXTR_SKIP ) !== count ( $ _bap_data ) ) { throw new ParseError ( 'Invalid variable name used' ) ; } try { include $ _bap_path -> full_path ; } catch ( Throwable $ e ) { while ( ob_get_level ( ) > $ _bap_level ) { ob_end_clean ( ) ; } throw new TemplateCompilationError ( $ _bap_path , $ e ) ; } return ltrim ( ob_get_clean ( ) ) ; }
Compile a template
129
function get_inner_html ( DOMElement $ element ) { $ inner_html = '' ; $ children = $ element -> childNodes ; foreach ( $ children as $ child ) { $ inner_html .= $ child -> ownerDocument -> saveXML ( $ child ) ; } return $ inner_html ; }
Gets the inner HTML of a given DOMElement .
130
protected function createMemcachedStore ( ) { $ serverArray = $ this -> config [ 'servers' ] ; $ persistent = boolval ( $ this -> config [ 'persistent' ] ) ; $ name = trim ( $ this -> config [ 'server_name' ] ) ; $ prefix = trim ( $ this -> config [ 'prefix' ] ) ; if ( $ persistent && ( strlen ( $ name ) > 0 ) ) { $ memcached = new Memcached ( $ name ) ; } else { $ memcached = new Memcached ( ) ; } if ( ! sizeof ( $ memcached -> getServerList ( ) ) ) { $ memcached -> addServers ( $ serverArray ) ; } return new MemcachedStore ( $ memcached , $ prefix ) ; }
create memcached store
131
protected function createRedisStore ( ) { $ serverArray = $ this -> config [ 'servers' ] ; $ persistent = boolval ( $ this -> config [ 'persistent' ] ) ; $ prefix = trim ( $ this -> config [ 'prefix' ] ) ; if ( $ persistent ) { foreach ( $ serverArray as $ k => $ v ) { $ v [ 'persistent' ] = true ; $ serverArray [ $ k ] = $ v ; } } $ redisServer = new RedisServer ( $ serverArray ) ; return new RedisStore ( $ redisServer , $ prefix ) ; }
create redis store
132
public function getStore ( ) { if ( null != $ this -> store ) { return $ this -> store ; } switch ( $ this -> config [ 'driver' ] ) { case "memcached" : $ this -> store = $ this -> createMemcachedStore ( ) ; break ; case "redis" : $ this -> store = $ this -> createRedisStore ( ) ; break ; default : throw new CacheException ( "store [{$this->config['driver']}] not supported." ) ; } return $ this -> store ; }
get cache store
133
public function has ( $ prop ) { $ getter = 'get' . ucfirst ( $ prop ) ; $ return = method_exists ( $ this , $ getter ) ; if ( ! $ return ) { $ is = 'is' . ucfirst ( $ prop ) ; $ return = method_exists ( $ this , $ is ) ; } return $ return ; }
Check to see if this class has a get or is method defined
134
public function AllErrorToException ( ) { if ( ! class_exists ( '\\Middlewares\\Whoops' ) ) return ; set_error_handler ( function ( $ severity , $ message , $ file , $ line ) { if ( ! ( error_reporting ( ) & $ severity ) ) { return ; } throw new \ ErrorException ( $ message , 0 , $ severity , $ file , $ line ) ; } ) ; }
Cette fonction Convertit les erreurs PHP en Exception pour fonctionner avec whoops
135
public function addEntityWithId ( $ entityId ) { $ entity = $ this -> getRepository ( ) -> get ( $ entityId ) ; if ( ! $ entity ) { throw new EntityNotFoundException ( "The entity with is '{$entityId}' was not found." ) ; } return $ this -> addEntity ( $ entity ) ; }
Adds an entity by entity id
136
public function getRepository ( ) { if ( null == $ this -> repository ) { $ this -> setRepository ( Orm :: getRepository ( $ this -> type ) ) ; } return $ this -> repository ; }
Gets entity repository for this collection
137
public function remove ( $ index ) { if ( ! $ index instanceof EntityInterface ) { $ index = $ this -> getRepository ( ) -> get ( $ index ) ; } return $ this -> findAndRemove ( $ index ) ; }
Removes the element at the given index and returns it .
138
protected function findAndRemove ( EntityInterface $ entity = null ) { if ( null == $ entity ) { return $ entity ; } foreach ( $ this -> data as $ key => $ existent ) { if ( $ existent -> getId ( ) == $ entity -> getId ( ) ) { parent :: remove ( $ key ) ; $ this -> getEmitter ( ) -> emit ( new EntityRemoved ( $ entity , [ 'collection' => $ this ] ) ) ; break ; } } return $ entity ; }
Iterates over the collection to remove an entity if found
139
public function setResponse ( Response $ response ) { $ this -> response = $ response ; $ this -> context -> registerInstance ( $ response ) ; }
Sets a new HTTP response object on the application clearing and overriding any previous response data .
140
public function setRouter ( Router $ router ) { $ this -> router = $ router ; $ this -> router -> setContext ( $ this -> context ) ; $ this -> context -> registerInstance ( $ router ) ; }
Sets the router that should be used to handle routing and request resolution duties .
141
protected function beforeStart ( ) { if ( empty ( $ this -> request ) ) { $ this -> setRequest ( Request :: extractFromEnvironment ( ) ) ; } $ this -> bootstrapRouter ( ) ; }
Bootstraps the application state as necessary .
142
public function start ( ) { $ this -> beforeStart ( ) ; $ this -> isBuffering = true ; ob_start ( ) ; $ this -> response = new Response ( ) ; $ this -> context -> registerInstance ( $ this -> response ) ; try { if ( ! $ this -> filters -> trigger ( Filters :: BEFORE_ROUTE , $ this -> context ) ) { return $ this -> response ; } $ routingResult = $ this -> router -> route ( $ this -> request ) ; if ( $ routingResult != null ) { $ this -> context -> registerInstance ( $ routingResult ) ; $ this -> response -> setResponseCode ( ResponseCode :: HTTP_OK ) ; $ returnValue = $ this -> dispatch ( $ routingResult ) ; if ( $ returnValue instanceof Response ) { if ( $ this -> isBuffering ) { ob_clean ( ) ; } $ this -> response = $ returnValue ; } } else { $ anyOptionsAvailable = $ this -> router -> getOptions ( $ this -> request ) ; if ( ! $ anyOptionsAvailable ) { $ this -> prepareNotFoundResponse ( ) ; } else if ( $ this -> request -> getMethod ( ) == RequestMethod :: OPTIONS ) { $ this -> prepareOptionsResponse ( ) ; } else { $ this -> prepareNotAllowedResponse ( ) ; } } $ this -> filters -> trigger ( Filters :: AFTER_ROUTE , $ this -> context ) ; } catch ( \ Exception $ ex ) { $ this -> prepareErrorResponse ( $ ex ) ; } finally { $ this -> sendResponse ( ) ; } return $ this -> response ; }
Based on the current configuration begins handling the incoming request . This function should result in data being output .
143
private function prepareOptionsResponse ( ) { ob_clean ( ) ; $ optionsForRoute = $ this -> router -> getOptions ( $ this -> request ) ; $ methodsAllowed = [ RequestMethod :: OPTIONS ] ; foreach ( $ optionsForRoute as $ route ) { $ acceptableMethods = $ route -> getAcceptableMethods ( ) ; $ methodsAllowed = array_merge_recursive ( $ methodsAllowed , $ acceptableMethods ) ; } array_unique ( $ methodsAllowed ) ; $ this -> response = new Response ( ) ; $ this -> response -> setResponseCode ( ResponseCode :: HTTP_OK ) ; $ this -> response -> setHeader ( 'Allow' , implode ( ',' , $ methodsAllowed ) ) ; $ this -> response -> setBody ( '' ) ; $ this -> context -> registerInstance ( $ this -> response ) ; $ this -> finalizeOutputBuffer ( ) ; }
Cleans the output buffer and builds a default HTTP 200 OK Allow response to an OPTIONS request .
144
private function prepareErrorResponse ( \ Exception $ ex ) { ob_clean ( ) ; $ this -> response = new Response ( ) ; $ this -> response -> setResponseCode ( ResponseCode :: HTTP_INTERNAL_SERVER_ERROR ) ; $ this -> context -> registerInstance ( $ this -> response ) ; $ this -> context -> registerInstance ( $ ex ) ; $ rethrow = false ; $ this -> filters -> trigger ( Filters :: ON_EXCEPTION , $ this -> context ) ; if ( ! $ this -> filters -> anyHandlersForEvent ( Filters :: ON_EXCEPTION ) ) { $ rethrow = true ; } $ this -> finalizeOutputBuffer ( ) ; if ( empty ( $ this -> response -> getBody ( ) ) ) { $ this -> serveStaticPage ( 'error_page' ) ; } if ( $ rethrow ) { throw $ ex ; } }
Cleans the output buffer and builds a default HTTP 500 error page . Invokes the appropriate filter if one is registered ; otherwise falls back to a default message .
145
private function prepareNotFoundResponse ( ) { ob_clean ( ) ; $ this -> response = new Response ( ) ; $ this -> response -> setResponseCode ( ResponseCode :: HTTP_NOT_FOUND ) ; $ this -> context -> registerInstance ( $ this -> response ) ; $ this -> filters -> trigger ( Filters :: NO_ROUTE_FOUND , $ this -> context ) ; $ this -> finalizeOutputBuffer ( ) ; if ( empty ( $ this -> response -> getBody ( ) ) ) { if ( $ this -> router -> isEmpty ( ) ) { $ this -> serveStaticPage ( 'enlighten_welcome' ) ; } else { $ this -> serveStaticPage ( 'not_found' ) ; } } }
Triggers any not found filters and prepares an appropriate 404 error response .
146
private function prepareNotAllowedResponse ( ) { ob_clean ( ) ; $ this -> response = new Response ( ) ; $ this -> response -> setResponseCode ( ResponseCode :: HTTP_METHOD_NOT_ALLOWED ) ; $ this -> context -> registerInstance ( $ this -> response ) ; $ this -> filters -> trigger ( Filters :: METHOD_NOT_ALLOWED , $ this -> context ) ; $ this -> finalizeOutputBuffer ( ) ; if ( empty ( $ this -> response -> getBody ( ) ) ) { $ this -> serveStaticPage ( 'method_not_allowed' ) ; } }
Triggers any not allowed filters and prepares an appropriate 404 error response .
147
private function serveStaticPage ( $ templateFile ) { $ staticFilePath = $ this -> installDirectory . '/static/' . $ templateFile . '.html' ; if ( file_exists ( $ staticFilePath ) ) { $ this -> response -> appendBody ( file_get_contents ( $ staticFilePath ) ) ; } }
Attempts to serve a internal framework static HTML file to the request .
148
private function finalizeOutputBuffer ( ) { if ( $ this -> isBuffering ) { $ this -> response -> appendBody ( ob_get_contents ( ) ) ; $ this -> isBuffering = false ; ob_end_clean ( ) ; } }
Cleans the output buffer if it is active moves its contents to the response and stops output buffering .
149
public function dispatch ( Route $ route ) { $ this -> beforeStart ( ) ; return $ this -> router -> dispatch ( $ route , $ this -> request ) ; }
Dispatches a Route .
150
private function registerRoute ( $ pattern , $ target , array $ requestMethods = [ ] ) { $ this -> bootstrapRouter ( ) ; $ route = new Route ( $ pattern , $ target ) ; if ( ! empty ( $ requestMethods ) ) { $ route -> setAcceptableMethods ( $ requestMethods ) ; } $ this -> router -> register ( $ route ) ; return $ route ; }
Internal function to register a new route . Will bootstrap the router if necessary .
151
public function get ( $ pattern , $ target ) { return $ this -> registerRoute ( $ pattern , $ target , [ RequestMethod :: GET , RequestMethod :: HEAD ] ) ; }
Registers a route for the GET and linked HEAD request methods .
152
public function redirect ( $ from , $ to , $ permanent = false ) { $ this -> bootstrapRouter ( ) ; return $ this -> router -> createRedirect ( $ from , $ to , $ permanent ) ; }
Registers a new redirection route .
153
public static function escapeTrailingBackslash ( $ text ) { if ( '\\' === substr ( $ text , - 1 ) ) { $ len = strlen ( $ text ) ; $ text = rtrim ( $ text , '\\' ) ; $ text .= str_repeat ( '<<' , $ len - strlen ( $ text ) ) ; } return $ text ; }
Escapes trailing \ in given text .
154
public function concerns ( $ names , array $ options = [ ] ) { $ names = ( array ) $ names ; foreach ( $ names as $ name ) { if ( isset ( $ this -> concerns [ $ name ] ) ) { $ this -> concerns [ $ name ] ( $ this , $ options ) ; } else { throw new Exception \ InvalidArgumentException ( sprintf ( "No concern named '%s' was found!" , $ name ) ) ; } } }
Execute one or more concerns .
155
public function orderby ( $ orderBy = null ) : Update { if ( ! \ is_string ( $ orderBy ) && ! \ is_array ( $ orderBy ) ) { throw new InvalidArgumentException ( '$orderBy has to be an array or a string' ) ; } $ this -> orderBy = $ this -> namesClass -> parse ( $ orderBy ) ; return $ this ; }
Adds order by to select
156
public function color ( $ color ) { if ( $ color !== null ) { Checkers :: checkColor ( $ color , null ) ; } $ this -> color = $ color ; return $ this ; }
Valid bootstrap color
157
public function run ( $ pointName , array $ data = [ ] , array $ headers = [ ] ) { $ this -> endpoint = $ this -> api -> getEndpoints ( ) -> findOrFail ( $ pointName ) ; $ client = new Client ( $ this -> api -> getHandler ( ) ) ; $ method = $ this -> endpoint -> getMethod ( ) ; $ uri = $ this -> endpoint -> getUri ( $ data ) ; $ body = $ this -> makeBody ( $ headers , $ data ) ; $ response = $ client -> request ( $ method , $ uri , $ body ) ; return new Response ( $ response , $ this -> endpoint -> getTransformer ( ) ) ; }
call a api endpoint .
158
protected function makeBody ( $ pointHeaders , $ data ) { unset ( $ data [ 'uriData' ] ) ; $ apiHeaders = array_map ( function ( $ value ) { return $ value -> get ( ) ; } , $ this -> api -> getHeaders ( ) -> get ( ) ) ; $ dataChain = $ this -> endpoint -> getMethod ( ) == 'GET' ? 'query' : 'json' ; $ body = array_merge ( $ apiHeaders , $ pointHeaders ) ; $ body [ $ dataChain ] = $ data ; $ request = new Request ( $ body , $ this -> endpoint -> getTransformer ( 'request' ) , $ dataChain ) ; return $ request -> getBody ( $ dataChain ) ; }
make the request body .
159
protected function setDeliverLibs ( $ conf ) { foreach ( $ conf as $ name => $ optName ) { $ options = $ optName ; $ dl = $ name ; if ( ! is_array ( $ optName ) ) { $ dl = $ optName ; $ options = array ( ) ; } $ dl = str_replace ( ' ' , '' , ucwords ( str_replace ( '-' , ' ' , $ dl ) ) ) ; $ service = 'YimaJquery\Deliveries\\' . $ dl ; if ( ! $ this -> serviceManager -> has ( $ service ) ) { trigger_error ( 'Service ' . $ service . ' not found.' , E_USER_WARNING ) ; continue ; } $ service = $ this -> serviceManager -> get ( $ service ) ; $ service -> setOptions ( $ options ) ; $ this -> helper -> addLibDeliver ( $ service ) ; } }
Set Deliverance library service
160
protected function setDecorator ( $ conf ) { $ decoratorClass = null ; if ( is_string ( $ conf ) ) { if ( class_exists ( $ conf ) ) { $ decoratorClass = new $ conf ( ) ; } elseif ( $ this -> serviceManager -> has ( $ conf ) ) { $ decoratorClass = $ this -> serviceManager -> get ( $ conf ) ; } } if ( ! is_object ( $ decoratorClass ) ) { throw new \ Exception ( 'Class or Service ' . $ conf . 'not found.' ) ; } if ( ! $ decoratorClass instanceof AbstractDecorator ) { throw new \ Exception ( sprintf ( 'Decorator class must instance of AbstractDecorator, but %s given.' , get_class ( $ decoratorClass ) ) ) ; } $ this -> helper -> setDecorator ( $ decoratorClass ) ; }
Set Decorator class
161
public function getUserToken ( string $ userName ) : string { if ( isset ( $ this -> userToken [ $ userName ] ) ) { return $ this -> userToken [ $ userName ] ; } }
Returns the user token .
162
public function getQuery ( ) : string { switch ( $ this -> authType ) { case self :: CREDENTIAL : return sprintf ( 'credentialToken=%s' , $ this -> getCredentialToken ( ) ) ; case self :: HANDLER : return sprintf ( 'handlerToken=%s' , $ this -> getHandlerToken ( ) ) ; case self :: IDENTITY : return sprintf ( 'identityToken=%s' , $ this -> getIdentityToken ( ) ) ; } }
Gets the Authorization related to the authType and transforms it to a query parameter .
163
public function isValid ( array $ attributes = [ ] ) { try { if ( ! isset ( $ attributes [ 'validator' ] ) ) { return false ; } $ reflection = new ReflectionClass ( $ attributes [ 'validator' ] ) ; if ( ! $ reflection -> hasMethod ( '__invoke' ) ) { return false ; } if ( ! in_array ( 'Antares\Tester\Contracts\Tester' , $ reflection -> getInterfaceNames ( ) ) ) { return false ; } } catch ( \ Exception $ e ) { Log :: emergency ( $ e ) ; return false ; } return true ; }
validate container attributes
164
protected function checkTableStatus ( string $ table , string $ sql ) : void { $ sql = preg_replace ( "@^\s+@ms" , '' , $ sql ) ; $ requestedColumns = [ ] ; foreach ( preg_split ( "@,\n@m" , $ sql ) as $ reqCol ) { if ( preg_match ( "@^PRIMARY KEY\s*\((.*?)\)@" , $ reqCol , $ pk ) ) { continue ; } preg_match ( "@^[^\s]+@" , $ reqCol , $ name ) ; $ name = $ name [ 0 ] ; $ requestedColumns [ $ name ] = [ 'column_name' => $ name , 'column_default' => null , 'is_nullable' => true , 'column_type' => '' , '_definition' => trim ( $ reqCol ) , ] ; $ reqCol = str_replace ( 'PRIMARY KEY' , '' , $ reqCol ) ; $ reqCol = preg_replace ( "@^$name\s+@" , '' , $ reqCol ) ; if ( strpos ( $ reqCol , 'NOT NULL' ) ) { $ requestedColumns [ $ name ] [ 'is_nullable' ] = false ; $ reqCol = str_replace ( 'NOT NULL' , '' , $ reqCol ) ; } if ( preg_match ( "@DEFAULT\s+(.*?)$@" , $ reqCol , $ default ) ) { $ parsed = preg_replace ( "@(^'|'$)@" , '' , $ default [ 1 ] ) ; $ requestedColumns [ $ name ] [ 'column_default' ] = $ parsed ; $ requestedColumns [ $ name ] [ '_default' ] = $ default [ 1 ] ; $ reqCol = str_replace ( $ default [ 0 ] , '' , $ reqCol ) ; } $ requestedColumns [ $ name ] [ 'column_type' ] = trim ( $ reqCol ) ; } $ this -> columns -> execute ( [ $ this -> loader -> getDatabase ( ) , $ table ] ) ; $ currentColumns = [ ] ; foreach ( $ this -> columns -> fetchAll ( PDO :: FETCH_ASSOC ) as $ column ) { if ( ! isset ( $ requestedColumns [ $ column [ 'column_name' ] ] ) ) { $ this -> addOperation ( "ALTER TABLE $table DROP COLUMN {$column['column_name']};" ) ; } else { $ column [ 'is_nullable' ] = $ column [ 'is_nullable' ] == 'YES' ; $ column [ 'column_type' ] = strtoupper ( $ column [ 'column_type' ] ) ; $ currentColumns [ $ column [ 'column_name' ] ] = $ column ; } } foreach ( $ requestedColumns as $ name => $ col ) { if ( ! isset ( $ currentColumns [ $ name ] ) ) { $ this -> addOperation ( "ALTER TABLE $table ADD COLUMN {$col['_definition']};" ) ; } else { foreach ( $ this -> modifyColumn ( $ table , $ name , $ col , $ currentColumns [ $ name ] ) as $ sql ) { $ this -> addOperation ( $ sql ) ; } } } }
Compare the table status against the requested SQL and generate ALTER statements accordingly .
165
public function index ( ) { $ this -> request -> data ( 'Task' , $ this -> request -> query ) ; $ this -> paginate = array ( 'TaskClient' => array ( 'limit' => Configure :: read ( 'Pagination.limit' ) , 'fields' => array ( 'command' , 'arguments' , 'status' , 'code_string' , 'stderr_truncated' , 'started' , 'stopped' , 'created' , 'modified' , 'runtime' , 'id' , 'process_id' ) , 'conditions' => $ this -> _paginationFilter ( ) , 'order' => array ( 'created' => 'desc' ) , 'contain' => array ( 'DependsOnTask' => array ( 'id' , 'status' ) ) ) ) ; $ this -> set ( array ( 'data' => $ this -> paginate ( "TaskClient" ) ) ) ; $ commandList = $ this -> TaskClient -> find ( 'list' , array ( 'fields' => array ( 'command' , 'command' ) , 'group' => array ( 'command' ) , ) ) ; $ statusList = $ this -> TaskClient -> find ( 'list' , array ( 'fields' => array ( 'status' , 'status' ) , 'group' => array ( 'status' ) , ) ) ; $ approximateRuntimes = array_map ( function ( $ command ) { return $ this -> TaskProfiler -> approximateRuntime ( $ command ) ; } , $ commandList ) ; $ this -> set ( array ( 'commandList' => $ commandList , 'statusList' => $ statusList , 'approximateRuntimes' => $ approximateRuntimes , 'batchActions' => array_combine ( $ this -> batchActions , $ this -> batchActions ) ) ) ; }
View list of tasks
166
public function profile ( ) { $ this -> request -> data ( 'Task' , $ this -> request -> query ) ; $ command = $ this -> request -> query ( 'command' ) ; $ this -> set ( 'data' , $ command ? $ this -> TaskProfiler -> profileCommand ( $ command ) : null ) ; $ this -> set ( array ( 'commandList' => $ this -> TaskClient -> find ( 'list' , array ( 'fields' => array ( 'command' , 'command' ) , 'group' => array ( 'command' ) , ) ) , ) ) ; if ( CakePlugin :: loaded ( 'GoogleChart' ) ) { $ this -> helpers [ ] = 'GoogleChart.GoogleChart' ; } }
Profile task command
167
protected function _paginationFilter ( ) { $ conditions = array_filter ( $ this -> request -> query , function ( $ var ) { return $ var !== '' ; } ) ; unset ( $ conditions [ 'url' ] , $ conditions [ 'batch_conditions' ] , $ conditions [ 'batch_action' ] ) ; foreach ( array ( 'started' , 'created' , 'stopped' , 'modified' ) as $ dateRangeField ) { if ( empty ( $ conditions [ $ dateRangeField ] ) ) { continue ; } if ( preg_match ( '/^(?P<start>.*)\s(-|to)\s(?P<end>.*)$/is' , $ conditions [ $ dateRangeField ] , $ range ) ) { $ conditions [ $ dateRangeField . ' BETWEEN ? AND ?' ] = array ( ( new DateTime ( $ range [ 'start' ] ) ) -> format ( 'Y-m-d H:i:s' ) , ( new DateTime ( $ range [ 'end' ] ) ) -> format ( 'Y-m-d H:i:s' ) ) ; } unset ( $ conditions [ $ dateRangeField ] ) ; } return $ conditions ; }
Builds pagination conditions from search form
168
public function createService ( Di $ di ) { $ required = [ 'views_dir' => null , 'template_500' => null , 'template_404' => null , ] ; $ config = $ di -> get ( 'config' ) [ 'error_handler' ] -> toArray ( ) ; $ errMsg = sprintf ( 'Cannot create error handler "%s"' , __CLASS__ ) ; if ( ! isset ( $ config [ 'options' ] ) ) { throw new InvalidArgumentException ( $ errMsg ) ; } $ options = array_merge ( $ required , $ config [ 'options' ] ) ; if ( empty ( $ options [ 'views_dir' ] ) || empty ( $ options [ 'template_500' ] ) || empty ( $ options [ 'template_404' ] ) || ( $ realPath = realpath ( $ options [ 'views_dir' ] ) ) === false ) { throw new InvalidArgumentException ( $ errMsg ) ; } $ this -> options = $ options ; $ this -> di = $ di ; $ this -> viewsDir = $ realPath ; return $ this ; }
Create error handler service
169
public function Get ( $ ConversationID , $ ViewingUserID , $ Offset = '0' , $ Limit = '' , $ Wheres = '' ) { if ( $ Limit == '' ) $ Limit = Gdn :: Config ( 'Conversations.Messages.PerPage' , 50 ) ; $ Offset = ! is_numeric ( $ Offset ) || $ Offset < 0 ? 0 : $ Offset ; if ( is_array ( $ Wheres ) ) $ this -> SQL -> Where ( $ Wheres ) ; $ this -> FireEvent ( 'BeforeGet' ) ; return $ this -> SQL -> Select ( 'cm.*' ) -> Select ( 'iu.Name' , '' , 'InsertName' ) -> Select ( 'iu.Email' , '' , 'InsertEmail' ) -> Select ( 'iu.Photo' , '' , 'InsertPhoto' ) -> From ( 'ConversationMessage cm' ) -> Join ( 'Conversation c' , 'cm.ConversationID = c.ConversationID' ) -> Join ( 'UserConversation uc' , 'c.ConversationID = uc.ConversationID and uc.UserID = ' . $ ViewingUserID , 'left' ) -> Join ( 'User iu' , 'cm.InsertUserID = iu.UserID' , 'left' ) -> BeginWhereGroup ( ) -> Where ( 'uc.DateCleared is null' ) -> OrWhere ( 'uc.DateCleared <' , 'cm.DateInserted' , TRUE , FALSE ) -> EndWhereGroup ( ) -> Where ( 'cm.ConversationID' , $ ConversationID ) -> OrderBy ( 'cm.DateInserted' , 'asc' ) -> Limit ( $ Limit , $ Offset ) -> Get ( ) ; }
Get messages by conversation .
170
public function GetNew ( $ ConversationID , $ LastMessageID ) { $ Session = Gdn :: Session ( ) ; $ this -> SQL -> Where ( 'MessageID > ' , $ LastMessageID ) ; return $ this -> Get ( $ ConversationID , $ Session -> UserID ) ; }
Get only new messages from conversation .
171
public function GetCount ( $ ConversationID , $ ViewingUserID , $ Wheres = '' ) { if ( is_array ( $ Wheres ) ) $ this -> SQL -> Where ( $ Wheres ) ; $ Data = $ this -> SQL -> Select ( 'cm.MessageID' , 'count' , 'Count' ) -> From ( 'ConversationMessage cm' ) -> Join ( 'Conversation c' , 'cm.ConversationID = c.ConversationID' ) -> Join ( 'UserConversation uc' , 'c.ConversationID = uc.ConversationID and uc.UserID = ' . $ ViewingUserID ) -> BeginWhereGroup ( ) -> Where ( 'uc.DateCleared is null' ) -> OrWhere ( 'uc.DateCleared >' , 'c.DateUpdated' , TRUE , FALSE ) -> EndWhereGroup ( ) -> GroupBy ( 'cm.ConversationID' ) -> Where ( 'cm.ConversationID' , $ ConversationID ) -> Get ( ) ; if ( $ Data -> NumRows ( ) > 0 ) return $ Data -> FirstRow ( ) -> Count ; return 0 ; }
Get number of messages in a conversation .
172
public function GetCountWhere ( $ Wheres = '' ) { if ( is_array ( $ Wheres ) ) $ this -> SQL -> Where ( $ Wheres ) ; $ Data = $ this -> SQL -> Select ( 'MessageID' , 'count' , 'Count' ) -> From ( 'ConversationMessage' ) -> Get ( ) ; if ( $ Data -> NumRows ( ) > 0 ) return $ Data -> FirstRow ( ) -> Count ; return 0 ; }
Get number of messages that meet criteria .
173
private function reset ( ) { $ this -> table = null ; $ this -> tables = null ; $ this -> columns = '*' ; $ this -> values = $ this -> sets = [ ] ; $ this -> where = $ this -> order = $ this -> group = '' ; }
function to clear all properties for the next use .
174
public function first ( $ type = 'object' ) { $ data = self :: query ( $ type ) ; if ( Collection :: count ( $ data ) > 0 ) { return $ data [ 0 ] ; } }
Get first Data returned from query .
175
public function query ( $ type = 'object' ) { $ sql = 'select ' . $ this -> columns . ' from ' . $ this -> getTables ( $ this -> tables ) . ' ' . $ this -> where . ' ' . $ this -> order . ' ' . $ this -> group ; static :: $ sql = static :: $ register [ ] = $ sql ; if ( $ data = Database :: read ( $ sql ) ) { return self :: fetch ( $ data , $ type ) ; } elseif ( Database :: execerr ( ) ) { throw new QueryException ( ) ; } }
get arraay of data .
176
private function getTables ( $ tables ) { $ names = '' ; $ i = 0 ; foreach ( $ tables as $ table ) { $ names .= $ table ; $ i ++ ; if ( count ( $ tables ) > $ i ) { $ names .= ',' ; } } return $ names ; }
Get the tables names as string .
177
public function fetch ( $ array , $ type = 'object' ) { $ data = [ ] ; foreach ( $ array as $ row ) { if ( $ type == 'object' ) { $ rw = new Row ( ) ; foreach ( $ row as $ index => $ column ) { if ( ! is_int ( $ index ) ) { $ rw -> $ index = $ column ; } } } elseif ( $ type == 'array' ) { $ rw = [ ] ; foreach ( $ row as $ index => $ column ) { if ( ! is_int ( $ index ) ) { $ rw [ $ index ] = $ column ; } } } $ data [ ] = $ rw ; } return $ data ; }
Fetch data .
178
public function select ( ) { $ columns = func_get_args ( ) ; $ target = '' ; $ i = false ; foreach ( $ columns as $ column ) { if ( ! $ i ) { $ target .= $ column ; } else { $ target .= ',' . $ column ; } $ i = true ; } $ this -> columns = $ target ; return $ this ; }
Set columns of query .
179
public function where ( $ column = null , $ relation = null , $ value = null , $ link = false ) { if ( is_null ( $ column ) && is_null ( $ relation ) && is_null ( $ value ) ) { $ this -> where = ' where 1 = 1 ' ; } else { if ( ! $ link ) { $ this -> where = " where $column $relation '$value' " ; } else { $ this -> where = " where $column $relation $value " ; } } return $ this ; }
Set where clause .
180
public function link ( $ column1 , $ colmun2 ) { if ( $ this -> where != '' ) { $ this -> where .= " and ( $column1 = $colmun2 ) " ; } else { $ this -> where = " where ( $column1 = $colmun2 ) " ; } return $ this ; }
Set a link between tables .
181
public function orWhere ( $ column , $ relation , $ value , $ link = false ) { if ( ! $ link ) { $ this -> where .= " or ( $column $relation '$value' )" ; } else { $ this -> where .= " or ( $column $relation $value )" ; } return $ this ; }
Set new OR condition in where clause .
182
public function andWhere ( $ column , $ relation , $ value , $ link = false ) { if ( ! $ link ) { $ this -> where .= " and ( $column $relation '$value' )" ; } else { $ this -> where .= " and ( $column $relation $value )" ; } return $ this ; }
Set new AND condition in where clause .
183
private function groupWhere ( $ begin , $ between , $ conditions ) { $ query = ( Strings :: trim ( $ begin ) == 'or' ) ? ' or ( ' : ( Strings :: trim ( $ begin ) == 'and' ) ? ' and ( ' : ' ( ' ; for ( $ i = 1 ; $ i < Collection :: count ( $ conditions ) ; $ i ++ ) { $ query .= $ conditions [ $ i ] ; $ query .= ( $ i < Collection :: count ( $ conditions ) - 1 ) ? " $between " : ' ' ; } $ query .= ' ) ' ; $ this -> where .= $ query ; return $ this ; }
Set new multi condition in where clause .
184
public function orGroup ( ) { $ conditions = func_get_args ( ) ; if ( Collection :: count ( $ conditions ) == 0 ) { throw new ErrorException ( 'Missing arguments for orGroup() ' ) ; } return $ this -> groupWhere ( $ conditions [ 0 ] , 'or' , $ conditions ) ; }
Set new OR for multi condition in where clause .
185
public function andGroup ( ) { $ conditions = func_get_args ( ) ; if ( Collection :: count ( $ conditions ) == 0 ) { throw new ErrorException ( 'Missing arguments for andGroup() ' ) ; } return $ this -> groupWhere ( $ conditions [ 0 ] , 'and' , $ conditions ) ; }
Set new AND for multi condition in where clause .
186
public function order ( ) { $ columns = func_get_args ( ) ; $ order = '' ; $ i = 0 ; if ( $ columns ) { foreach ( $ columns as $ value ) { if ( ! $ i ) { $ order .= ' order by ' . $ value ; } else { $ order .= ',' . $ value ; } $ i = 1 ; } } $ this -> order = $ order ; return $ this ; }
Set the order of data .
187
public function group ( ) { $ columns = func_get_args ( ) ; $ group = '' ; $ i = 0 ; if ( $ columns ) { foreach ( $ columns as $ value ) { if ( ! $ i ) { $ order .= ' group by ' . $ value ; } else { $ order .= ',' . $ value ; } $ i = 1 ; } } $ this -> group = $ group ; return $ this ; }
Set the group of data .
188
public function column ( ) { $ columns = func_get_args ( ) ; if ( Collection :: count ( $ columns ) == 1 && is_array ( $ columns [ 0 ] ) ) { $ columns = $ columns [ 0 ] ; } $ target = '' ; $ i = false ; foreach ( $ columns as $ column ) { if ( ! $ i ) { $ target .= "$column" ; } else { $ target .= ",$column" ; } $ i = true ; } $ this -> columns = $ target ; return $ this ; }
set array of columns .
189
public function value ( ) { $ values = func_get_args ( ) ; if ( Collection :: count ( $ values ) == 1 && is_array ( $ values [ 0 ] ) ) { $ values = $ values [ 0 ] ; } $ target = '' ; $ i = false ; foreach ( $ values as $ value ) { $ value = str_replace ( "'" , "''" , $ value ) ; if ( ! $ i ) { $ target .= "'$value'" ; } else { $ target .= ",'$value'" ; } $ i = true ; } $ this -> values = $ target ; return $ this ; }
set array of values .
190
public function insert ( ) { $ query = 'insert into ' . $ this -> getTables ( $ this -> tables ) . ' (' . $ this -> columns . ') values (' . $ this -> values . ')' ; $ this -> reset ( ) ; return Database :: exec ( $ query ) ; }
execute insert query .
191
public function set ( $ column , $ value , $ quote = true ) { $ value = str_replace ( "'" , "''" , $ value ) ; $ this -> sets [ ] = $ quote ? " $column = '$value'" : " $column = $value" ; return $ this ; }
function to set elemets to update .
192
public function update ( ) { $ query = 'update ' . $ this -> getTables ( $ this -> tables ) . ' set ' ; for ( $ i = 0 ; $ i < Collection :: count ( $ this -> sets ) ; $ i ++ ) { if ( $ i < Collection :: count ( $ this -> sets ) - 1 ) { $ query .= $ this -> sets [ $ i ] . ',' ; } else { $ query .= $ this -> sets [ $ i ] ; } } $ query .= ' ' . $ this -> where ; $ this -> reset ( ) ; return Database :: exec ( $ query ) ; }
execute update query .
193
public function delete ( ) { $ query = 'delete from ' . $ this -> getTables ( $ this -> tables ) . ' ' ; $ query .= ' ' . $ this -> where ; $ this -> reset ( ) ; return Database :: exec ( $ query ) ; }
delete row from data table .
194
public function innerHtml ( ) { if ( ! $ this -> hasChildren ( ) ) { return '' ; } if ( ! is_null ( $ this -> innerHtml ) ) { return $ this -> innerHtml ; } $ child = $ this -> firstChild ( ) ; $ string = '' ; while ( ! is_null ( $ child ) ) { if ( $ child instanceof TextNode ) { $ string .= $ child -> text ( ) ; } elseif ( $ child instanceof HtmlNode ) { $ string .= $ child -> outerHtml ( ) ; } else { throw new UnknownChildTypeException ( 'Unknown child type "' . get_class ( $ child ) . '" found in node' ) ; } try { $ child = $ this -> nextChild ( $ child -> id ( ) ) ; } catch ( ChildNotFoundException $ e ) { $ child = null ; } } $ this -> innerHtml = $ string ; return $ string ; }
Gets the inner html of this node .
195
public function outerHtml ( ) { if ( $ this -> tag -> name ( ) == 'root' ) { return $ this -> innerHtml ( ) ; } if ( ! is_null ( $ this -> outerHtml ) ) { return $ this -> outerHtml ; } $ return = $ this -> tag -> makeOpeningTag ( ) ; if ( $ this -> tag -> isSelfClosing ( ) ) { return $ return ; } $ return .= $ this -> innerHtml ( ) ; $ return .= $ this -> tag -> makeClosingTag ( ) ; $ this -> outerHtml = $ return ; return $ return ; }
Gets the html of this node including it s own tag .
196
public static function typed ( string $ type , iterable $ input = [ ] ) : Map { $ resolver = Resolver :: typed ( $ type ) ; return new static ( $ input , $ resolver ) ; }
Map named constructor .
197
private function setupRegisteredModules ( $ modules , $ paths ) { if ( empty ( $ modules ) || empty ( $ paths ) ) { throw new Exception \ InvalidArgumentException ( 'Invalid parameters for init phalcon extesion' ) ; } foreach ( $ modules as $ moduleName ) { $ found = false ; foreach ( $ paths as $ path ) { $ modulePath = $ path . DIRECTORY_SEPARATOR . $ moduleName . DIRECTORY_SEPARATOR . 'Module.php' ; if ( file_exists ( $ modulePath ) ) { $ found = true ; $ this -> modules [ $ moduleName ] = [ 'className' => $ moduleName . '\\Module' , 'path' => $ modulePath , ] ; break ; } } if ( ! $ found ) { throw new Exception \ RuntimeException ( sprintf ( 'Not found module "%s"' , $ moduleName ) ) ; } } }
Setup array registered modules when without cache or cache is missed
198
protected function filterModuleConfig ( $ moduleConfig , $ moduleName ) { if ( ! ArrayUtils :: isHashTable ( $ moduleConfig , true ) ) { $ errMsg = sprintf ( 'The configuration for module "%s" is invalid' , $ moduleName ) ; throw new Exception \ RuntimeException ( $ errMsg ) ; } if ( isset ( $ moduleConfig [ 'view' ] ) ) { $ realPathView = realpath ( $ moduleConfig [ 'view' ] [ $ moduleName ] ) ; if ( ! $ realPathView ) { $ errMsg = sprintf ( 'The view path for module "%s" is invalid' , $ moduleName ) ; throw new Exception \ RuntimeException ( $ errMsg ) ; } $ moduleConfig [ 'view' ] [ $ moduleName ] = $ realPathView ; } if ( isset ( $ moduleConfig [ 'volt' ] ) && isset ( $ moduleConfig [ 'volt' ] [ $ moduleName ] [ 'path' ] ) ) { $ path = realpath ( $ moduleConfig [ 'volt' ] [ $ moduleName ] [ 'path' ] ) ; unset ( $ moduleConfig [ 'volt' ] [ $ moduleName ] [ 'path' ] ) ; if ( $ path ) { $ moduleConfig [ 'volt' ] [ $ moduleName ] [ 'path' ] = $ path ; } } return $ moduleConfig ; }
Filter module s configurations
199
protected function getModulesAutoloadConfigWithoutCache ( ) { $ result = [ ] ; foreach ( $ this -> modules as $ moduleName => $ moduleConfig ) { $ className = $ moduleConfig [ 'className' ] ; $ module = new $ className ; if ( ! $ module instanceof AbstractModule ) { $ errMsg = sprintf ( 'Class "%s" must be extended from %s' , $ className , AbstractModule :: class ) ; throw new Exception \ RuntimeException ( $ errMsg ) ; } $ autoloadConfig = $ module -> getAutoloaderConfig ( ) ; if ( ! ArrayUtils :: isHashTable ( $ autoloadConfig ) ) { $ errMsg = sprintf ( 'The autoloader configuration for module "%s" is invalid' , $ moduleName ) ; throw new Exception \ RuntimeException ( $ errMsg ) ; } $ result = ArrayUtils :: merge ( $ result , $ autoloadConfig ) ; } foreach ( $ result as $ moduleName => $ configAutoload ) { foreach ( $ configAutoload as $ key => $ value ) { $ result [ $ moduleName ] [ $ key ] = realpath ( $ value ) ; } } return $ result ; }
Get autoload config in each module without cache