idx int64 0 60.3k | question stringlengths 64 4.24k | target stringlengths 5 618 |
|---|---|---|
44,800 | private function tokenExpired ( ) { $ tokenExpirationTime = $ this -> requestTimestamp + $ this -> data [ static :: RESPONSE_KEY_ACCESS_TOKEN_TTL ] - static :: TTL_CORRECTION_TIME_SEC ; return $ this -> tokenExists ( ) && time ( ) > $ tokenExpirationTime ; } | Checks if token is expired |
44,801 | private function tokenCanBeRenewed ( ) { return $ this -> tokenExists ( ) && ( time ( ) < ( $ this -> requestTimestamp + $ this -> data [ self :: RESPONSE_KEY_REFRESH_TOKEN_TTL ] ) ) ; } | Checks if token can be renewed |
44,802 | public function createBatch ( CreateBatchParameters $ parameters ) { $ requestData = $ this -> getDefaultRequestData ( 'json' , $ parameters -> exportToArray ( ) ) ; return $ this -> sendRequest ( 'batches' , $ requestData , self :: HTTP_METHOD_POST ) ; } | Creates a batch . |
44,803 | public function executeBatch ( $ batchUid ) { $ endpoint = vsprintf ( 'batches/%s' , [ $ batchUid ] ) ; $ requestData = $ this -> getDefaultRequestData ( 'json' , [ 'action' => self :: ACTION_EXECUTE , ] ) ; return $ this -> sendRequest ( $ endpoint , $ requestData , self :: HTTP_METHOD_POST ) ; } | Execute batch . |
44,804 | public function getBatchStatus ( $ batchUid ) { $ endpoint = vsprintf ( 'batches/%s' , [ $ batchUid ] ) ; $ requestData = $ this -> getDefaultRequestData ( 'query' , [ ] ) ; return $ this -> sendRequest ( $ endpoint , $ requestData , self :: HTTP_METHOD_GET ) ; } | Returns batch status . |
44,805 | public function getErrorsByKey ( $ key ) { if ( ! is_string ( $ key ) ) { throw new \ Exception ( 'Key must be a string' ) ; } $ errors = array_filter ( $ this -> errors , function ( $ el ) use ( $ key ) { return $ el [ 'key' ] === $ key ; } ) ; return $ errors ; } | Get list of errors by specified key . |
44,806 | public function formatErrors ( $ title = '' ) { $ errorsStr = PHP_EOL ; foreach ( $ this -> errors as $ k => $ error ) { $ details = [ ] ; if ( isset ( $ error [ 'details' ] ) && is_array ( $ error [ 'details' ] ) ) { foreach ( $ error [ 'details' ] as $ name => $ value ) { $ details [ ] = sprintf ( '%s:%s' , $ name , $ value ) ; } } $ body = sprintf ( 'key: %smessage: %sdetails: %s' , $ error [ 'key' ] . PHP_EOL , $ error [ 'message' ] . PHP_EOL , implode ( ' | ' , $ details ) . PHP_EOL ) ; $ errorsStr .= $ body . self :: ERROR_OUTPUT_SEPARATOR . PHP_EOL ; } $ messageTemplate = $ title . PHP_EOL . 'Response code: %s' . PHP_EOL . 'Response errors (%s): %s%s' . PHP_EOL ; $ output = vsprintf ( $ messageTemplate , [ $ this -> getCode ( ) , count ( $ this -> errors ) , PHP_EOL . self :: ERROR_OUTPUT_SEPARATOR , $ errorsStr , ] ) ; return $ output ; } | Format errors . |
44,807 | public function createRecord ( $ spaceId , $ objectId , RecordParameters $ parameters ) { $ requestData = $ this -> getDefaultRequestData ( 'json' , $ parameters -> exportToArray ( ) ) ; $ endpoint = vsprintf ( 'projects/%s/spaces/%s/objects/%s/records' , [ $ this -> getProjectId ( ) , $ spaceId , $ objectId , ] ) ; return $ this -> sendRequest ( $ endpoint , $ requestData , static :: HTTP_METHOD_POST ) ; } | Creates a new record . |
44,808 | public function deleteRecord ( $ spaceId , $ objectId , $ recordId ) { $ requestData = $ this -> getDefaultRequestData ( 'query' , [ ] ) ; $ endpoint = vsprintf ( 'projects/%s/spaces/%s/objects/%s/records/%s' , [ $ this -> getProjectId ( ) , $ spaceId , $ objectId , $ recordId ] ) ; return $ this -> sendRequest ( $ endpoint , $ requestData , static :: HTTP_METHOD_DELETE ) ; } | Deletes record . |
44,809 | public function getResult ( $ profile = [ ] ) { $ profile [ 'userName' ] = $ this -> userName ; $ profile [ 'token' ] = $ this -> token ; $ di = \ Phalcon \ Di :: getDefault ( ) ; $ result = $ di -> get ( 'result' , [ 'profile' ] ) ; $ result -> outputMode = 'single' ; $ id = ( isset ( $ profile [ 'id' ] ) ) ? $ profile [ 'id' ] : 1 ; $ data = $ di -> get ( 'data' , [ $ id , 'profile' , $ profile ] ) ; $ result -> addData ( $ data ) ; return $ result ; } | take an array of profile data and return a fully compatible result set |
44,810 | public function jsonSerialize ( ) { $ config = $ this -> di -> get ( 'config' ) ; if ( $ config [ 'application' ] [ 'propertyFormatTo' ] == 'none' ) { $ attributes = $ this -> attributes ; } else { $ inflector = $ this -> di -> get ( 'inflector' ) ; $ attributes = [ ] ; foreach ( $ this -> attributes as $ key => $ value ) { $ attributes [ $ inflector -> normalize ( $ key , $ config [ 'application' ] [ 'propertyFormatTo' ] ) ] = $ value ; } } $ result = [ 'id' => $ this -> id , 'type' => $ this -> type , 'attributes' => $ attributes ] ; if ( $ this -> relationships ) { $ result [ 'relationships' ] = $ this -> relationships ; } return $ result ; } | hook to describe how to encode this class for JSON |
44,811 | public function evaluateRule ( $ fieldValue ) { $ testFunction = "return ('" . $ fieldValue . "' $this->operator '$this->value' ) ? true : false ;" ; $ result = eval ( $ testFunction ) ; if ( ! is_bool ( $ result ) ) { throw new HTTPException ( 'DenyIf rule returned invalid result. Must be a boolean' , 500 , [ 'code' => '136497941613689198' ] ) ; } return $ result ; } | for a supplied value evaluate it against the defined rule set |
44,812 | public function onConstruct ( ) { if ( $ this -> request -> getMethod ( ) == 'OPTIONS' && APPLICATION_ENV != 'production' ) { return ; } $ config = $ this -> getDI ( ) -> get ( 'config' ) ; $ auth = $ this -> getDI ( ) -> get ( 'auth' ) ; switch ( $ config [ 'security' ] ) { case true : $ token = $ this -> getAuthToken ( ) ; if ( $ auth -> isLoggedIn ( $ token ) ) { } else { throw new HTTPException ( 'Unauthorized, please authenticate first.' , 401 , [ 'dev' => 'Must be authenticated to access.' , 'code' => '30945680384502037' ] ) ; } break ; case false : if ( $ auth -> isLoggedIn ( 'HACKYHACKERSON' ) ) { } else { throw new HTTPException ( 'Security False is not loading a valid user.' , 401 , [ 'dev' => 'The authenticator isn\'t loading a valid user.' , 'code' => '23749873490704' ] ) ; } break ; default : throw new HTTPException ( 'Bad security value supplied' , 500 , [ 'code' => '280273409724075' ] ) ; break ; } parent :: onConstruct ( ) ; } | this function will gather an auth token and proceed or fail |
44,813 | protected function formatJSON ( ) { $ result = new \ stdClass ; if ( $ this -> outputMode == self :: MODE_ERROR ) { $ this -> formatFailure ( $ result ) ; } else { $ this -> formatSuccess ( $ result ) ; } if ( $ this -> meta ) { $ result -> meta = $ this -> meta ; } return $ result ; } | will convert the intermediate data result data into ActiveModel compatible result object |
44,814 | protected function formatJSON ( ) { $ result = new \ stdClass ( ) ; if ( $ this -> outputMode == self :: MODE_ERROR ) { $ this -> formatFailure ( $ result ) ; } else { $ this -> formatSuccess ( $ result ) ; } foreach ( $ this -> plain as $ key => $ value ) { $ result -> $ key = $ value ; } if ( $ this -> meta ) { $ result -> meta = $ this -> meta ; } return $ result ; } | adapters function to spit output into a generic class which will be converted to json before too long |
44,815 | protected function formatSuccess ( $ result ) { switch ( $ this -> outputMode ) { case self :: MODE_SINGLE : $ result -> data = array_values ( $ this -> data ) [ 0 ] ; break ; case self :: MODE_MULTIPLE : $ result -> data = array_values ( $ this -> data ) ; break ; case self :: MODE_OTHER : break ; default : throw new HTTPException ( 'Error generating output. Cannot match output mode with data set.' , 500 , [ 'code' => '894684684646846816161' ] ) ; } if ( $ this -> data && $ this -> included ) { $ result -> included = array_flatten ( $ this -> included ) ; } } | utility class to process extracting intermediate data from the data object |
44,816 | protected function formatFailure ( $ result ) { $ appConfig = $ this -> di -> get ( 'config' ) [ 'application' ] ; $ inflector = $ this -> di -> get ( 'inflector' ) ; $ result -> errors = [ ] ; foreach ( $ this -> errors as $ error ) { if ( $ error -> validationList ) { $ validationErrors = array_map ( function ( Message $ validation ) use ( $ error , $ appConfig , $ inflector ) { $ field = $ inflector -> normalize ( $ validation -> getField ( ) , $ appConfig [ 'propertyFormatTo' ] ) ; $ details = [ 'code' => $ error -> code , 'title' => $ error -> title , 'detail' => $ validation -> getMessage ( ) , 'source' => [ 'pointer' => "/data/attributes/$field" ] , 'meta' => [ 'field' => $ field ] ] ; if ( $ appConfig [ 'debugApp' ] && $ error -> dev ) { $ details [ 'meta' ] [ 'developer_message' ] = $ error -> dev ; } return $ details ; } , $ error -> validationList ) ; $ result -> errors = array_merge ( $ result -> errors , $ validationErrors ) ; } else { $ details = [ 'title' => $ error -> title , 'code' => $ error -> code , 'detail' => $ error -> more , ] ; if ( $ appConfig [ 'debugApp' ] ) { $ meta = array_filter ( [ 'developer_message' => $ error -> dev , 'file' => $ error -> file , 'line' => $ error -> line , 'stack' => $ error -> stack , 'context' => $ error -> context , ] ) ; if ( $ meta ) { $ details [ 'meta' ] = $ meta ; } } $ result -> errors [ ] = $ details ; } } } | darn there was an error process the offending code and return to the client |
44,817 | public function build ( $ count = false ) { $ modelNameSpace = $ this -> model -> getModelNameSpace ( ) ; $ mm = $ this -> getDI ( ) -> get ( 'modelsManager' ) ; $ query = $ mm -> createBuilder ( ) -> from ( $ modelNameSpace ) ; $ columns = array ( "$modelNameSpace.*" ) ; $ this -> queryJoinHelper ( $ query ) ; $ this -> querySearchHelper ( $ query ) ; $ this -> querySortHelper ( $ query ) ; if ( $ count ) { $ query -> columns ( 'count(*) as count' ) ; } else { $ existingColumns = $ query -> getColumns ( ) ; $ allColumns = array_merge ( $ columns , $ existingColumns ) ; $ query -> columns ( $ allColumns ) ; } if ( ! $ count ) { $ this -> queryLimitHelper ( $ query ) ; } return $ query ; } | build a PHQL based query to be executed by the runSearch method broken up into helpers so extending this function duplicates less code |
44,818 | public function send ( Result $ result = null ) { if ( $ result ) { if ( $ this -> di -> get ( 'config' ) [ 'application' ] [ 'debugApp' ] == true ) { $ timer = $ this -> di -> get ( 'stopwatch' ) ; $ timer -> end ( ) ; $ summary = [ 'total_run_time' => round ( ( $ timer -> endTime - $ timer -> startTime ) * 1000 , 2 ) . ' ms' , 'laps' => [ ] ] ; foreach ( $ timer -> laps as $ lap ) { $ summary [ 'laps' ] [ $ lap [ 'name' ] ] = round ( ( $ lap [ 'end' ] - $ lap [ 'start' ] ) * 1000 , 2 ) . ' ms' ; } $ result -> addMeta ( 'stopwatch' , $ summary ) ; } $ this -> _send ( $ result -> outputJSON ( ) ) ; } else { $ this -> setStatusCode ( 204 ) ; $ this -> _send ( '' ) ; } exit ( ) ; } | format result set for output to web browser add any final meta data |
44,819 | private function _send ( $ message ) { $ response = $ this -> di -> get ( 'response' ) ; $ response -> setStatusCode ( $ this -> httpCode , $ this -> httpMessage ) ; if ( $ this -> head || ! $ message ) { $ response -> setContentType ( null ) ; } else { $ jsonConfig = $ this -> di -> get ( 'config' ) [ 'application' ] [ 'debugApp' ] ? JSON_PRETTY_PRINT : 0 ; $ response -> setJsonContent ( $ message , $ jsonConfig ) ; } $ response -> send ( ) ; } | for a given string message prepare a basic json response for the browser |
44,820 | public function setStatusCode ( $ code , $ message = null ) { $ this -> httpCode = $ code ; $ this -> httpMessage = $ message ; } | simple setter for properties |
44,821 | public function normalize ( $ word , $ to ) { switch ( $ to ) { case 'camel' : return lcfirst ( $ this -> camelize ( $ word ) ) ; break ; case 'snake' : return $ this -> underscore ( $ word ) ; break ; case 'dash' : return $ this -> dasherize ( $ word ) ; break ; default : throw new HTTPException ( 'Invalid nomalization requested' , 404 , array ( 'dev' => 'The provided TO field was invalid It did not match any expected format' , 'code' => '46546846468464684' ) ) ; break ; } } | for a given word convert from one format to another supported values include camel dash snake |
44,822 | final public function arrayKeysToCamel ( array $ snakeArray ) { $ camelArray = [ ] ; foreach ( $ snakeArray as $ key => $ value ) { if ( is_array ( $ value ) ) { $ value = $ this -> arrayKeysToCamel ( $ value ) ; } $ camelArray [ $ this -> camelize ( $ key ) ] = $ value ; unset ( $ snakeArray [ $ key ] ) ; } return $ camelArray ; } | In - Place recursive conversion of array keys in snake_Case to camelCase |
44,823 | final public function objectPropertiesToCamel ( $ snakeObject ) { $ camelObject = new \ stdClass ( ) ; foreach ( $ snakeObject as $ key => $ value ) { if ( is_object ( $ value ) ) { $ value = $ this -> objectPropertiesToCamel ( $ value ) ; } elseif ( is_array ( $ value ) ) { $ value = $ this -> arrayKeysToCamel ( $ value ) ; } $ camelObject -> { $ this -> camelize ( $ key ) } = $ value ; unset ( $ snakeObject [ $ key ] ) ; } return $ camelObject ; } | In - Place recursive conversion of stdClass keys in snake_Case to camelCase |
44,824 | final public function arrayKeysToSnake ( array $ camelArray ) { $ snakeArray = [ ] ; foreach ( $ camelArray as $ key => $ value ) { if ( is_array ( $ value ) ) { $ value = $ this -> arrayKeysToSnake ( $ value ) ; } $ snakeArray [ $ this -> underscore ( $ key ) ] = $ value ; unset ( $ camelArray [ $ key ] ) ; } return $ snakeArray ; } | In - Place recursive conversion of array keys in camelCase to snake_Case |
44,825 | final public function objectPropertiesToSnake ( $ camelObject , $ parent_key = 'root' ) { $ snakeObject = new \ stdClass ( ) ; foreach ( $ camelObject as $ key => $ value ) { if ( is_object ( $ value ) ) { $ value = $ this -> objectPropertiesToSnake ( $ value , $ key ) ; } elseif ( is_array ( $ value ) ) { $ value = $ this -> arrayKeysToSnake ( $ value ) ; } if ( is_object ( $ value ) ) { $ obj_vars = get_object_vars ( $ value ) ; } else { $ obj_vars = array ( ) ; } if ( in_array ( $ key , array_keys ( $ obj_vars ) ) && ( $ parent_key !== "root" ) ) { foreach ( $ value -> { $ key } as $ vk => $ vv ) { if ( ! isset ( $ snakeObject -> $ parent_key ) ) { $ snakeObject -> $ parent_key = new \ stdClass ( ) ; } if ( ! property_exists ( $ snakeObject -> $ parent_key , $ this -> underscore ( $ key ) ) ) { $ snakeObject -> $ parent_key -> { $ this -> underscore ( $ key ) } = new \ stdClass ( ) ; } $ snakeObject -> $ parent_key -> { $ this -> underscore ( $ key ) } -> { $ vk } = $ vv ; } } else { if ( $ parent_key === "root" ) { if ( ! empty ( $ obj_vars ) ) { $ property_key = array_keys ( $ obj_vars ) [ 0 ] ; foreach ( $ value -> { $ key } as $ vk => $ vv ) { if ( ! property_exists ( $ snakeObject , $ property_key ) ) { $ snakeObject -> $ property_key = new \ stdClass ( ) ; } $ snakeObject -> $ property_key -> { $ vk } = $ vv ; } } else { $ snakeObject -> { $ this -> underscore ( $ key ) } = $ value ; } } else { if ( ! property_exists ( $ snakeObject , $ parent_key ) ) { $ snakeObject -> $ parent_key = new \ stdClass ( ) ; } $ snakeObject -> $ parent_key -> { $ this -> underscore ( $ key ) } = $ value ; } } } return $ snakeObject ; } | In - Place recursive conversion of object properties in camelCase to snake_Case |
44,826 | public function evaluateCallback ( \ PhalconRest \ API \ BaseModel $ oldModel , $ formData ) { $ check = $ this -> check ; $ check ( $ oldModel , $ formData ) ; } | for a supplied parameters run the call back do not return a value let call back handle what it finds and processes |
44,827 | public function registerRelationshipDefinitions ( $ relation ) { switch ( $ relation -> getType ( ) ) { case PhalconRelation :: HAS_ONE : case PhalconRelation :: BELONGS_TO : case PhalconRelation :: HAS_ONE_THROUGH : $ name = $ relation -> getTableName ( 'singular' ) ; break ; case PhalconRelation :: HAS_MANY : case PhalconRelation :: HAS_MANY_THROUGH : $ name = $ relation -> getTableName ( 'plural' ) ; break ; default : throw new HTTPException ( 'A Bad Relationship Type was supplied!' , 500 , [ 'code' => '8948616164789797' ] ) ; } $ this -> relationshipRegistry [ strtolower ( $ name ) ] = $ relation ; } | write or overwrite a definition each definition should map to a table name we ll massage the name a little bit to cut down on errors |
44,828 | public function addError ( ErrorStore $ error ) { $ this -> outputMode = self :: MODE_ERROR ; $ this -> errors [ ] = $ error ; } | add an error store object to the Result payload |
44,829 | public function addIncluded ( Data $ newData ) { $ this -> included [ $ newData -> getType ( ) ] [ $ newData -> getId ( ) ] = $ newData ; } | add a Data object to include array on result payload |
44,830 | public function addRelationship ( $ id , $ relationship , $ related_id , $ type = false ) { foreach ( $ this -> data as $ key => $ data ) { if ( $ data -> getId ( ) == $ id ) { $ this -> data [ $ key ] -> addRelationship ( $ relationship , $ related_id , $ type ) ; return true ; } } return false ; } | for a supplied primary id and related id create a relationship |
44,831 | public function outputJSON ( ) { if ( count ( $ this -> data ) > 1 && $ this -> outputMode == self :: MODE_SINGLE ) { throw new \ Exception ( 'multiple records returned, but output-mode is single?' ) ; } return $ this -> formatJSON ( ) ; } | used this function to perform some final checks on the result set before passing to the adapter |
44,832 | public function getPlain ( $ key = false ) { if ( $ key ) { if ( isset ( $ this -> plain [ $ key ] ) ) { return $ this -> plain [ $ key ] ; } else { return null ; } } else { return $ this -> plain ; } } | provides access to the plain array |
44,833 | public function authenticate ( $ userName , $ password ) { $ this -> beforeLogin ( $ userName , $ password ) ; $ result = $ this -> adapter -> authenticate ( $ userName , $ password ) ; if ( $ result ) { $ this -> profile -> loadProfile ( "$this->userNameFieldName = '$userName'" ) ; $ this -> profile -> resetToken ( ) ; } $ this -> afterLogin ( $ userName , $ password , $ result ) ; return $ result ; } | run a set of credentials against the adapters internal authenticate function will retain a copy of the adapter provided profile |
44,834 | public function getRules ( int $ crud = NULL , string $ type = NULL ) : array { if ( $ crud == NULL ) { $ ruleSet = $ this -> rules ; } else { $ ruleSet = [ ] ; foreach ( $ this -> rules as $ rule ) { if ( $ rule -> crud & $ crud ) { $ ruleSet [ ] = $ rule ; } } } if ( $ type == NULL ) { return $ ruleSet ; } else { $ filteredRuleSet = [ ] ; foreach ( $ ruleSet as $ rule ) { $ reflection = new \ ReflectionClass ( $ rule ) ; $ className = $ reflection -> getShortName ( ) ; if ( $ className == $ type ) { $ filteredRuleSet [ ] = $ rule ; } } return $ filteredRuleSet ; } } | get all rules for the relevant action If no mode is supplied all rules are returned |
44,835 | public function addFilterRule ( string $ field , string $ value , $ operator = null , int $ crud = READRULES ) { $ this -> rules [ $ field ] = new FilterRule ( $ field , $ value , $ operator , $ crud ) ; } | add a filter rule into the store |
44,836 | public function addQueryRule ( string $ rule , int $ crud = READRULES ) { $ this -> rules [ rand ( 1 , 99999 ) ] = new QueryRule ( $ rule , $ crud ) ; } | load a query rule into the store |
44,837 | public function addModelCallbackRule ( \ Closure $ check , $ crud = DELETERULES ) { $ this -> rules [ rand ( 1 , 99999 ) ] = new ModelCallbackRule ( $ check , $ crud ) ; } | load a modelCallBack rule into the store |
44,838 | public function clearRules ( int $ crud = NULL ) { if ( $ crud == NULL ) { $ this -> rules = [ ] ; return true ; } $ ruleSet = [ ] ; foreach ( $ this -> rules as $ rule ) { if ( ! $ rule -> crud & $ crud ) { $ ruleSet [ ] = $ rule ; } } $ this -> rules = $ ruleSet ; return true ; } | clear all rules of particular mode If no mode is supplied all rules are wiped |
44,839 | public function getModelName ( $ type = 'plural' ) { if ( $ type == 'plural' ) { if ( isset ( $ this -> pluralName ) ) { return $ this -> pluralName ; } else { $ config = $ this -> getDI ( ) -> get ( 'config' ) ; $ modelNameSpace = $ config [ 'namespaces' ] [ 'models' ] ; $ name = get_class ( $ this ) ; $ name = str_replace ( $ modelNameSpace , '' , $ name ) ; $ this -> pluralName = $ name ; return $ this -> pluralName ; } } if ( $ type == 'singular' ) { if ( ! isset ( $ this -> singularName ) ) { $ this -> singularName = substr ( $ this -> getModelName ( 'plural' ) , 0 , strlen ( $ this -> getModelName ( 'plural' ) ) - 1 ) ; } return $ this -> singularName ; } return false ; } | provided to lazy load the model s name |
44,840 | public function getModelNameSpace ( ) { if ( ! isset ( $ this -> modelNameSpace ) ) { $ config = $ this -> getDI ( ) -> get ( 'config' ) ; $ nameSpace = $ config [ 'namespaces' ] [ 'models' ] ; $ this -> modelNameSpace = $ nameSpace . $ this -> getModelName ( ) ; } return $ this -> modelNameSpace ; } | simple function to return the model s full name space relies on getModelName lazy load and cache result |
44,841 | public function getPrimaryKeyName ( ) { if ( ! isset ( $ this -> primaryKeyName ) ) { $ memory = $ this -> getDI ( ) -> get ( 'memory' ) ; $ attributes = $ memory -> getPrimaryKeyAttributes ( $ this ) ; $ attributeKey = $ attributes [ 0 ] ; $ colMap = $ memory -> getColumnMap ( $ this ) ; if ( is_null ( $ colMap ) ) { $ this -> primaryKeyName = $ attributeKey ; } else { $ this -> primaryKeyName = $ colMap [ $ attributeKey ] ; } } return $ this -> primaryKeyName ; } | will return the primary key name for a given model |
44,842 | public function getTableName ( $ type = 'plural' ) { if ( $ type == 'plural' ) { if ( isset ( $ this -> pluralTableName ) ) { return $ this -> pluralTableName ; } else { $ this -> pluralTableName = $ this -> getSource ( ) ; return $ this -> pluralTableName ; } } if ( $ type == 'singular' ) { if ( isset ( $ this -> singularTableName ) ) { return $ this -> singularTableName ; } else { $ tableName = $ this -> getTableName ( 'plural' ) ; $ this -> singularTableName = substr ( $ tableName , 0 , strlen ( $ tableName ) - 1 ) ; return $ this -> singularTableName ; } } } | default behavior is to expect plural table names in schema |
44,843 | public function getPrimaryKeyValue ( ) { $ key = $ this -> getPrimaryKeyName ( ) ; return isset ( $ this -> $ key ) ? $ this -> $ key : null ; } | return the model s current primary key value this is designed to work for a single model record and not a collection |
44,844 | public function getRelations ( ) { if ( ! isset ( $ this -> relationships ) ) { $ this -> relationships = array ( ) ; $ mm = $ this -> getModelsManager ( ) ; $ relationships = $ mm -> getRelations ( get_class ( $ this ) ) ; $ mtmRelationships = $ mm -> getHasManyToMany ( $ this ) ; $ relationships = array_merge ( $ relationships , $ mtmRelationships ) ; foreach ( $ relationships as $ relation ) { $ this -> relationships [ ] = new Relation ( $ relation , $ mm ) ; } } return $ this -> relationships ; } | return all configured relations for a given model use the supplied Relation library |
44,845 | public function getRelation ( $ name ) { if ( ! isset ( $ this -> relationships ) ) { $ relations = $ this -> getRelations ( ) ; } else { $ relations = $ this -> relationships ; } foreach ( $ relations as $ relation ) { if ( $ relation -> getAlias ( ) == $ name ) { return $ relation ; } } return false ; } | get a particular relationship configured for this model |
44,846 | public function loadBlockColumns ( ) { $ blockColumns = [ ] ; $ parentModelName = static :: $ parentModel ; if ( $ parentModelName ) { $ parentModelNameSpace = "\\PhalconRest\\Models\\" . $ parentModelName ; $ parentModel = new $ parentModelNameSpace ( ) ; $ blockColumns = $ parentModel -> getBlockColumns ( ) ; if ( $ blockColumns == null ) { $ blockColumns = [ ] ; } } $ this -> setBlockColumns ( $ blockColumns , true ) ; } | a hook to be run when initializing a model write logic here to block columns |
44,847 | public function setBlockColumns ( $ columnList , $ clear = false ) { if ( $ clear ) { $ this -> blockColumns = [ ] ; } foreach ( $ columnList as $ column ) { $ this -> blockColumns [ ] = $ column ; } } | for a given array of column names add them to the block list |
44,848 | public function getBlockColumns ( $ includeParent = true ) { if ( $ this -> blockColumns === null ) { $ this -> loadBlockColumns ( ) ; } $ blockColumns = $ this -> blockColumns ; if ( $ includeParent ) { $ parentModel = $ this -> getParentModel ( true ) ; if ( $ parentModel ) { $ parentModel = new $ parentModel ( ) ; $ parentColumns = $ parentModel -> getBlockColumns ( true ) ; if ( $ parentColumns == null ) { $ parentColumns = [ ] ; } $ blockColumns = array_unique ( array_merge ( $ blockColumns , $ parentColumns ) ) ; } } return $ blockColumns ; } | basic getter for private property |
44,849 | public function getAllColumns ( $ includeParent = true ) { $ metaData = $ this -> getDI ( ) -> get ( 'memory' ) ; $ colMap = $ metaData -> getColumnMap ( $ this ) ; if ( is_null ( $ colMap ) ) { $ colMap = $ metaData -> getAttributes ( $ this ) ; } if ( $ includeParent ) { $ parentModel = $ this -> getParentModel ( true ) ; if ( $ parentModel ) { $ parentModel = new $ parentModel ( ) ; $ parentColumns = $ parentModel -> getAllColumns ( true ) ; if ( $ parentColumns == null ) { $ parentColumns = [ ] ; } $ colMap = array_merge ( $ colMap , $ parentColumns ) ; } } return $ colMap ; } | return what should be a full set of columns for the model if requested return parent columns as well |
44,850 | public function getParentModels ( $ withNamespace = false ) { $ modelNameSpace = null ; if ( ! isset ( $ parentModels ) ) { $ config = $ this -> getDI ( ) -> get ( 'config' ) ; $ modelNameSpace = $ config [ 'namespaces' ] [ 'models' ] ; $ path = $ modelNameSpace . $ this -> getModelName ( ) ; $ parents = array ( ) ; $ currentParent = $ path :: $ parentModel ; while ( $ currentParent ) : $ parents [ ] = $ currentParent ; $ path = $ modelNameSpace . $ currentParent ; $ currentParent = $ path :: $ parentModel ; endwhile ; $ this -> parentModels = $ parents ; } if ( count ( $ this -> parentModels ) == 0 ) { return false ; } if ( ! $ withNamespace ) { $ modelNameSpace = null ; } $ parents = [ ] ; foreach ( $ this -> parentModels as $ parent ) { $ parents [ ] = $ modelNameSpace . $ parent ; } return $ parents ; } | ask this entity for all parents from the model and up the chain lazy load and cache |
44,851 | public function getParentModel ( $ withNamespace = false ) { $ config = $ this -> getDI ( ) -> get ( 'config' ) ; $ modelNameSpace = $ config [ 'namespaces' ] [ 'models' ] ; $ path = $ modelNameSpace . $ this -> getModelName ( ) ; $ parentModelName = $ path :: $ parentModel ; if ( ! $ parentModelName ) { return false ; } return $ withNamespace ? $ modelNameSpace . $ parentModelName : $ parentModelName ; } | get the model name or full namespace |
44,852 | public function update ( $ key , $ value ) { if ( $ this -> enforceRules ) { $ value -> enable ( ) ; } else { $ value -> disable ( ) ; } $ this -> store [ $ key ] = $ value ; } | load rule store and conform to general activation settings |
44,853 | public function get ( $ key ) { if ( array_key_exists ( $ key , $ this -> store ) ) { return $ this -> store [ $ key ] ; } return null ; } | check for a rulestore in the registry return NULL if no matching name if found |
44,854 | public function getNewStore ( \ PhalconRest \ API \ BaseModel $ model ) : \ PhalconRest \ Rules \ Store { $ newStore = new \ PhalconRest \ Rules \ Store ( $ model ) ; if ( $ this -> enforceRules ) { $ newStore -> enable ( ) ; } else { $ newStore -> disable ( ) ; } return $ newStore ; } | construct a new Store object configured for enforcement |
44,855 | final public function disable ( ) { $ this -> enforceRules = false ; foreach ( $ this -> store as $ store ) { $ store -> disable ( ) ; } } | tell the rule register to deactivate |
44,856 | final public function enable ( ) { $ this -> enforceRules = true ; foreach ( $ this -> store as $ store ) { $ store -> enable ( ) ; } } | tell the rulestore to enforce it s rules |
44,857 | protected function getTableNameSpace ( string $ name , $ escape = true ) { $ searchBits = explode ( ':' , $ name ) ; $ colMap = [ ] ; if ( count ( $ searchBits ) == 2 ) { $ fieldName = $ searchBits [ 1 ] ; $ matchFound = false ; foreach ( $ this -> entity -> activeRelations as $ relation ) { if ( $ searchBits [ 0 ] == $ relation -> getTableName ( ) ) { $ alias = $ relation -> getAlias ( ) ; if ( ! $ alias ) { $ alias = $ relation -> getReferencedModel ( ) ; } $ modelNameSpace = $ relation -> getReferencedModel ( ) ; $ relatedModel = new $ modelNameSpace ( ) ; $ colMap = $ relatedModel -> getAllColumns ( ) ; $ matchFound = true ; break ; } } if ( $ matchFound == false ) { throw new HTTPException ( "Unknown table prefix supplied in filter." , 500 , array ( 'dev' => "Encountered a table prefix that did not match any known hasOne relationships in the model. Encountered Search: $fieldName" , 'code' => '891488651361948131461849' ) ) ; } } else { $ fieldName = $ searchBits [ 0 ] ; $ alias = $ this -> model -> getModelNameSpace ( ) ; $ colMap = $ this -> model -> getAllColumns ( false ) ; } foreach ( $ colMap as $ field ) { if ( $ fieldName == $ field ) { return ( $ escape == true ? "[$alias]" : $ alias ) ; } } $ currentModel = $ this -> model ; while ( $ currentModel ) { $ parentModelNameSpace = $ currentModel -> getParentModel ( true ) ; $ parentModelName = $ currentModel -> getParentModel ( false ) ; if ( $ parentModelName ) { $ parentModel = new $ parentModelNameSpace ( ) ; foreach ( $ this -> entity -> activeRelations as $ relation ) { $ alias = $ relation -> getAlias ( ) ; if ( $ parentModelName == $ alias || $ parentModelName == $ relation -> getModelName ( ) ) { $ colMap = $ parentModel -> getAllColumns ( false ) ; foreach ( $ colMap as $ field ) { if ( $ fieldName == $ field ) { return ( $ escape == true ? "[$alias]" : $ alias ) ; } } } } $ currentModel = $ parentModel ; } else { $ currentModel = false ; } } return false ; } | Given a particular fieldName look through the current model s column map and see if that particular fieldName appears in it if it does then return the appropriate namespace for this fieldName |
44,858 | public function addEntityWith ( string $ name ) { if ( strstr ( $ this -> entityWith , $ name ) ) { } switch ( $ this -> entityWith ) { case 'none' : $ this -> entityWith = $ name ; break ; case 'all' : break ; default : $ this -> entityWith .= ',' . $ name ; break ; } } | load a supplied with string into the class variable |
44,859 | public function getLimit ( ) { if ( ! is_null ( $ this -> suppliedLimit ) ) { return $ this -> suppliedLimit ; } elseif ( ! is_null ( $ this -> entityLimit ) ) { return $ this -> entityLimit ; } return false ; } | return the correct limit based on set order supplied entity none |
44,860 | public function getOffset ( ) { if ( ! is_null ( $ this -> suppliedOffset ) ) { return $ this -> suppliedOffset ; } elseif ( ! is_null ( $ this -> entityOffset ) ) { return $ this -> entityOffset ; } return false ; } | return the correct offset based on set order supplied entity none |
44,861 | public function getSort ( $ format = 'native' ) { if ( ! is_null ( $ this -> suppliedSort ) ) { $ nativeSort = $ this -> suppliedSort ; } elseif ( ! is_null ( $ this -> entitySort ) ) { $ nativeSort = $ this -> entitySort ; } else { return false ; } if ( $ format == 'sql' ) { $ sortFields = explode ( ',' , $ nativeSort ) ; $ parsedSorts = array ( ) ; foreach ( $ sortFields as $ order ) { if ( substr ( $ order , 0 , 1 ) == '-' ) { $ subOrder = substr ( $ order , 1 ) ; if ( ! empty ( $ subOrder ) ) { $ parsedSorts [ ] = $ subOrder . " DESC" ; } } else { $ parsedSorts [ ] = $ order ; } } $ nativeSort = implode ( ',' , $ parsedSorts ) ; } return $ nativeSort ; } | return the correct sort based on set order supplied entity none |
44,862 | public function getWith ( ) { if ( $ this -> entityWith == 'block' ) { return 'none' ; } if ( $ this -> suppliedWith == 'default' ) { return $ this -> entityWith ; } if ( $ this -> entityWith == 'none' ) { return $ this -> suppliedWith ; } if ( $ this -> entityWith == 'all' or $ this -> suppliedWith == 'all' ) { return 'all' ; } return $ this -> entityWith . ',' . $ this -> suppliedWith ; } | return the correct set of related tables to include |
44,863 | public function getSearchFields ( ) { $ searchFields = array ( ) ; if ( ! isset ( $ this -> entitySearchFields ) and ! isset ( $ this -> suppliedSearchFields ) ) { return false ; } $ sources = array ( 'suppliedSearchFields' , 'entitySearchFields' ) ; foreach ( $ sources as $ source ) { if ( isset ( $ this -> $ source ) ) { foreach ( $ this -> $ source as $ key => $ value ) { $ searchFields [ $ key ] = $ value ; } } } return $ searchFields ; } | entity search fields are always applied and should not be modified by suppliedSearchFields |
44,864 | public function buildSearchParameters ( ) { $ search_parameters = array ( ) ; if ( $ this -> isSearch ) { $ approved_search = array ( ) ; foreach ( $ this -> getSearchFields ( ) as $ field => $ value ) { if ( strstr ( $ value , '*' ) ) { $ value = str_replace ( '*' , '%' , $ value ) ; $ approved_search [ ] = "$field LIKE '$value'" ; } else { if ( strstr ( $ value , '!' ) ) { $ value = str_replace ( '!' , '%' , $ value ) ; $ approved_search [ ] = "$field NOT LIKE '$value'" ; } else { $ approved_search [ ] = "$field='$value'" ; } } } $ search_parameters = array ( implode ( ' and ' , $ approved_search ) ) ; } $ limit = $ this -> getLimit ( ) ; if ( $ limit ) { $ search_parameters [ 'limit' ] = $ limit ; } $ offset = $ this -> getOffset ( ) ; if ( $ offset ) { $ search_parameters [ 'offset' ] = $ offset ; } $ sort = $ this -> getSort ( 'sql' ) ; if ( $ sort ) { $ search_parameters [ 'order' ] = $ sort ; } return $ search_parameters ; } | will apply the configured search parameters and build an array for phalcon consumption |
44,865 | public function mungeData ( $ post , BaseModel $ model ) : \ stdClass { if ( ! isset ( $ post -> attributes ) ) { throw new HTTPException ( 'The API received a malformed request' , 400 , [ 'dev' => 'Bad or incomplete attributes property submitted to the API' , 'code' => '894168146168168168161' ] ) ; } else { $ data = $ post -> attributes ; } if ( isset ( $ post -> id ) ) { $ data -> id = $ post -> id ; } if ( isset ( $ post -> relationships ) ) { $ modelRelations = $ model -> getRelations ( ) ; foreach ( $ modelRelations as $ relation ) { switch ( $ relation -> getType ( ) ) { case PhalconRelation :: HAS_ONE : case PhalconRelation :: BELONGS_TO : $ name = $ relation -> getTableName ( 'singular' ) ; if ( isset ( $ post -> relationships -> $ name ) ) { $ fk = $ relation -> getFields ( ) ; if ( isset ( $ post -> relationships -> $ name -> data -> id ) ) { $ data -> $ fk = $ post -> relationships -> $ name -> data -> id ; } else { } } break ; case PhalconRelation :: HAS_MANY : break ; default : break ; } } } return $ data ; } | will disentangle the mess JSON API submits down to something our API can work with |
44,866 | protected function convertCase ( $ request ) { $ inflector = new Inflector ( ) ; switch ( $ this -> defaultCaseFormat ) { case "snake" : if ( is_object ( $ request ) ) { $ request = $ inflector -> objectPropertiesToSnake ( $ request ) ; } elseif ( is_array ( $ request ) ) { $ request = $ inflector -> arrayKeysToSnake ( $ request ) ; } break ; case "camel" : if ( is_object ( $ request ) ) { $ request = $ inflector -> objectPropertiesToCamel ( $ request ) ; } elseif ( is_array ( $ request ) ) { $ request = $ inflector -> arrayKeysToCamel ( $ request ) ; } break ; default : break ; } return $ request ; } | for a given array of values convert cases to the defaultCaseFormat |
44,867 | public function getJsonProperty ( string $ name , $ filter = 'string' ) { $ filterService = new Filter ( ) ; $ json = $ this -> getJsonRawBody ( ) ; if ( is_object ( $ json ) ) { if ( isset ( $ json -> $ name ) ) { return $ filterService -> sanitize ( $ json -> $ name , $ filter ) ; } else { return null ; } } else { throw new HTTPException ( 'Could not find expected json data.' , 500 , [ 'dev' => json_encode ( $ json ) , 'code' => '894984616161681468764' ] ) ; } } | a simple function to extract a property s value from the JSON post if no match is found then return null |
44,868 | public function getTableName ( $ type = 'plural' ) { $ property = $ type . 'TableName' ; if ( $ this -> $ property == null ) { $ this -> model = $ this -> getModel ( ) ; $ this -> $ property = $ this -> model -> getTableName ( $ type ) ; } return $ this -> $ property ; } | get the table name by passing this along to the underlying model |
44,869 | public function getAlias ( ) { if ( ! isset ( $ this -> alias ) ) { $ options = $ this -> getOptions ( ) ; if ( isset ( $ options [ 'alias' ] ) ) { $ this -> alias = $ options [ 'alias' ] ; } else { $ this -> alias = null ; } } return $ this -> alias ; } | Get the primary model for a relationship |
44,870 | public function getHasOnes ( ) { $ modelNameSpace = $ this -> relation -> getReferencedModel ( ) ; $ list = [ ] ; $ relationships = $ this -> modelManager -> getRelations ( $ modelNameSpace ) ; foreach ( $ relationships as $ relation ) { $ refType = $ relation -> getType ( ) ; if ( $ refType == 1 ) { $ list [ ] = $ relation -> getReferencedModel ( ) ; } } return $ list ; } | get a list of hasOne tables similar to getParent but more inclusive |
44,871 | public function getModel ( ) { if ( $ this -> model == null ) { $ name = $ this -> relation -> getReferencedModel ( ) ; $ this -> model = new $ name ( ) ; } return $ this -> model ; } | ez access to the foreign model depicted by the relationship |
44,872 | public function onConstruct ( ) { $ di = DI :: getDefault ( ) ; $ this -> setDI ( $ di ) ; $ router = $ di -> get ( 'router' ) ; $ matchedRoute = $ router -> getMatchedRoute ( ) ; $ method = $ matchedRoute -> getHttpMethods ( ) ; $ model = $ this -> getModel ( ) ; if ( is_object ( $ model ) ) { switch ( $ method ) { case 'GET' : $ mode = READRULES ; break ; case 'POST' : $ mode = CREATERULES ; break ; case 'PUT' : case 'PATCH' : $ mode = UPDATERULES ; break ; case 'DELETE' : $ mode = DELETERULES ; break ; default : throw new HTTPException ( 'Unsupported operation encountered' , 404 , [ 'dev' => 'Encountered operation: ' . $ method , 'code' => '8914681681681681' ] ) ; break ; } $ modelRuleStore = $ di -> get ( 'ruleList' ) -> get ( $ model -> getModelName ( ) ) ; foreach ( $ modelRuleStore -> getRules ( $ mode , 'DenyRule' ) as $ rule ) { throw new HTTPException ( 'Not authorized to access this end point for this operation:' . $ method , 403 , [ 'dev' => 'You do not have access to the requested resource.' , 'code' => '89494186161681864' ] ) ; } $ this -> getEntity ( ) ; } } | Includes the default Dependency Injector and loads the Entity . |
44,873 | public function atomicMethod ( ... $ args ) { $ di = $ this -> getDI ( ) ; $ router = $ di -> get ( 'router' ) ; $ matchedRoute = $ router -> getMatchedRoute ( ) ; $ handler = $ matchedRoute -> getName ( ) ; $ db = $ di -> get ( 'db' ) ; $ store = $ this -> getDI ( ) -> get ( 'store' ) ; $ db -> begin ( ) ; $ store -> update ( 'transaction_is_atomic' , true ) ; try { $ result = $ this -> { $ handler } ( ... $ args ) ; $ store -> update ( 'rollback_transaction' , false ) ; return $ result ; } catch ( \ Throwable $ e ) { $ store -> update ( 'rollback_transaction' , true ) ; throw $ e ; } } | proxy through which all atomic requests are passed . |
44,874 | public function getModel ( $ modelNameString = false ) { if ( ! $ this -> model ) { $ controllerClass = "\\PhalconRest\Controllers\\" . $ this -> getControllerName ( "singular" ) ; if ( class_exists ( $ controllerClass ) ) { $ controller = new $ controllerClass ( ) ; $ model = $ controller -> getModel ( ) ; if ( $ model ) { $ this -> model = $ model ; } } } if ( ! $ this -> model ) { $ config = $ this -> getDI ( ) -> get ( 'config' ) ; if ( ! $ modelNameString ) { $ modelNameString = $ this -> getControllerName ( ) ; } $ modelName = $ config [ 'namespaces' ] [ 'models' ] . $ modelNameString ; $ this -> model = new $ modelName ( $ this -> di ) ; } return $ this -> model ; } | Load a default model unless one is already in place return the currently loaded model |
44,875 | public function getEntity ( ) { if ( $ this -> entity == false ) { $ config = $ this -> getDI ( ) -> get ( 'config' ) ; $ model = $ this -> getModel ( ) ; $ searchHelper = $ this -> getSearchHelper ( ) ; $ entity = $ config [ 'namespaces' ] [ 'entities' ] . $ this -> getControllerName ( 'singular' ) . 'Entity' ; $ entityPath = $ config [ 'application' ] [ 'entitiesDir' ] . $ this -> getControllerName ( 'singular' ) . 'Entity.php' ; $ defaultEntityNameSpace = $ config [ 'namespaces' ] [ 'defaultEntity' ] ; if ( file_exists ( $ entityPath ) ) { $ entity = new $ entity ( $ model , $ searchHelper ) ; } else { $ entity = new $ defaultEntityNameSpace ( $ model , $ searchHelper ) ; } $ this -> entity = $ this -> configureEntity ( $ entity ) ; } return $ this -> entity ; } | Load a default entity unless a custom version is detected return the currently loaded entity |
44,876 | public function getControllerName ( $ type = 'plural' ) { if ( $ type == 'singular' ) { if ( $ this -> singularName == null ) { $ className = get_called_class ( ) ; $ config = $ this -> getDI ( ) -> get ( 'config' ) ; $ className = str_replace ( $ config [ 'namespaces' ] [ 'controllers' ] , '' , $ className ) ; $ className = str_replace ( 'Controller' , '' , $ className ) ; $ this -> singularName = $ className ; } return $ this -> singularName ; } elseif ( $ type == 'plural' ) { if ( $ this -> pluralName == null ) { $ this -> pluralName = $ this -> getControllerName ( 'singular' ) . 's' ; } return $ this -> pluralName ; } return false ; } | get the controllers singular or plural name |
44,877 | public function getOne ( $ id ) { $ result = $ this -> entity -> findFirst ( $ id ) ; if ( $ result -> countResults ( ) == 0 ) { throw new HTTPException ( 'Resource not available.' , 404 , [ 'dev' => 'The resource you requested is not available.' , 'code' => '43758093745021' ] ) ; } else { return $ result ; } } | run a limited query for one record bypass nearly all normal search params and just search by the primary key |
44,878 | public function post ( ) { $ request = $ this -> getDI ( ) -> get ( 'request' ) ; $ post = $ request -> getJson ( $ this -> getControllerName ( 'singular' ) , $ this -> getModel ( ) ) ; if ( ! $ post ) { throw new HTTPException ( 'There was an error adding new record. Missing POST data.' , 400 , [ 'dev' => 'Invalid data posted to the server' , 'code' => '568136818916816555' ] ) ; } if ( method_exists ( $ this -> model , "getBlockColumns" ) ) { $ blockFields = $ this -> model -> getBlockColumns ( ) ; foreach ( $ blockFields as $ key => $ value ) { unset ( $ post -> $ value ) ; } } $ post = $ this -> beforeSave ( $ post ) ; $ id = $ this -> entity -> save ( $ post ) ; $ this -> afterSave ( $ post , $ id ) ; $ result = $ this -> entity -> findFirst ( $ id ) ; if ( $ result -> countResults ( ) == 0 ) { throw new HTTPException ( 'There was an error retrieving the newly created record.' , 500 , [ 'dev' => 'The resource you requested is not available after it was just created' , 'code' => '1238510381861' ] ) ; } else { return $ result ; } } | Attempt to save a record from POST This should be saving a new record |
44,879 | public function delete ( $ id ) { $ this -> beforeDelete ( $ id ) ; $ this -> entity -> delete ( $ id ) ; $ this -> afterDelete ( $ id ) ; } | Pass through to entity so it can perform extra logic if needed most of the time ... |
44,880 | public function put ( $ id ) { $ request = $ this -> getDI ( ) -> get ( 'request' ) ; $ put = $ request -> getJson ( $ this -> getControllerName ( 'singular' ) , $ this -> model ) ; if ( ! $ put ) { throw new HTTPException ( 'There was an error updating an existing record.' , 500 , [ 'dev' => 'Invalid data posted to the server' , 'code' => '568136818916816' ] ) ; } if ( method_exists ( $ this -> model , "getBlockColumns" ) ) { $ blockFields = $ this -> model -> getBlockColumns ( ) ; foreach ( $ blockFields as $ key => $ value ) { unset ( $ put -> $ value ) ; } } $ put = $ this -> beforeSave ( $ put , $ id ) ; $ id = $ this -> entity -> save ( $ put , $ id ) ; $ this -> afterSave ( $ put , $ id ) ; $ result = $ this -> entity -> findFirst ( $ id ) ; if ( $ result -> countResults ( ) == 0 ) { throw new HTTPException ( 'There was an error retrieving the just updated record.' , 500 , [ 'dev' => 'The resource you requested is not available after it was just updated' , 'code' => '1238510381861' ] ) ; } else { return $ result ; } } | read in a resource and update it |
44,881 | public function matchCurrentRequest ( ) { $ requestMethod = ( isset ( $ _POST [ '_method' ] ) && ( $ _method = strtoupper ( $ _POST [ '_method' ] ) ) && in_array ( $ _method , array ( RequestMethodInterface :: METHOD_PUT , RequestMethodInterface :: METHOD_DELETE ) , true ) ) ? $ _method : $ _SERVER [ 'REQUEST_METHOD' ] ; $ requestUrl = $ _SERVER [ 'REQUEST_URI' ] ; if ( ( $ pos = strpos ( $ requestUrl , '?' ) ) !== false ) { $ requestUrl = substr ( $ requestUrl , 0 , $ pos ) ; } return $ this -> match ( $ requestUrl , $ requestMethod ) ; } | Matches the current request against mapped routes |
44,882 | public function match ( $ requestUrl , $ requestMethod = RequestMethodInterface :: METHOD_GET ) { $ currentDir = dirname ( $ _SERVER [ 'SCRIPT_NAME' ] ) ; foreach ( $ this -> routes -> all ( ) as $ routes ) { if ( ! in_array ( $ requestMethod , ( array ) $ routes -> getMethods ( ) , true ) ) { continue ; } if ( '/' !== $ currentDir ) { $ requestUrl = str_replace ( $ currentDir , '' , $ requestUrl ) ; } $ route = rtrim ( $ routes -> getRegex ( ) , '/' ) ; $ pattern = '@^' . preg_quote ( $ this -> basePath ) . $ route . '/?$@i' ; if ( ! preg_match ( $ pattern , $ requestUrl , $ matches ) ) { continue ; } $ params = array ( ) ; if ( preg_match_all ( '/:([\w-%]+)/' , $ routes -> getUrl ( ) , $ argument_keys ) ) { $ argument_keys = $ argument_keys [ 1 ] ; if ( count ( $ argument_keys ) !== ( count ( $ matches ) - 1 ) ) { continue ; } foreach ( $ argument_keys as $ key => $ name ) { if ( isset ( $ matches [ $ key + 1 ] ) ) { $ params [ $ name ] = $ matches [ $ key + 1 ] ; } } } $ routes -> setParameters ( $ params ) ; $ routes -> dispatch ( ) ; return $ routes ; } return false ; } | Match given request _url and request method and see if a route has been defined for it If so return route s target If called multiple times |
44,883 | public function generate ( $ routeName , array $ params = array ( ) ) { if ( ! isset ( $ this -> namedRoutes [ $ routeName ] ) ) { throw new Exception ( "No route with the name $routeName has been found." ) ; } $ route = $ this -> namedRoutes [ $ routeName ] ; $ url = $ route -> getUrl ( ) ; if ( $ params && preg_match_all ( '/:(\w+)/' , $ url , $ param_keys ) ) { $ param_keys = $ param_keys [ 1 ] ; foreach ( $ param_keys as $ key ) { if ( isset ( $ params [ $ key ] ) ) { $ url = preg_replace ( '/:' . preg_quote ( $ key , '/' ) . '/' , $ params [ $ key ] , $ url , 1 ) ; } } } return $ url ; } | Reverse route a named route |
44,884 | public static function parseConfig ( array $ config ) { $ collection = new RouteCollection ( ) ; foreach ( $ config [ 'routes' ] as $ name => $ route ) { $ collection -> attachRoute ( new Route ( $ route [ 0 ] , array ( '_controller' => str_replace ( '.' , '::' , $ route [ 1 ] ) , 'methods' => $ route [ 2 ] , 'name' => $ name ) ) ) ; } $ router = new Router ( $ collection ) ; if ( isset ( $ config [ 'base_path' ] ) ) { $ router -> setBasePath ( $ config [ 'base_path' ] ) ; } return $ router ; } | Create routes by array and return a Router object |
44,885 | protected function processSomeAttachments ( Collection $ models , array $ attachments ) { $ progress = $ this -> getProgressBar ( $ models ) ; $ progress -> start ( ) ; foreach ( $ models as $ model ) { $ progress -> advance ( ) ; foreach ( $ model -> getAttachedFiles ( ) as $ attachedFile ) { if ( in_array ( $ attachedFile -> name , $ attachments ) ) { $ attachedFile -> reprocess ( ) ; } } } $ progress -> finish ( ) ; } | Process a only a specified subset of stapler attachments . |
44,886 | protected function processAllAttachments ( Collection $ models ) { $ progress = $ this -> getProgressBar ( $ models ) ; $ progress -> start ( ) ; foreach ( $ models as $ model ) { $ progress -> advance ( ) ; foreach ( $ model -> getAttachedFiles ( ) as $ attachedFile ) { $ attachedFile -> reprocess ( ) ; } } $ progress -> finish ( ) ; } | Process all stapler attachments defined on a class . |
44,887 | protected function getProgressBar ( Collection $ models ) { $ output = $ this -> output ? : new NullOutput ( ) ; $ progress = new ProgressBar ( $ output , $ models -> count ( ) ) ; return $ progress ; } | Get an instance of the ProgressBar helper . |
44,888 | public function get ( $ name ) { $ item = $ this -> getItemPath ( $ name ) ; return $ this -> config -> get ( $ item ) ; } | Retrieve a configuration value . |
44,889 | protected function registerStaplerRefreshCommand ( ) { $ this -> app -> bind ( 'stapler.refresh' , function ( $ app ) { $ refreshService = $ app [ 'ImageRefreshService' ] ; return new Commands \ RefreshCommand ( $ refreshService ) ; } ) ; } | Register the stapler refresh command with the container . |
44,890 | protected function loadIndexSchema ( $ name ) { $ index = new IndexSchema ( ) ; $ this -> resolveIndexNames ( $ index , $ name ) ; $ this -> resolveIndexType ( $ index ) ; if ( $ this -> findColumns ( $ index ) ) { return $ index ; } return null ; } | Loads the metadata for the specified index . |
44,891 | protected function resolveIndexType ( $ index ) { $ indexTypes = $ this -> getIndexTypes ( ) ; $ index -> type = array_key_exists ( $ index -> name , $ indexTypes ) ? $ indexTypes [ $ index -> name ] : 'unknown' ; $ index -> isRt = ( $ index -> type == 'rt' ) ; } | Resolves the index name . |
44,892 | public function getIndexSchema ( $ name , $ refresh = false ) { if ( isset ( $ this -> _indexes [ $ name ] ) && ! $ refresh ) { return $ this -> _indexes [ $ name ] ; } $ db = $ this -> db ; $ realName = $ this -> getRawIndexName ( $ name ) ; if ( $ db -> enableSchemaCache && ! in_array ( $ name , $ db -> schemaCacheExclude , true ) ) { $ cache = is_string ( $ db -> schemaCache ) ? Yii :: $ app -> get ( $ db -> schemaCache , false ) : $ db -> schemaCache ; if ( $ cache instanceof Cache ) { $ key = $ this -> getCacheKey ( $ name ) ; if ( $ refresh || ( $ index = $ cache -> get ( $ key ) ) === false ) { $ index = $ this -> loadIndexSchema ( $ realName ) ; if ( $ index !== null ) { $ cache -> set ( $ key , $ index , $ db -> schemaCacheDuration , new TagDependency ( [ 'tags' => $ this -> getCacheTag ( ) , ] ) ) ; } } return $ this -> _indexes [ $ name ] = $ index ; } } return $ this -> _indexes [ $ name ] = $ this -> loadIndexSchema ( $ realName ) ; } | Obtains the metadata for the named index . |
44,893 | public function getIndexSchemas ( $ refresh = false ) { $ indexes = [ ] ; foreach ( $ this -> getIndexNames ( $ refresh ) as $ name ) { if ( ( $ index = $ this -> getIndexSchema ( $ name , $ refresh ) ) !== null ) { $ indexes [ ] = $ index ; } } return $ indexes ; } | Returns the metadata for all indexes in the database . |
44,894 | public function getIndexNames ( $ refresh = false ) { if ( ! isset ( $ this -> _indexNames ) || $ refresh ) { $ this -> initIndexesInfo ( ) ; } return $ this -> _indexNames ; } | Returns all index names in the Sphinx . |
44,895 | public function getIndexTypes ( $ refresh = false ) { if ( ! isset ( $ this -> _indexTypes ) || $ refresh ) { $ this -> initIndexesInfo ( ) ; } return $ this -> _indexTypes ; } | Returns all index types in the Sphinx . |
44,896 | protected function initIndexesInfo ( ) { $ this -> _indexNames = [ ] ; $ this -> _indexTypes = [ ] ; $ indexes = $ this -> findIndexes ( ) ; foreach ( $ indexes as $ index ) { $ indexName = $ index [ 'Index' ] ; $ this -> _indexNames [ ] = $ indexName ; $ this -> _indexTypes [ $ indexName ] = $ index [ 'Type' ] ; } } | Initializes information about name and type of all index in the Sphinx . |
44,897 | public function refresh ( ) { $ cache = is_string ( $ this -> db -> schemaCache ) ? Yii :: $ app -> get ( $ this -> db -> schemaCache , false ) : $ this -> db -> schemaCache ; if ( $ this -> db -> enableSchemaCache && $ cache instanceof Cache ) { TagDependency :: invalidate ( $ cache , $ this -> getCacheTag ( ) ) ; } $ this -> _indexNames = [ ] ; $ this -> _indexes = [ ] ; } | Refreshes the schema . This method cleans up all cached index schemas so that they can be re - created later to reflect the Sphinx schema change . |
44,898 | public function quoteValue ( $ str ) { if ( is_string ( $ str ) ) { return $ this -> db -> getSlavePdo ( ) -> quote ( $ str ) ; } return $ str ; } | Quotes a string value for use in a query . Note that if the parameter is not a string it will be returned without change . |
44,899 | public function quoteIndexName ( $ name ) { if ( strpos ( $ name , '(' ) !== false || strpos ( $ name , '{{' ) !== false ) { return $ name ; } return $ this -> quoteSimpleIndexName ( $ name ) ; } | Quotes a index name for use in a query . If the index name contains schema prefix the prefix will also be properly quoted . If the index name is already quoted or contains ( or {{ then this method will do nothing . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.