idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
60,100
public function getDeferred ( $ url , $ responseElement = "" , $ params = "{}" , $ jsCallback = NULL , $ attr = "id" ) { return $ this -> js -> _get ( $ url , $ params , $ responseElement , $ jsCallback , $ attr , false ) ; }
Prepares a Get ajax request To use on an event
60,101
protected function addError ( $ name , $ customMessage = null ) { $ this -> errors [ $ name ] = $ customMessage ? : $ this -> message ? : $ this -> { $ name . 'Message' } ; }
Adds error definition
60,102
protected function isString ( $ input ) { return is_scalar ( $ input ) || is_null ( $ input ) || ( is_object ( $ input ) && method_exists ( $ input , '__toString' ) ) ; }
Checks if the input value could be convert to string
60,103
protected function reset ( ) { $ this -> errors = array ( ) ; if ( count ( $ this -> store ) >= 2 ) { $ last = end ( $ this -> store ) ; foreach ( $ this -> backup as $ name => $ value ) { if ( ! array_key_exists ( $ name , $ last ) ) { $ this -> $ name = $ value ; } } array_shift ( $ this -> store ) ; } $ this -> store [ ] = array ( ) ; }
Reset validator status
60,104
protected function connect ( ) { if ( ! $ this -> object ) { $ this -> object = new \ Memcache ; } foreach ( $ this -> servers as $ server ) { call_user_func_array ( array ( $ this -> object , 'addServer' ) , $ server ) ; } }
Instance memcache object and connect to server
60,105
protected function checkToken ( ) { $ query = $ this -> query ; $ signature = $ this -> sign ( $ this -> token , isset ( $ query [ 'timestamp' ] ) ? $ query [ 'timestamp' ] : '' , isset ( $ query [ 'nonce' ] ) ? $ query [ 'nonce' ] : '' ) ; return isset ( $ query [ 'signature' ] ) && $ signature === $ query [ 'signature' ] ; }
Check if the WeChat server signature is valid
60,106
public function run ( ) { if ( $ this -> parseRet [ 'code' ] !== 1 ) { return false ; } if ( isset ( $ this -> query [ 'echostr' ] ) ) { return htmlspecialchars ( $ this -> query [ 'echostr' ] , ENT_QUOTES , 'UTF-8' ) ; } $ msg = $ this -> handleMsg ( ) ; if ( ! $ msg ) { return 'success' ; } return $ this -> isEncrypted ( ) ? $ this -> encryptMsg ( $ msg ) : $ msg ; }
Execute the matched rule and returns the rule result
60,107
protected function handleMsg ( ) { switch ( $ this -> getMsgType ( ) ) { case 'text' : if ( $ result = $ this -> handleText ( ) ) { return $ result ; } break ; case 'event' : case 'device_event' : $ event = strtolower ( $ this -> getEvent ( ) ) ; switch ( $ event ) { case 'subscribe' : $ result = $ this -> handleEvent ( 'subscribe' ) ; $ scanResult = null ; if ( $ this -> getTicket ( ) ) { $ scanResult = $ this -> handleEvent ( 'scan' ) ; } if ( $ result ) { return $ result ; } if ( $ scanResult ) { return $ scanResult ; } break ; case 'scan' : if ( $ result = $ this -> handleEvent ( 'scan' ) ) { return $ result ; } break ; default : if ( $ result = $ this -> handleEvent ( $ event , $ this -> getEventKey ( ) ) ) { return $ result ; } break ; } break ; default : if ( isset ( $ this -> rules [ $ this -> getMsgType ( ) ] ) ) { return $ this -> handle ( $ this -> rules [ $ this -> getMsgType ( ) ] ) ; } } if ( isset ( $ this -> rules [ 'transferCustomer' ] ) ) { return $ this -> handle ( $ this -> rules [ 'transferCustomer' ] ) ; } if ( ! $ this -> handled && $ this -> defaults ) { return $ this -> handle ( $ this -> defaults ) ; } return false ; }
Executes the matched rule and returns the rule result
60,108
public function on ( $ name , $ key , Closure $ fn = null ) { $ name = strtolower ( $ name ) ; if ( $ key instanceof Closure ) { $ this -> rules [ 'event' ] [ $ name ] [ '' ] = $ key ; } else { $ this -> rules [ 'event' ] [ $ name ] [ $ key ] = $ fn ; } return $ this ; }
Adds a rule to handle user event such as click subscribe
60,109
public function sendMusic ( $ title , $ description , $ url , $ hqUrl = null ) { return $ this -> send ( 'music' , array ( 'Music' => array ( 'Title' => $ title , 'Description' => $ description , 'MusicUrl' => $ url , 'HQMusicUrl' => $ hqUrl , ) , ) ) ; }
Generate music message for output
60,110
public function sendArticle ( array $ articles ) { if ( ! is_int ( key ( $ articles ) ) ) { $ articles = array ( $ articles ) ; } $ response = array ( 'ArticleCount' => count ( $ articles ) , 'Articles' => array ( 'item' => array ( ) , ) , ) ; foreach ( $ articles as $ article ) { $ article += array ( 'title' => null , 'description' => null , 'picUrl' => null , 'url' => null , ) ; $ response [ 'Articles' ] [ 'item' ] [ ] = array ( 'Title' => $ article [ 'title' ] , 'Description' => $ article [ 'description' ] , 'PicUrl' => $ article [ 'picUrl' ] , 'Url' => $ article [ 'url' ] , ) ; } return $ this -> send ( 'news' , $ response ) ; }
Generate article message for output
60,111
public function getAttr ( $ name ) { return isset ( $ this -> attrs [ $ name ] ) ? $ this -> attrs [ $ name ] : null ; }
Returns the XML element value
60,112
public function getScanSceneId ( ) { $ eventKey = $ this -> getEventKey ( ) ; if ( strpos ( $ eventKey , 'qrscene_' ) === 0 ) { $ eventKey = substr ( $ eventKey , 8 ) ; } return $ eventKey ; }
Returns the scene id from the scan result available when the message event is subscribe or scan
60,113
public function getKeyword ( ) { if ( $ this -> getMsgType ( ) == 'text' ) { return strtolower ( $ this -> getContent ( ) ) ; } elseif ( $ this -> getMsgType ( ) == 'event' && strtolower ( $ this -> getEvent ( ) ) == 'click' ) { return strtolower ( $ this -> getEventKey ( ) ) ; } return false ; }
Returns the user inputted content or clicked button value
60,114
public function send ( $ type , array $ response ) { return $ response + array ( 'ToUserName' => $ this -> getFromUserName ( ) , 'FromUserName' => $ this -> getToUserName ( ) , 'MsgType' => $ type , 'CreateTime' => time ( ) , ) ; }
Generate message for output
60,115
protected function addTextRule ( $ type , $ keyword , Closure $ fn ) { $ this -> rules [ 'text' ] [ ] = array ( 'type' => $ type , 'keyword' => $ keyword , 'fn' => $ fn , ) ; return $ this ; }
Adds a rule to handle user text input
60,116
protected function handleText ( ) { $ content = $ this -> getContent ( ) ; foreach ( $ this -> rules [ 'text' ] as $ rule ) { if ( $ rule [ 'type' ] == 'is' && 0 === strcasecmp ( $ content , $ rule [ 'keyword' ] ) ) { return $ this -> handle ( $ rule [ 'fn' ] ) ; } if ( $ rule [ 'type' ] == 'has' && false !== mb_stripos ( $ content , $ rule [ 'keyword' ] ) ) { return $ this -> handle ( $ rule [ 'fn' ] ) ; } if ( $ rule [ 'type' ] == 'startsWith' && 0 === mb_stripos ( $ content , $ rule [ 'keyword' ] ) ) { return $ this -> handle ( $ rule [ 'fn' ] ) ; } if ( $ rule [ 'type' ] == 'match' && preg_match ( $ rule [ 'keyword' ] , $ content ) ) { return $ this -> handle ( $ rule [ 'fn' ] ) ; } } return false ; }
Handle text rule
60,117
protected function handle ( $ fn ) { $ this -> handled = true ; $ content = $ fn ( $ this , $ this -> wei ) ? : '' ; if ( $ content && ! is_array ( $ content ) ) { $ content = $ this -> sendText ( $ content ) ; } $ this -> beforeSend && call_user_func_array ( $ this -> beforeSend , array ( $ this , & $ content , $ this -> wei ) ) ; return $ content ? $ this -> arrayToXml ( $ content ) -> asXML ( ) : '' ; }
Executes callback handler
60,118
protected function arrayToXml ( array $ array , SimpleXMLElement $ xml = null ) { if ( $ xml === null ) { $ xml = new SimpleXMLElement ( '<xml/>' ) ; } foreach ( $ array as $ key => $ value ) { if ( is_array ( $ value ) ) { if ( isset ( $ value [ 0 ] ) ) { foreach ( $ value as $ subValue ) { $ subNode = $ xml -> addChild ( $ key ) ; $ this -> arrayToXml ( $ subValue , $ subNode ) ; } } else { $ subNode = $ xml -> addChild ( $ key ) ; $ this -> arrayToXml ( $ value , $ subNode ) ; } } else { if ( is_numeric ( $ value ) ) { $ xml -> addChild ( $ key , $ value ) ; } else { $ child = $ xml -> addChild ( $ key ) ; $ node = dom_import_simplexml ( $ child ) ; $ node -> appendChild ( $ node -> ownerDocument -> createCDATASection ( $ value ) ) ; } } } return $ xml ; }
Convert to XML element
60,119
protected function xmlToArray ( $ xml ) { $ useErrors = libxml_use_internal_errors ( true ) ; $ array = simplexml_load_string ( $ xml , 'SimpleXMLElement' , LIBXML_NOCDATA ) ; libxml_use_internal_errors ( $ useErrors ) ; return array_map ( 'strval' , ( array ) $ array ) ; }
Convert XML string to array
60,120
public static function fromValue ( $ just , $ nothing = null ) : self { return $ just !== $ nothing ? self :: just ( $ just ) : self :: nothing ( ) ; }
fromValue method .
60,121
public function setCost ( $ cost ) { if ( $ cost < 4 || $ cost > 31 ) { throw new \ InvalidArgumentException ( sprintf ( "Invalid bcrypt cost parameter specified: %s" , $ cost ) ) ; } $ this -> cost = $ cost ; return $ this ; }
Set the cost parameter for bcrypt
60,122
public function generateSalt ( ) { $ raw_salt_len = 16 ; $ required_salt_len = 22 ; $ buffer = function_exists ( 'random_bytes' ) ? random_bytes ( $ raw_salt_len ) : mcrypt_create_iv ( $ raw_salt_len , MCRYPT_DEV_URANDOM ) ; $ salt = str_replace ( '+' , '.' , base64_encode ( $ buffer ) ) ; $ salt = substr ( $ salt , 0 , $ required_salt_len ) ; return $ salt ; }
Generate a 22 bytes salt string
60,123
public function list ( $ entityCode , $ entityId , $ param = null ) { $ entityCode = strtolower ( $ entityCode ) ; $ uriAppend = "{$entityCode}/{$entityId}" ; $ params = $ this -> getQueryParams ( ) ; $ response = $ this -> handler -> handle ( 'GET' , false , $ uriAppend , $ params ) ; return $ this -> make ( $ response ) ; }
Get list factor values for current entity
60,124
public function set ( $ entityToCode , $ entityId , array $ factorValueIds ) { $ uriAppend = 'set' ; $ params = array_merge ( $ this -> getQueryParams ( ) , [ 'entityToCode' => $ entityToCode , 'entityId' => $ entityId , 'factorValueIds' => implode ( ',' , $ factorValueIds ) ] ) ; $ response = $ this -> handler -> handle ( 'POST' , $ params , $ uriAppend ) ; return $ this -> make ( $ response ) ; }
Set factor value for current entity
60,125
public function forISBN ( $ isbn ) { if ( ! $ this -> isValidISBN ( $ isbn ) ) { throw new InvalidArgumentException ( 'ISBN is not valid. Got: ' . $ isbn ) ; } $ response = $ this -> client -> request ( 'GET' , 'volumes' , [ 'query' => [ 'q' => 'isbn:' . $ isbn ] , 'http_errors' => false , ] ) ; $ status = $ response -> getStatusCode ( ) ; if ( $ status != 200 ) { throw new InvalidResponseException ( 'Invalid response. Status: ' . $ status . '. Body: ' . $ response -> getBody ( ) ) ; } $ res = json_decode ( $ response -> getBody ( ) , true ) ; $ totalItems = intval ( $ res [ 'totalItems' ] ) ; if ( $ totalItems != 1 ) { throw new InvalidResponseException ( 'Did not get 1 result. Got: ' . $ totalItems ) ; } return $ this -> extractBook ( $ res ) ; }
Retrieve information about a book given its ISBN .
60,126
private function parseDate ( $ rawDate ) { foreach ( [ 'Y-m-d' , 'Y-m' , 'Y' ] as $ dateFormat ) { $ publishedDate = DateTime :: createFromFormat ( $ dateFormat . '|' , $ rawDate ) ; if ( $ publishedDate !== false ) { break ; } } if ( $ publishedDate === false ) { $ publishedDate = null ; } return [ $ publishedDate , $ dateFormat ] ; }
Parse the publication date .
60,127
public function large ( $ email , $ default = null , $ rating = null ) { return $ this -> __invoke ( $ email , $ this -> largeSize , $ default , $ rating ) ; }
Generate a large size Gravatar URL for a specified email address
60,128
public function small ( $ email , $ default = null , $ rating = null ) { return $ this -> __invoke ( $ email , $ this -> smallSize , $ default , $ rating ) ; }
Generate a small size Gravatar URL for a specified email address
60,129
public function connect ( ) { if ( $ this -> object ) { return true ; } $ this -> object = new \ Redis ; $ connect = $ this -> persistent ? 'pconnect' : 'connect' ; $ result = $ this -> object -> $ connect ( $ this -> host , $ this -> port , $ this -> timeout ) ; if ( $ result && $ this -> auth ) { $ result = $ this -> object -> auth ( $ this -> auth ) ; } if ( $ result ) { foreach ( $ this -> options as $ key => $ value ) { $ this -> object -> setOption ( $ key , $ value ) ; } } return $ result ; }
Connect the redis server and set redis options
60,130
public function applyCoupon ( $ basketId , string $ couponCode ) { $ params = [ "basketId" => $ basketId , "couponCode" => $ couponCode , ] ; $ response = $ this -> handler -> handle ( 'POST' , $ params , 'apply' ) ; return $ response ; }
Apply coupon code to basket
60,131
public function cancelCoupon ( $ basketId , string $ couponCode , $ userId ) { $ params = [ "basketId" => $ basketId , "couponCode" => $ couponCode , "userId" => $ userId ] ; $ response = $ this -> handler -> handle ( 'POST' , $ params , 'discard' ) ; return $ response ; }
Discard coupon code for basket
60,132
public function ret ( $ message , $ code = 1 , $ type = 'success' ) { return $ this -> ret -> __invoke ( $ message , $ code , $ type ) ; }
Return operation result data
60,133
public function err ( $ message , $ code = - 1 , $ level = 'info' ) { return $ this -> ret -> err ( $ message , $ code , $ level ) ; }
Return operation failed result and logs with an info level
60,134
public function connect ( ) { if ( $ this -> isConnected ) { return false ; } if ( ! $ this -> pdo ) { $ this -> beforeConnect && call_user_func ( $ this -> beforeConnect , $ this ) ; $ dsn = $ this -> getDsn ( ) ; $ attrs = $ this -> attrs + array ( PDO :: ATTR_ERRMODE => PDO :: ERRMODE_EXCEPTION , PDO :: ATTR_STRINGIFY_FETCHES => true , PDO :: ATTR_DEFAULT_FETCH_MODE => PDO :: FETCH_ASSOC ) ; try { $ this -> pdo = new PDO ( $ dsn , $ this -> user , $ this -> password , $ attrs ) ; } catch ( \ PDOException $ e ) { $ this -> connectFails && call_user_func ( $ this -> connectFails , $ this , $ e ) ; throw $ e ; } $ this -> afterConnect && call_user_func ( $ this -> afterConnect , $ this , $ this -> pdo ) ; } $ this -> isConnected = true ; return true ; }
Connect to the database server
60,135
public function insert ( $ table , array $ data ) { $ table = $ this -> getTable ( $ table ) ; $ field = implode ( ', ' , array_keys ( $ data ) ) ; $ placeholder = array ( ) ; foreach ( $ data as $ key => $ value ) { if ( $ value instanceof \ stdClass && isset ( $ value -> scalar ) ) { $ placeholder [ ] = $ value -> scalar ; unset ( $ data [ $ key ] ) ; } else { $ placeholder [ ] = '?' ; } } $ placeholder = implode ( ', ' , $ placeholder ) ; $ query = "INSERT INTO $table ($field) VALUES ($placeholder)" ; return $ this -> executeUpdate ( $ query , array_values ( $ data ) ) ; }
Executes an INSERT query to insert specified data into table
60,136
public function batchInsert ( $ table , array $ data , $ extra = null ) { $ table = $ this -> getTable ( $ table ) ; $ field = implode ( ', ' , array_keys ( $ data [ 0 ] ) ) ; $ placeholders = array ( ) ; $ values = array ( ) ; switch ( $ this -> driver ) { default : case 'mysql' : case 'pgsql' : foreach ( $ data as $ row ) { $ placeholders [ ] = '(' . implode ( ', ' , array_pad ( array ( ) , count ( $ row ) , '?' ) ) . ')' ; $ values = array_merge ( $ values , array_values ( $ row ) ) ; } $ placeholder = 'VALUES ' . implode ( ', ' , $ placeholders ) ; break ; case 'sqlite' : foreach ( $ data as $ row ) { $ placeholders [ ] = 'SELECT ' . implode ( ', ' , array_pad ( array ( ) , count ( $ row ) , '?' ) ) ; $ values = array_merge ( $ values , array_values ( $ row ) ) ; } $ placeholder = implode ( ' UNION ' , $ placeholders ) ; break ; } $ query = "INSERT INTO $table ($field) $placeholder" ; $ extra && $ query .= ' ' . $ extra ; return $ this -> executeUpdate ( $ query , $ values ) ; }
Insert batch data into table
60,137
public function update ( $ table , array $ data , array $ conditions ) { $ table = $ this -> getTable ( $ table ) ; $ set = $ this -> buildSqlObject ( $ data , ', ' ) ; $ where = $ this -> buildSqlObject ( $ conditions , ' AND ' ) ; $ query = "UPDATE $table SET $set WHERE $where" ; $ params = array_merge ( array_values ( $ data ) , array_values ( $ conditions ) ) ; return $ this -> executeUpdate ( $ query , $ params ) ; }
Executes a UPDATE query
60,138
public function delete ( $ table , array $ conditions ) { $ table = $ this -> getTable ( $ table ) ; $ where = $ this -> buildSqlObject ( $ conditions , ' AND ' ) ; $ query = "DELETE FROM $table WHERE " . $ where ; return $ this -> executeUpdate ( $ query , array_values ( $ conditions ) ) ; }
Executes a DELETE query
60,139
public function select ( $ table , $ conditions , $ select = '*' ) { $ data = $ this -> selectAll ( $ table , $ conditions , $ select , 1 ) ; return $ data ? $ data [ 0 ] : false ; }
Executes a SELECT query and return the first result
60,140
public function selectAll ( $ table , $ conditions = false , $ select = '*' , $ limit = null ) { $ params = array ( ) ; $ query = "SELECT $select FROM " . $ this -> getTable ( $ table ) . ' ' ; if ( is_array ( $ conditions ) ) { if ( ! empty ( $ conditions ) ) { $ query .= "WHERE " . implode ( ' = ? AND ' , array_keys ( $ conditions ) ) . ' = ?' ; $ params = array_values ( $ conditions ) ; } } elseif ( $ conditions !== false ) { $ query .= "WHERE id = :id" ; $ params = array ( 'id' => $ conditions ) ; } if ( $ limit ) { $ query .= " LIMIT $limit" ; } return $ this -> query ( $ query , $ params ) -> fetchAll ( ) ; }
Executes a SELECT query and return all results
60,141
public function fetch ( $ sql , $ params = array ( ) , $ types = array ( ) ) { return $ this -> query ( $ sql , $ params , $ types ) -> fetch ( ) ; }
Executes a query and returns the first array result
60,142
public function fetchAll ( $ sql , $ params = array ( ) , $ types = array ( ) ) { return $ this -> query ( $ sql , $ params , $ types ) -> fetchAll ( ) ; }
Executes a query and returns all array results
60,143
public function fetchColumn ( $ sql , $ params = array ( ) , $ column = 0 ) { return $ this -> query ( $ sql , $ params ) -> fetchColumn ( $ column ) ; }
Executes a query and returns a column value of the first row
60,144
public function query ( $ sql , $ params = array ( ) , $ types = array ( ) , $ returnRows = false ) { if ( ! $ returnRows && $ this -> slaveDb ) { $ slaveDb = $ this -> wei -> get ( $ this -> slaveDb ) ; return $ slaveDb -> query ( $ sql , $ params , $ types , $ returnRows ) ; } $ this -> connect ( ) ; $ this -> queries [ ] = $ sql ; if ( $ this -> beforeQuery ) { call_user_func_array ( $ this -> beforeQuery , array ( $ sql , $ params , $ types , $ this ) ) ; } try { if ( ! $ returnRows ) { if ( $ params ) { $ stmt = $ this -> pdo -> prepare ( $ sql ) ; if ( $ types ) { $ this -> bindParameter ( $ stmt , $ params , $ types ) ; $ stmt -> execute ( ) ; } else { $ stmt -> execute ( ( array ) $ params ) ; } } else { $ stmt = $ this -> pdo -> query ( $ sql ) ; } $ result = $ stmt ; } else { if ( $ params ) { $ stmt = $ this -> pdo -> prepare ( $ sql ) ; $ stmt -> execute ( $ params ) ; $ result = $ stmt -> rowCount ( ) ; } else { $ result = $ this -> pdo -> exec ( $ sql ) ; } } } catch ( \ PDOException $ e ) { $ msg = sprintf ( "An exception occurred while executing \"%s\" : \n\n %s" , $ sql , $ e -> getMessage ( ) ) ; $ params && $ msg .= ', with parameters ' . json_encode ( $ params ) ; $ message = new \ ReflectionProperty ( $ e , 'message' ) ; $ message -> setAccessible ( true ) ; $ message -> setValue ( $ e , $ msg ) ; throw $ e ; } if ( $ this -> afterQuery ) { call_user_func_array ( $ this -> afterQuery , array ( $ sql , $ params , $ types , $ this ) ) ; } return $ result ; }
Executes an SQL statement returning a PDOStatement object or the number of affected rows
60,145
public function sum ( $ table , $ field , $ conditions = false ) { return $ this -> executeAggregate ( 'SUM' , $ table , $ field , $ conditions ) ; }
Returns the sum of specified table field and conditions
60,146
public function max ( $ table , $ field , $ conditions = false ) { return $ this -> executeAggregate ( 'MAX' , $ table , $ field , $ conditions ) ; }
Returns the max value of specified table field and conditions
60,147
public function min ( $ table , $ field , $ conditions = false ) { return $ this -> executeAggregate ( 'MIN' , $ table , $ field , $ conditions ) ; }
Returns the min value of specified table field and conditions
60,148
public function avg ( $ table , $ field , $ conditions = false ) { return $ this -> executeAggregate ( 'AVG' , $ table , $ field , $ conditions ) ; }
Returns the avg value of specified table field and conditions
60,149
public function init ( $ table , $ data = array ( ) , $ isNew = true ) { $ class = $ this -> getRecordClass ( $ table ) ; return new $ class ( array ( 'wei' => $ this -> wei , 'db' => $ this , 'table' => $ table , 'isNew' => $ isNew , 'data' => $ data , ) ) ; }
Init a record instance
60,150
public function find ( $ table , $ id ) { $ data = $ this -> select ( $ table , $ id ) ; return $ data ? $ this -> init ( $ table , $ data , false ) : false ; }
Find a record from specified table and conditions
60,151
public function findOrInit ( $ table , $ id , $ data = array ( ) ) { return $ this -> init ( $ table ) -> findOrInit ( $ id , $ data ) ; }
Find a record if not found create a new one from specified data
60,152
public function getRecordClass ( $ table ) { if ( isset ( $ this -> recordClasses [ $ table ] ) ) { return $ this -> recordClasses [ $ table ] ; } if ( $ this -> recordNamespace ) { $ class = $ this -> recordNamespace . '\\' . implode ( '' , array_map ( 'ucfirst' , explode ( '_' , $ table ) ) ) ; if ( class_exists ( $ class ) ) { return $ class ; } } return $ this -> recordClass ; }
Returns the record class name of table
60,153
public function getDsn ( ) { if ( $ this -> dsn ) { return $ this -> dsn ; } $ dsn = $ this -> driver . ':' ; switch ( $ this -> driver ) { case 'mysql' : $ this -> host && $ dsn .= 'host=' . $ this -> host . ';' ; $ this -> port && $ dsn .= 'port=' . $ this -> port . ';' ; $ this -> dbname && $ dsn .= 'dbname=' . $ this -> dbname . ';' ; $ this -> unixSocket && $ dsn .= 'unix_socket=' . $ this -> unixSocket . ';' ; $ this -> charset && $ dsn .= 'charset=' . $ this -> charset ; break ; case 'sqlite' : $ dsn .= $ this -> path ; break ; case 'pgsql' : $ this -> host && $ dsn .= 'host=' . $ this -> host . ';' ; $ this -> port && $ dsn .= 'port=' . $ this -> port . ';' ; $ this -> dbname && $ dsn .= 'dbname=' . $ this -> dbname ; break ; default : throw new \ RuntimeException ( sprintf ( 'Unsupported database driver: %s' , $ this -> driver ) ) ; } return $ this -> dsn = $ dsn ; }
Returns the PDO DSN
60,154
public function getTableFields ( $ table , $ withPrefix = false ) { $ fullTable = $ withPrefix ? $ table : $ this -> getTable ( $ table ) ; if ( isset ( $ this -> tableFields [ $ fullTable ] ) ) { return $ this -> tableFields [ $ fullTable ] ; } else { $ fields = array ( ) ; switch ( $ this -> driver ) { case 'mysql' : $ tableInfo = $ this -> fetchAll ( "SHOW COLUMNS FROM $fullTable" ) ; $ fields = $ this -> filter ( $ tableInfo , 'Field' ) ; break ; case 'sqlite' : $ tableInfo = $ this -> fetchAll ( "PRAGMA table_info($fullTable)" ) ; $ fields = $ this -> filter ( $ tableInfo , 'name' ) ; break ; case 'pgsql' : $ tableInfo = $ this -> fetchAll ( "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_catalog = ? AND table_name = ? ORDER BY dtd_identifier ASC" , array ( $ this -> dbname , $ fullTable ) ) ; $ fields = $ this -> filter ( $ tableInfo , 'column_name' ) ; } if ( empty ( $ fields ) ) { throw new \ PDOException ( sprintf ( 'Table or view "%s" not found' , $ fullTable ) ) ; } return $ this -> tableFields [ $ table ] = $ fields ; } }
Returns the name of fields of specified table
60,155
protected function bindParameter ( \ PDOStatement $ stmt , $ params , $ types ) { ! is_array ( $ params ) && $ params = array ( $ params ) ; ! is_array ( $ types ) && $ types = array ( $ types ) ; $ isIndex = is_int ( key ( $ params ) ) ; $ index = 1 ; foreach ( $ params as $ name => $ param ) { if ( $ isIndex ) { if ( isset ( $ types [ $ index - 1 ] ) ) { $ stmt -> bindValue ( $ index , $ param , $ types [ $ index - 1 ] ) ; } else { $ stmt -> bindValue ( $ index , $ param ) ; } $ index ++ ; } else { if ( isset ( $ types [ $ name ] ) ) { $ stmt -> bindValue ( $ name , $ param , $ types [ $ name ] ) ; } else { $ stmt -> bindValue ( $ name , $ param ) ; } } } }
Bind parameters to statement object
60,156
protected function executeAggregate ( $ fn , $ table , $ field , $ conditions ) { $ data = $ this -> selectAll ( $ table , $ conditions , $ fn . '(' . $ field . ')' ) ; return $ data ? ( float ) current ( $ data [ 0 ] ) : 0.0 ; }
Execute a query with aggregate function
60,157
public function useDb ( $ database ) { switch ( $ this -> driver ) { case 'mysql' : $ this -> query ( "USE `$database`" ) ; $ this -> dbname = $ database ; break ; default : throw new \ RuntimeException ( sprintf ( 'Unsupported switching database for current driver: %s' , $ this -> driver ) ) ; } return $ this ; }
Switch to specified database
60,158
public function transactional ( callable $ fn ) { $ pdo = $ this -> getPdo ( ) ; $ pdo -> beginTransaction ( ) ; try { call_user_func ( $ fn ) ; $ pdo -> commit ( ) ; } catch ( \ Exception $ e ) { $ pdo -> rollBack ( ) ; throw $ e ; } }
Execute a function in a transaction
60,159
public function map ( callable $ func ) : self { $ list = $ this -> list ; foreach ( $ list as $ index => $ val ) { $ list [ $ index ] = $ func ( $ val ) ; } return new static ( $ list ) ; }
map method .
60,160
public function flatMap ( callable $ func ) : array { $ list = $ this -> list ; $ acc = [ ] ; foreach ( $ list as $ val ) { $ acc [ ] = $ func ( $ val ) ; } return $ acc ; }
flatMap method .
60,161
public function filter ( callable $ func ) : self { $ list = $ this -> list ; $ acc = [ ] ; foreach ( $ list as $ index => $ val ) { if ( $ func ( $ val ) ) { $ acc [ ] = $ val ; } } return new static ( \ SplFixedArray :: fromArray ( $ acc ) ) ; }
filter method .
60,162
public function fold ( callable $ func , $ acc ) : self { $ list = $ this -> list ; foreach ( $ list as $ val ) { $ acc = $ func ( $ acc , $ val ) ; } return new static ( $ acc ) ; }
fold method .
60,163
public function slice ( int $ count ) : self { $ list = $ this -> list ; $ listCount = $ list -> count ( ) ; $ new = new \ SplFixedArray ( $ listCount - $ count ) ; foreach ( $ new as $ index => $ val ) { $ new [ $ index ] = $ list [ ( $ index + $ count ) ] ; } return new static ( $ new ) ; }
slice method .
60,164
public function merge ( self $ list ) : self { $ oldSize = $ this -> getSize ( ) ; $ combinedSize = $ oldSize + $ list -> getSize ( ) ; $ old = $ this -> list ; $ old -> setSize ( $ combinedSize ) ; foreach ( $ old as $ index => $ val ) { if ( $ index > $ oldSize - 1 ) { $ old [ $ index ] = $ list -> getList ( ) [ ( $ index - $ oldSize ) ] ; } } return new static ( $ old ) ; }
merge method .
60,165
public function reverse ( ) : self { $ list = $ this -> list ; $ count = $ this -> list -> getSize ( ) ; $ newList = new \ SplFixedArray ( $ count ) ; foreach ( $ newList as $ index => $ val ) { $ newList [ $ index ] = $ list [ $ count - $ index - 1 ] ; } return new static ( $ newList ) ; }
reverse method .
60,166
public function fill ( $ value , int $ start , int $ end ) { $ list = $ this -> list ; foreach ( $ list as $ index => $ val ) { $ list [ $ index ] = $ index >= $ start && $ index <= $ end ? $ value : $ val ; } return new static ( $ list ) ; }
fill method .
60,167
public function full ( $ param = null ) { $ uriAppend = 'full' ; $ params = $ this -> getQueryParams ( ) ; if ( ! is_null ( $ param ) ) { $ uriAppend = is_int ( $ param ) ? $ uriAppend . "/$param" : "url/$param" ; } $ response = $ this -> handler -> handle ( 'GET' , false , $ uriAppend , $ params ) ; return $ this -> make ( $ response ) ; }
Get list of entities
60,168
protected function prepareProps ( $ field , $ rule ) { $ props = $ messages = array ( ) ; $ props [ 'plugins/app/js/validation' ] = $ this ; if ( isset ( $ this -> names [ $ field ] ) ) { $ props [ 'name' ] = $ this -> names [ $ field ] ; } if ( isset ( $ this -> messages [ $ field ] [ $ rule ] ) && is_array ( $ this -> messages [ $ field ] ) ) { $ messages = $ this -> messages [ $ field ] [ $ rule ] ; } elseif ( isset ( $ this -> messages [ $ field ] ) && is_scalar ( $ this -> messages [ $ field ] ) ) { $ messages = $ this -> messages [ $ field ] ; } if ( is_scalar ( $ messages ) ) { $ props [ 'message' ] = $ messages ; } elseif ( is_array ( $ messages ) ) { foreach ( $ messages as $ name => $ message ) { $ props [ $ name . 'Message' ] = $ message ; } } return $ props ; }
Prepare name and messages property option for rule validator
60,169
public function getRuleParams ( $ field , $ rule ) { return isset ( $ this -> rules [ $ field ] [ $ rule ] ) ? ( array ) $ this -> rules [ $ field ] [ $ rule ] : array ( ) ; }
Get validation rule parameters
60,170
public function getInvalidRules ( $ field = null ) { return $ field ? isset ( $ this -> invalidRules [ $ field ] ) ? $ this -> invalidRules [ $ field ] : array ( ) : $ this -> invalidRules ; }
Get invalid rules by field
60,171
public function removeRule ( $ field , $ rule ) { if ( isset ( $ this -> rules [ $ field ] [ $ rule ] ) ) { unset ( $ this -> rules [ $ field ] [ $ rule ] ) ; return true ; } return false ; }
Removes the rule in field
60,172
public function removeField ( $ field ) { if ( isset ( $ this -> rules [ $ field ] ) ) { unset ( $ this -> rules [ $ field ] ) ; return true ; } return false ; }
Removes the validate field
60,173
public function setData ( $ data ) { if ( ! is_array ( $ data ) && ! is_object ( $ data ) ) { throw new \ InvalidArgumentException ( sprintf ( 'Expected argument of type array or object, "%s" given' , is_object ( $ data ) ? get_class ( $ data ) : gettype ( $ data ) ) ) ; } $ this -> data = $ data ; return $ this ; }
Sets data for validation
60,174
public function getFieldData ( $ field ) { if ( ( is_array ( $ this -> data ) && array_key_exists ( $ field , $ this -> data ) ) || ( $ this -> data instanceof \ ArrayAccess && $ this -> data -> offsetExists ( $ field ) ) ) { return $ this -> data [ $ field ] ; } elseif ( isset ( $ this -> data -> $ field ) ) { return $ this -> data -> $ field ; } elseif ( method_exists ( $ this -> data , 'get' . $ field ) ) { return $ this -> data -> { 'get' . $ field } ( ) ; } else { return null ; } }
Returns validation field data
60,175
public function setFieldData ( $ field , $ data ) { if ( is_array ( $ this -> data ) ) { $ this -> data [ $ field ] = $ data ; } else { $ this -> data -> $ field = $ data ; } return $ this ; }
Sets data for validation field
60,176
public function getDetailMessages ( ) { $ messages = array ( ) ; foreach ( $ this -> invalidRules as $ field => $ rules ) { foreach ( $ rules as $ rule ) { $ messages [ $ field ] [ $ rule ] = $ this -> ruleValidators [ $ field ] [ $ rule ] -> getMessages ( ) ; } } return $ messages ; }
Returns detail invalid messages
60,177
public function getSummaryMessages ( ) { $ messages = $ this -> getDetailMessages ( ) ; $ summaries = array ( ) ; foreach ( $ messages as $ field => $ rules ) { foreach ( $ rules as $ options ) { foreach ( $ options as $ message ) { $ summaries [ $ field ] [ ] = $ message ; } } } return $ summaries ; }
Returns summary invalid messages
60,178
public function getJoinedMessage ( $ separator = "\n" ) { $ messages = $ this -> getDetailMessages ( ) ; $ array = array ( ) ; foreach ( $ messages as $ rules ) { foreach ( $ rules as $ options ) { foreach ( $ options as $ message ) { $ array [ ] = $ message ; } } } return implode ( $ separator , array_unique ( $ array ) ) ; }
Returns error message string connected by specified separator
60,179
public function getRuleValidator ( $ field , $ rule ) { return isset ( $ this -> ruleValidators [ $ field ] [ $ rule ] ) ? $ this -> ruleValidators [ $ field ] [ $ rule ] : null ; }
Returns the rule validator object
60,180
public function createRuleValidator ( $ rule , array $ options = array ( ) ) { if ( 0 === stripos ( $ rule , 'not' ) ) { $ options [ 'negative' ] = true ; $ rule = substr ( $ rule , 3 ) ; } $ object = 'is' . ucfirst ( $ rule ) ; $ class = $ this -> wei -> getClass ( $ object ) ; if ( ! $ class || ! class_exists ( $ class ) ) { throw new \ InvalidArgumentException ( sprintf ( 'Validator "%s" not found' , $ rule ) ) ; } $ options = $ options + array ( 'wei' => $ this -> wei ) + ( array ) $ this -> wei -> getConfig ( 'is' . ucfirst ( $ rule ) ) ; return new $ class ( $ options ) ; }
Create a rule validator instance by specified rule name
60,181
public function detectEnvName ( ) { if ( $ this -> envFile && is_file ( $ this -> envFile ) ) { $ this -> name = require $ this -> envFile ; if ( $ this -> name ) { return ; } } if ( $ this -> detector && $ this -> name = call_user_func ( $ this -> detector ) ) { return ; } if ( isset ( $ this -> server [ 'SERVER_ADDR' ] ) ) { $ ip = $ this -> server [ 'SERVER_ADDR' ] ; if ( isset ( $ this -> ipMap [ $ ip ] ) ) { $ this -> name = $ this -> ipMap [ $ ip ] ; } else { $ this -> name = 'prod' ; } return ; } if ( php_sapi_name ( ) == 'cli' && $ ips = $ this -> getServerIps ( ) ) { foreach ( $ ips as $ ip ) { if ( isset ( $ this -> ipMap [ $ ip ] ) ) { $ this -> name = $ this -> ipMap [ $ ip ] ; return ; } } } $ this -> name = 'prod' ; return ; }
Detect environment by server IP
60,182
public function loadConfigFile ( $ file , $ env = null ) { $ file = str_replace ( '%env%' , $ env ? : $ this -> name , $ file ) ; $ config = $ this -> getFileConfig ( $ file ) ; if ( $ config ) { $ this -> wei -> setConfig ( $ config ) ; } return $ this ; }
Loads configs from specified file to service container
60,183
public function loadConfigDir ( $ dir , $ env = null ) { ! $ env && $ env = $ this -> name ; $ config = $ this -> getFileConfig ( $ dir . '/config.php' ) ; $ envConfig = $ this -> getFileConfig ( $ dir . '/config-' . $ env . '.php' ) ; $ config = array_replace_recursive ( $ config , $ envConfig ) ; $ this -> wei -> setConfig ( $ config ) ; return $ this ; }
Loads two config files in specified directory to service container
60,184
public function _json ( $ url , $ method = "get" , $ params = "{}" , $ jsCallback = NULL , $ attr = "id" , $ context = "document" , $ immediatly = false ) { $ jsCallback = isset ( $ jsCallback ) ? $ jsCallback : "" ; $ retour = $ this -> _getAjaxUrl ( $ url , $ attr ) ; $ retour .= "$.{$method}(url," . $ params . ").done(function( data ) {\n" ; $ retour .= "\tdata=$.parseJSON(data);for(var key in data){" . "if($('#'+key," . $ context . ").length){ if($('#'+key," . $ context . ").is('[value]')) { $('#'+key," . $ context . ").val(data[key]);} else { $('#'+key," . $ context . ").html(data[key]); }}};\n" ; $ retour .= "\t" . $ jsCallback . "\n" . "\t$(document).trigger('jsonReady',[data]);\n" . "});\n" ; if ( $ immediatly ) $ this -> jquery_code_for_compile [ ] = $ retour ; return $ retour ; }
Makes an ajax request and receives the JSON data types by assigning DOM elements with the same name
60,185
public function _jsonArray ( $ maskSelector , $ url , $ method = "get" , $ params = "{}" , $ jsCallback = NULL , $ attr = "id" , $ context = null , $ immediatly = false ) { $ jsCallback = isset ( $ jsCallback ) ? $ jsCallback : "" ; $ retour = $ this -> _getAjaxUrl ( $ url , $ attr ) ; if ( $ context === null ) { $ appendTo = "\t\tnewElm.appendTo($('" . $ maskSelector . "').parent());\n" ; $ newElm = "$('#'+newId)" ; } else { $ appendTo = "\t\tnewElm.appendTo(" . $ context . ");\n" ; $ newElm = $ context . ".find('#'+newId)" ; } $ retour .= "var self = $(this);\n$.{$method}(url," . $ params . ").done(function( data ) {\n" ; $ retour .= "\tdata=$.parseJSON(data);$.each(data, function(index, value) {\n" . "\tvar created=false;var maskElm=$('" . $ maskSelector . "').first();maskElm.hide();" . "\tvar newId=(maskElm.attr('id') || 'mask')+'-'+index;" . "\tvar newElm=" . $ newElm . ";\n" . "\tif(!newElm.length){\n" . "\t\tnewElm=maskElm.clone();newElm.attr('id',newId);\n" ; $ retour .= $ appendTo ; $ retour .= "\t}\n" . "\tfor(var key in value){\n" . "\t\t\tvar html = $('<div />').append($(newElm).clone()).html();\n" . "\t\t\tif(html.indexOf('[['+key+']]')>-1){\n" . "\t\t\t\tcontent=$(html.split('[['+key+']]').join(value[key]));\n" . "\t\t\t\t$(newElm).replaceWith(content);newElm=content;\n" . "\t\t\t}\n" . "\t\tvar sel='[data-id=\"'+key+'\"]';if($(sel,newElm).length){\n" . "\t\t\tvar selElm=$(sel,newElm);\n" . "\t\t\t if(selElm.is('[value]')) { selElm.attr('value',value[key]);selElm.val(value[key]);} else { selElm.html(value[key]); }\n" . "\t\t}\n" . "}\n" . "\t$(newElm).show(true);" . "\n" . "\t$(newElm).removeClass('hide');" . "});\n" ; $ retour .= "\t$(document).trigger('jsonReady',[data]);\n" ; $ retour .= "\t" . $ jsCallback . "\n" . "});\n" ; if ( $ immediatly ) $ this -> jquery_code_for_compile [ ] = $ retour ; return $ retour ; }
Makes an ajax request and receives a JSON array data types by copying and assigning them to the DOM elements with the same name
60,186
public function getConfig ( ) { return [ 'cluster' => Config :: get ( 'database.redis.cluster' ) , 'default' => [ 'host' => $ this -> HAClient -> getIpAddress ( ) , 'port' => $ this -> HAClient -> getPort ( ) , 'password' => Config :: get ( 'database.redis.password' , null ) , 'database' => Config :: get ( 'database.redis.database' , 0 ) , ] ] ; }
Get the config values for the redis database .
60,187
protected function addRedirectByHost ( $ sourceUriPath , $ targetUriPath , $ statusCode , $ host = null ) { $ redirect = new Redirect ( $ sourceUriPath , $ targetUriPath , $ statusCode , $ host ) ; $ this -> updateDependingRedirects ( $ redirect ) ; $ this -> persistenceManager -> persistAll ( ) ; $ this -> redirectRepository -> add ( $ redirect ) ; $ this -> routerCachingService -> flushCachesForUriPath ( $ sourceUriPath ) ; return RedirectDto :: create ( $ redirect ) ; }
Adds a redirect to the repository and updates related redirects accordingly .
60,188
protected function updateDependingRedirects ( RedirectInterface $ newRedirect ) { $ existingRedirectForSourceUriPath = $ this -> redirectRepository -> findOneBySourceUriPathAndHost ( $ newRedirect -> getSourceUriPath ( ) , $ newRedirect -> getHost ( ) , false ) ; if ( $ existingRedirectForSourceUriPath !== null ) { $ this -> removeAndLog ( $ existingRedirectForSourceUriPath , sprintf ( 'Existing redirect for the source URI path "%s" removed.' , $ newRedirect -> getSourceUriPath ( ) ) ) ; $ this -> routerCachingService -> flushCachesForUriPath ( $ existingRedirectForSourceUriPath -> getSourceUriPath ( ) ) ; } $ existingRedirectForTargetUriPath = $ this -> redirectRepository -> findOneBySourceUriPathAndHost ( $ newRedirect -> getTargetUriPath ( ) , $ newRedirect -> getHost ( ) , false ) ; if ( $ existingRedirectForTargetUriPath !== null ) { $ this -> removeAndLog ( $ existingRedirectForTargetUriPath , sprintf ( 'Existing redirect for the target URI path "%s" removed.' , $ newRedirect -> getTargetUriPath ( ) ) ) ; $ this -> routerCachingService -> flushCachesForUriPath ( $ existingRedirectForTargetUriPath -> getSourceUriPath ( ) ) ; } $ obsoleteRedirectInstances = $ this -> redirectRepository -> findByTargetUriPathAndHost ( $ newRedirect -> getSourceUriPath ( ) , $ newRedirect -> getHost ( ) ) ; foreach ( $ obsoleteRedirectInstances as $ obsoleteRedirect ) { if ( $ obsoleteRedirect -> getSourceUriPath ( ) === $ newRedirect -> getTargetUriPath ( ) ) { $ this -> redirectRepository -> remove ( $ obsoleteRedirect ) ; } else { $ obsoleteRedirect -> setTargetUriPath ( $ newRedirect -> getTargetUriPath ( ) ) ; $ this -> redirectRepository -> update ( $ obsoleteRedirect ) ; } } }
Updates affected redirects in order to avoid redundant or circular redirections .
60,189
public function incrementHitCount ( RedirectInterface $ redirect ) { try { $ this -> redirectRepository -> incrementHitCount ( $ redirect ) ; } catch ( \ Exception $ exception ) { $ this -> _logger -> logException ( $ exception ) ; } }
Increment the hit counter for the given redirect .
60,190
public function getFirstValueByAttributeCodeAsString ( string $ code , $ asTitle = true ) { $ attributeValue = $ this -> getFirstValueByAttributeCode ( $ code ) ; if ( ! $ attributeValue ) { return "" ; } $ field = $ asTitle ? 'title' : 'value' ; return $ attributeValue -> $ field ; }
The method should get rid of addition conditions in templates
60,191
public function calcChecksum ( $ input ) { $ wi = array ( 7 , 9 , 10 , 5 , 8 , 4 , 2 , 1 , 6 , 3 , 7 , 9 , 10 , 5 , 8 , 4 , 2 ) ; $ sum = 0 ; for ( $ i = 16 ; $ i >= 0 ; $ i -- ) { $ sum += $ input [ $ i ] * $ wi [ $ i ] ; } $ checksum = ( 12 - $ sum % 11 ) % 11 ; return $ checksum == 10 ? 'X' : ( string ) $ checksum ; }
Calculate the final digit of id card
60,192
public function toArray ( $ returnFields = array ( ) ) { if ( ! $ this -> isColl ) { $ data = array_fill_keys ( $ returnFields ? : $ this -> getFields ( ) , null ) ; if ( ! $ returnFields ) { return $ this -> data + $ data ; } else { $ data = array_fill_keys ( $ returnFields , null ) ; return array_intersect_key ( $ this -> data , $ data ) + $ data ; } } else { $ data = array ( ) ; foreach ( $ this -> data as $ key => $ record ) { $ data [ $ key ] = $ record -> toArray ( $ returnFields ) ; } return $ data ; } }
Returns the record data as array
60,193
public function isFillable ( $ field ) { return ! in_array ( $ field , $ this -> guarded ) && ! $ this -> fillable || in_array ( $ field , $ this -> fillable ) ; }
Check if the field is assignable through fromArray method
60,194
public function save ( $ data = array ( ) ) { $ data && $ this -> fromArray ( $ data ) ; if ( ! $ this -> isColl ) { if ( $ this -> isDestroyed ) { return $ this ; } if ( $ this -> detached ) { $ this -> db -> delete ( $ this -> table , array ( $ this -> primaryKey => $ this -> data [ $ this -> primaryKey ] ) ) ; $ this -> isDestroyed = true ; return $ this ; } $ isNew = $ this -> isNew ; $ this -> triggerCallback ( 'beforeSave' ) ; $ this -> triggerCallback ( $ isNew ? 'beforeCreate' : 'beforeUpdate' ) ; if ( $ isNew ) { if ( array_key_exists ( $ this -> primaryKey , $ this -> data ) && ! $ this -> data [ $ this -> primaryKey ] ) { unset ( $ this -> data [ $ this -> primaryKey ] ) ; } $ this -> db -> insert ( $ this -> table , $ this -> data ) ; $ this -> isNew = false ; if ( ! isset ( $ this -> data [ $ this -> primaryKey ] ) || ! $ this -> data [ $ this -> primaryKey ] ) { $ sequence = sprintf ( '%s_%s_seq' , $ this -> fullTable , $ this -> primaryKey ) ; $ this -> data [ $ this -> primaryKey ] = $ this -> db -> lastInsertId ( $ sequence ) ; } } else { if ( $ this -> isChanged ) { $ data = array_intersect_key ( $ this -> data , $ this -> changedData ) ; $ this -> db -> update ( $ this -> table , $ data , array ( $ this -> primaryKey => $ this -> data [ $ this -> primaryKey ] ) ) ; } } $ this -> changedData = array ( ) ; $ this -> isChanged = false ; $ this -> triggerCallback ( $ isNew ? 'afterCreate' : 'afterUpdate' ) ; $ this -> triggerCallback ( 'afterSave' ) ; } else { foreach ( $ this -> data as $ record ) { $ record -> save ( ) ; } } return $ this ; }
Save the record or data to database
60,195
public function destroy ( $ conditions = false ) { $ this -> andWhere ( $ conditions ) ; ! $ this -> loaded && $ this -> loadData ( 0 ) ; if ( ! $ this -> isColl ) { $ this -> triggerCallback ( 'beforeDestroy' ) ; $ this -> executeDestroy ( ) ; $ this -> isDestroyed = true ; $ this -> triggerCallback ( 'afterDestroy' ) ; } else { foreach ( $ this -> data as $ record ) { $ record -> destroy ( ) ; } } return $ this ; }
Delete the current record and trigger the beforeDestroy and afterDestroy callback
60,196
public function reload ( ) { $ this -> data = ( array ) $ this -> db -> select ( $ this -> table , array ( $ this -> primaryKey => $ this -> get ( $ this -> primaryKey ) ) ) ; $ this -> changedData = array ( ) ; $ this -> isChanged = false ; $ this -> triggerCallback ( 'afterLoad' ) ; return $ this ; }
Reload the record data from database
60,197
public function saveColl ( $ data , $ extraData = array ( ) , $ sort = false ) { if ( ! is_array ( $ data ) ) { return $ this ; } $ newData = array ( ) ; foreach ( $ this -> data as $ key => $ record ) { unset ( $ this -> data [ $ key ] ) ; if ( $ record instanceof $ this ) { $ newData [ $ record [ $ this -> primaryKey ] ] = $ record ; } } $ this -> data = $ newData ; foreach ( $ data as $ index => $ row ) { if ( ! array_filter ( $ row ) ) { unset ( $ data [ $ index ] ) ; } } $ existIds = array ( ) ; foreach ( $ data as $ row ) { if ( isset ( $ row [ $ this -> primaryKey ] ) && $ row [ $ this -> primaryKey ] !== null ) { $ existIds [ ] = $ row [ $ this -> primaryKey ] ; } } foreach ( $ this -> data as $ key => $ record ) { if ( ! in_array ( $ record [ $ this -> primaryKey ] , $ existIds ) ) { $ record -> destroy ( ) ; unset ( $ this -> data [ $ key ] ) ; } } foreach ( $ data as $ index => $ row ) { if ( $ sort ) { $ row [ $ sort ] = $ index ; } if ( isset ( $ row [ $ this -> primaryKey ] ) && isset ( $ this -> data [ $ row [ $ this -> primaryKey ] ] ) ) { $ this -> data [ $ row [ $ this -> primaryKey ] ] -> fromArray ( $ row ) ; } else { $ this [ ] = $ this -> db ( $ this -> table ) -> fromArray ( $ extraData + $ row ) ; } } return $ this -> save ( ) ; }
Merges data into collection and save to database including insert update and delete
60,198
public function get ( $ name ) { if ( ! $ this -> isColl && ! in_array ( $ name , $ this -> getFields ( ) ) ) { throw new \ InvalidArgumentException ( sprintf ( 'Field "%s" not found in record class "%s"' , $ name , get_class ( $ this ) ) ) ; } return isset ( $ this -> data [ $ name ] ) ? $ this -> data [ $ name ] : null ; }
Receives the record field value
60,199
public function set ( $ name , $ value = null ) { $ this -> loaded = true ; if ( ! $ this -> data && $ value instanceof static ) { $ this -> isColl = true ; } if ( ! $ this -> isColl ) { if ( in_array ( $ name , $ this -> getFields ( ) ) ) { $ this -> changedData [ $ name ] = isset ( $ this -> data [ $ name ] ) ? $ this -> data [ $ name ] : null ; $ this -> data [ $ name ] = $ value ; $ this -> isChanged = true ; } } else { if ( ! $ value instanceof static ) { throw new \ InvalidArgumentException ( 'Value for collection must be an instance of Wei\Record' ) ; } else { if ( $ name === null ) { $ this -> data [ ] = $ value ; } else { $ this -> data [ $ name ] = $ value ; } } } return $ this ; }
Set the record field value