idx
int64 0
60.3k
| question
stringlengths 64
4.24k
| target
stringlengths 5
618
|
|---|---|---|
14,000
|
static public function renumberKeysToAvoidLeapsIfKeysAreAllNumeric ( array $ array = array ( ) , $ level = 0 ) { $ level ++ ; $ allKeysAreNumeric = TRUE ; foreach ( array_keys ( $ array ) as $ key ) { if ( is_numeric ( $ key ) === FALSE ) { $ allKeysAreNumeric = FALSE ; break ; } } $ renumberedArray = $ array ; if ( $ allKeysAreNumeric === TRUE ) { $ renumberedArray = array_values ( $ array ) ; } foreach ( $ renumberedArray as $ key => $ value ) { if ( is_array ( $ value ) ) { $ renumberedArray [ $ key ] = self :: renumberKeysToAvoidLeapsIfKeysAreAllNumeric ( $ value , $ level ) ; } } return $ renumberedArray ; }
|
Renumber the keys of an array to avoid leaps is keys are all numeric .
|
14,001
|
public function setInstance ( $ instance ) { $ reflection = new ReflectionClass ( $ instance ) ; $ name = str_replace ( '\\' , ':' , $ reflection -> getName ( ) ) ; $ this -> instances [ $ name ] = $ instance ; }
|
Add new entry in instances .
|
14,002
|
public function get ( $ key ) { if ( isset ( $ this -> factories [ $ key ] ) ) { return $ this -> factories [ $ key ] ( ) ; } if ( ! isset ( $ this -> instances [ $ key ] ) ) { if ( isset ( $ this -> registry [ $ key ] ) ) { $ this -> instances [ $ key ] = $ this -> registry [ $ key ] ( ) ; } else { $ this -> instances [ $ key ] = self :: newInstance ( $ key ) ; } } return $ this -> instances [ $ key ] ; }
|
Get an entry by key
|
14,003
|
public static function newInstance ( $ class ) { $ className = str_replace ( ':' , '\\' , $ class ) ; $ reflectedClass = new ReflectionClass ( $ className ) ; if ( $ reflectedClass -> isInstantiable ( ) ) { $ constructor = $ reflectedClass -> getConstructor ( ) ; if ( $ constructor ) { $ parameters = $ constructor -> getParameters ( ) ; $ constructorParameters = array ( ) ; foreach ( $ parameters as $ parameter ) { if ( $ parameter -> getClass ( ) ) { $ constructorParameters [ ] = self :: newInstance ( $ parameter -> getClass ( ) -> getName ( ) ) ; } else { $ constructorParameters [ ] = $ parameter -> getDefaultValue ( ) ; } } return $ reflectedClass -> newInstanceArgs ( $ constructorParameters ) ; } else { return $ reflectedClass -> newInstance ( ) ; } } else { throw new Exception ( $ class . " is not instantiable Class" ) ; } }
|
An instance factory method
|
14,004
|
public function postAddPhotos ( Request $ request ) { if ( ! $ request -> hasFile ( 'photos' ) ) { return response ( '' , 400 ) ; } foreach ( $ request -> file ( 'photos' ) as $ file ) { $ photo = Photo :: upload ( $ file -> getRealPath ( ) ) ; session ( ) -> push ( 'photos' , [ 'photo_id' => $ photo -> getKey ( ) , 'filename' => $ file -> getClientOriginalName ( ) , ] ) ; } }
|
Process and store several photos .
|
14,005
|
public function postDeletePhoto ( Request $ request ) { if ( session ( ) -> has ( 'photos' ) ) { $ photos = session ( 'photos' ) ; foreach ( $ photos as $ index => $ photo ) { if ( in_array ( $ request -> input ( 'file' ) , $ photo ) ) { $ photo = Photo :: find ( $ photo [ 'photo_id' ] ) ; $ photo -> delete ( ) ; unset ( $ photos [ $ index ] ) ; session ( 'photos' , $ photos ) ; return response ( '' , 200 ) ; } } } return response ( '' , 400 ) ; }
|
Delete a photo .
|
14,006
|
public function actionGetWarehouses ( ) { $ street = $ _GET [ 'street' ] ; $ warehouses = $ this -> getResponse ( 'AddressGeneral' , 'getWarehouses' , [ 'CityName' => $ _GET [ 'CityName' ] ] ) ; $ warehousesByStreet = [ ] ; foreach ( $ warehouses -> data [ 'data' ] as $ warehouse ) { if ( substr_count ( mb_strtolower ( $ warehouse [ 'Description' ] ) , mb_strtolower ( $ street ) ) != 0 || substr_count ( mb_strtolower ( $ warehouse [ 'DescriptionRu' ] ) , mb_strtolower ( $ street ) ) ) { $ warehousesByStreet [ ] = $ warehouse ; } } return json_encode ( $ warehousesByStreet ) ; }
|
Gets warehouses by city and street .
|
14,007
|
public function validateRequestParameters ( $ request , $ amz_client_id ) { $ errors = array ( ) ; $ state = $ request -> getParam ( 'state' , false ) ; $ redirect_uri = $ request -> getParam ( 'redirect_uri' , false ) ; $ client_id = $ request -> getParam ( 'client_id' , false ) ; $ scope = $ request -> getParam ( 'scope' , false ) ; $ response_type = $ request -> getParam ( 'response_type' , false ) ; if ( $ state === false ) { $ errors [ ] = 'state' ; } if ( $ redirect_uri === false ) { $ errors [ ] = 'redirect_uri' ; } if ( $ client_id != $ amz_client_id ) { $ errors [ ] = 'client_id' ; } if ( $ response_type != 'token' ) { $ errors [ ] = 'response_type' ; } if ( count ( $ errors ) ) { throw new InvalidArgumentException ( 'Missing or incorrect parameters: ' . implode ( ', ' , $ errors ) ) ; } else { return [ 'state' => $ state , 'redirect_uri' => $ redirect_uri , 'client_id' => $ client_id , 'scope' => $ scope , 'response_type' => $ response_type , ] ; } }
|
Validate request parameters
|
14,008
|
public function getRedirectLocation ( $ parameters , $ access_token ) { $ location = array ( ) ; array_push ( $ location , $ parameters [ 'redirect_uri' ] . '#state=' . $ parameters [ 'state' ] ) ; array_push ( $ location , 'access_token=' . $ access_token ) ; array_push ( $ location , 'token_type=Bearer' ) ; return implode ( '&' , $ location ) ; }
|
Get redirect location
|
14,009
|
static private function _registerDispatch ( ) { $ auto_dispatch = ! is_null ( Config :: get ( 'router.auto_dispatch' ) ) ? Config :: get ( 'router.auto_dispatch' ) : true ; if ( ! self :: $ _dispatch_registered && $ auto_dispatch ) { register_shutdown_function ( function ( ) { $ response = self :: dispatch ( ) ; } ) ; self :: $ _dispatch_registered = true ; } }
|
Register dispatch function on shutdown
|
14,010
|
static private function _process ( \ Lollipop \ HTTP \ Request $ req , \ Lollipop \ HTTP \ Response $ res ) { if ( is_null ( self :: $ _kernel ) ) { $ active = self :: $ _active_route ; $ top = function ( \ Lollipop \ HTTP \ Request $ req , \ Lollipop \ HTTP \ Response $ res ) use ( $ active ) { return Route :: resolve ( $ active [ 'callback' ] , $ req , $ res , $ active [ 'arguments' ] ) ; } ; self :: $ _kernel = $ top ; } $ start = self :: $ _kernel ; self :: $ _busy = true ; $ new_response = $ start ( $ req , $ res ) ; self :: $ _busy = false ; if ( $ new_response instanceof \ Lollipop \ HTTP \ Response ) { $ res = $ new_response ; } else { $ res -> set ( $ new_response ) ; } return $ res ; }
|
Process middleware stack
|
14,011
|
static private function _getDefaultPageNotFound ( ) { return [ 'path' => '404' , 'callback' => function ( \ Lollipop \ HTTP \ Request $ req , \ Lollipop \ HTTP \ Response $ res , $ args = [ ] ) { $ pagenotfound = '<!DOCTYPE html>' . '<!-- Lollipop for PHP by John Aldrich Bernardo . '<html>' . '<head><title>404 Not Found</title></head>' . '<meta name="viewport" content="width=device-width, initial-scale=1">' . '<body>' . '<h1>404 Not Found</h1>' . '<p>The page that you have requested could not be found.</p>' . '</body>' . '</html>' ; $ response = new Response ( $ pagenotfound ) ; $ response -> header ( 'HTTP/1.0 404 Not Found' ) ; return $ response ; } , 'arguments' => [ ] ] ; }
|
Check if any of routes doesn t match
|
14,012
|
protected function mapAdminRoutes ( ) { $ this -> name ( 'seo.' ) -> prefix ( $ this -> config ( ) -> get ( 'arcanesoft.seo.route.prefix' , 'seo' ) ) -> group ( function ( ) { Routes \ Admin \ DashboardRoutes :: register ( ) ; Routes \ Admin \ PagesRoutes :: register ( ) ; Routes \ Admin \ FootersRoutes :: register ( ) ; Routes \ Admin \ MetasRoutes :: register ( ) ; Routes \ Admin \ RedirectsRoutes :: register ( ) ; Routes \ Admin \ SpammersRoutes :: register ( ) ; Routes \ Admin \ SettingsRoutes :: register ( ) ; } ) ; }
|
Map the admin routes .
|
14,013
|
static function file ( $ key , $ default = null , $ validator = null ) { if ( ! isset ( $ _FILES [ $ key ] ) || $ _FILES [ $ key ] [ 'error' ] != UPLOAD_ERR_OK ) return self :: processError ( $ default ) ; $ file = new InputFile ( $ _FILES [ $ key ] [ 'tmp_name' ] ) ; $ file -> setContentType ( $ _FILES [ $ key ] [ 'type' ] ) ; $ file -> setOriginalName ( $ _FILES [ $ key ] [ 'name' ] ) ; if ( $ validator instanceof Validator ) { if ( $ validator -> execute ( $ file ) ) { return $ file ; } else { return self :: processError ( $ default ) ; } } else if ( is_callable ( $ validator ) ) { try { if ( $ validator ( $ file ) ) { return $ file ; } else { return self :: processError ( $ default ) ; } } catch ( Exception $ e ) { throw FrameworkException :: internalError ( "Validator error" ) ; } } return $ file ; }
|
Get Uploaded File
|
14,014
|
static function set ( $ key , $ value ) { $ me = self :: getInstance ( ) ; $ me -> parameters [ $ key ] = $ value ; }
|
Set Value Manually
|
14,015
|
protected function configureEndpoint ( EndpointInterface $ Endpoint , $ action ) { switch ( $ action ) { case self :: ACTION_AUTH : $ Endpoint = $ this -> configureAuthenticationEndpoint ( $ Endpoint ) ; break ; case self :: ACTION_LOGOUT : $ Endpoint = $ this -> configureLogoutEndpoint ( $ Endpoint ) ; break ; } return $ Endpoint ; }
|
Configure an actions Endpoint Object
|
14,016
|
public static function run ( ) { if ( ! session_id ( ) ) { session_start ( ) ; } $ complementType = self :: getType ( 'strtoupper' ) ; $ path = App :: $ complementType ( ) ; if ( $ paths = File :: getFilesFromDir ( $ path ) ) { foreach ( $ paths as $ path ) { if ( ! $ path -> isDot ( ) && $ path -> isDir ( ) ) { $ _path = Url :: addBackSlash ( $ path -> getPath ( ) ) ; $ slug = $ path -> getBasename ( ) ; $ file = $ _path . $ slug . '/' . $ slug . '.json' ; if ( ! File :: exists ( $ file ) ) { continue ; } self :: load ( $ file ) ; } } } self :: requestHandler ( self :: getType ( 'strtolower' , false ) ) ; }
|
Load all complements found in the directory .
|
14,017
|
public static function load ( $ file ) { $ complement = Json :: fileToArray ( $ file ) ; $ complement [ 'config-file' ] = $ file ; self :: $ id = isset ( $ complement [ 'id' ] ) ? $ complement [ 'id' ] : 'Default' ; $ that = self :: getInstance ( ) ; return $ that -> setComplement ( $ complement ) ; }
|
Load complement configuration from json file and set settings .
|
14,018
|
public static function setCurrentID ( $ id ) { $ type = self :: getType ( ) ; $ appID = App :: getCurrentID ( ) ; if ( array_key_exists ( $ id , self :: $ instances [ $ appID ] [ $ type ] ) ) { self :: $ id = $ id ; return true ; } return false ; }
|
Define the current complement ID .
|
14,019
|
public static function script ( $ pathUrl = null , $ vue = true , $ vueResource = true ) { $ that = self :: getInstance ( ) ; $ file = $ vue ? 'vue+' : '' ; $ file .= $ vueResource ? 'vue-resource+' : '' ; return $ that -> setFile ( $ file . 'eliasis-complement.min' , 'script' , $ pathUrl ) ; }
|
Set and get script url .
|
14,020
|
public static function exists ( $ complementID ) { $ type = self :: getType ( ) ; return array_key_exists ( $ complementID , self :: $ instances [ App :: getCurrentID ( ) ] [ $ type ] ) ; }
|
Check if complement exists .
|
14,021
|
public static function getLibraryVersion ( ) { $ path = self :: getLibraryPath ( ) ; $ composer = Json :: fileToArray ( $ path . 'composer.json' ) ; return isset ( $ composer [ 'version' ] ) ? $ composer [ 'version' ] : '1.1.1' ; }
|
Get library version .
|
14,022
|
protected static function getInstance ( ) { $ type = self :: getType ( ) ; $ appID = App :: getCurrentID ( ) ; $ complementID = self :: getCurrentID ( ) ; $ complement = get_called_class ( ) ; if ( ! isset ( self :: $ instances [ $ appID ] [ $ type ] [ $ complementID ] ) ) { self :: $ instances [ $ appID ] [ $ type ] [ $ complementID ] = new $ complement ( ) ; } return self :: $ instances [ $ appID ] [ $ type ] [ $ complementID ] ; }
|
Get complement instance .
|
14,023
|
public static function fromNative ( ) { $ args = \ func_get_args ( ) ; if ( \ count ( $ args ) != 8 ) { throw new \ BadMethodCallException ( 'You must provide exactly 8 arguments: 1) addressee name, 2) street name, 3) street number, 4) district, 5) city, 6) region, 7) postal code, 8) country code.' ) ; } $ name = new StringLiteral ( $ args [ 0 ] ) ; $ street = new Street ( new StringLiteral ( $ args [ 1 ] ) , new StringLiteral ( $ args [ 2 ] ) ) ; $ district = new StringLiteral ( $ args [ 3 ] ) ; $ city = new StringLiteral ( $ args [ 4 ] ) ; $ region = new StringLiteral ( $ args [ 5 ] ) ; $ postalCode = new StringLiteral ( $ args [ 6 ] ) ; $ country = Country :: fromNative ( $ args [ 7 ] ) ; return new self ( $ name , $ street , $ district , $ city , $ region , $ postalCode , $ country ) ; }
|
Returns a new Address from native PHP arguments
|
14,024
|
public function sameValueAs ( ValueObjectInterface $ address ) { if ( false === Util :: classEquals ( $ this , $ address ) ) { return false ; } return $ this -> getName ( ) -> sameValueAs ( $ address -> getName ( ) ) && $ this -> getStreet ( ) -> sameValueAs ( $ address -> getStreet ( ) ) && $ this -> getDistrict ( ) -> sameValueAs ( $ address -> getDistrict ( ) ) && $ this -> getCity ( ) -> sameValueAs ( $ address -> getCity ( ) ) && $ this -> getRegion ( ) -> sameValueAs ( $ address -> getRegion ( ) ) && $ this -> getPostalCode ( ) -> sameValueAs ( $ address -> getPostalCode ( ) ) && $ this -> getCountry ( ) -> sameValueAs ( $ address -> getCountry ( ) ) ; }
|
Tells whether two Address are equal
|
14,025
|
public function setMessage ( $ data ) { if ( ! isset ( $ _SESSION [ 'flash' ] ) ) { $ _SESSION [ 'flash' ] = array ( ) ; } if ( ! in_array ( $ data [ 'type' ] , $ this -> valid ) ) { $ data [ 'type' ] = $ this -> valid [ 0 ] ; } $ _SESSION [ 'flash' ] [ 'type' ] = $ data [ 'type' ] ; $ _SESSION [ 'flash' ] [ 'message' ] = $ data [ 'message' ] ; return true ; }
|
Set the message into session variable
|
14,026
|
public function datatableRenderHtml ( Twig_Environment $ twig , AbstractDatatableView $ datatable ) { return $ twig -> render ( 'SgDatatablesBundle:Datatable:datatable_html.html.twig' , $ this -> getOptions ( $ datatable ) ) ; }
|
Renders the html template .
|
14,027
|
public function datatableRenderJs ( Twig_Environment $ twig , AbstractDatatableView $ datatable ) { return $ twig -> render ( 'SgDatatablesBundle:Datatable:datatable_js.html.twig' , $ this -> getOptions ( $ datatable ) ) ; }
|
Renders the js template .
|
14,028
|
public function datatableFilterRender ( Twig_Environment $ twig , AbstractDatatableView $ datatable , AbstractColumn $ column , $ loopIndex ) { if ( $ filterProperty = $ column -> getFilter ( ) -> getProperty ( ) ) { $ filterColumnId = $ datatable -> getColumnIdByColumnName ( $ filterProperty ) ; } else { $ filterColumnId = $ loopIndex ; } return $ twig -> render ( $ column -> getFilter ( ) -> getTemplate ( ) , array ( 'column' => $ column , 'filterColumnId' => $ filterColumnId , 'selectorId' => $ loopIndex , 'tableId' => $ datatable -> getName ( ) ) ) ; }
|
Renders the custom datatable filter .
|
14,029
|
public function datatableIcon ( Twig_Environment $ twig , $ icon , $ label = '' ) { if ( $ icon ) return $ twig -> render ( 'SgDatatablesBundle:Action:icon.html.twig' , array ( 'icon' => $ icon , 'label' => $ label ) ) ; else return $ label ; }
|
Renders icon && label .
|
14,030
|
protected function registerChildShutdown ( ) { $ ipc = $ this -> ipc ; register_shutdown_function ( function ( ) use ( $ ipc ) { $ error = error_get_last ( ) ; if ( $ error && isset ( $ error [ 'type' ] ) && in_array ( $ error [ 'type' ] , array ( E_ERROR , E_PARSE , E_CORE_ERROR , E_COMPILE_ERROR ) ) ) { $ ipc -> put ( new ExceptionDataHolder ( new \ ErrorException ( $ error [ 'message' ] , 0 , $ error [ 'type' ] , $ error [ 'file' ] , $ error [ 'line' ] ) ) ) ; } } ) ; register_shutdown_function ( function ( ) { posix_kill ( getmypid ( ) , SIGKILL ) ; } ) ; }
|
Avoids the closing of resources in child process
|
14,031
|
public static function addListener ( $ callback , $ eventName , $ priority = EventPriority :: NORMAL ) { if ( EventPriority :: getPriority ( $ priority ) == false ) { throw new EventException ( 'Can not add listener: Unknown priority ' . $ priority , 1 ) ; } if ( ! is_callable ( $ callback ) ) { throw new EventException ( "Can not add listener: Callback is not callable" , 1 ) ; } if ( empty ( $ eventName ) ) { throw new EventException ( "Can not add listener: No eventname provided" , 1 ) ; } if ( ! isset ( self :: $ listeners [ $ eventName ] ) ) { self :: $ listeners [ $ eventName ] = array ( ) ; } if ( ! isset ( self :: $ listeners [ $ eventName ] [ $ priority ] ) ) { self :: $ listeners [ $ eventName ] [ $ priority ] = array ( ) ; } if ( func_num_args ( ) > 3 ) { $ args = array_slice ( func_get_args ( ) , 3 ) ; } else { $ args = array ( ) ; } self :: $ listeners [ $ eventName ] [ $ priority ] [ ] = array ( $ callback , $ args ) ; }
|
Adds a function as listener .
|
14,032
|
public static function removeListener ( $ callback , $ eventName , $ priority = EventPriority :: NORMAL ) { if ( EventPriority :: getPriority ( $ priority ) == false ) { throw new EventException ( 'Unknown priority ' . $ priority ) ; } if ( ! isset ( self :: $ listeners [ $ eventName ] ) || ! isset ( self :: $ listeners [ $ eventName ] [ $ priority ] ) ) { return ; } foreach ( self :: $ listeners [ $ eventName ] [ $ priority ] as $ i => $ _callback ) { if ( $ _callback [ 0 ] == $ callback ) { unset ( self :: $ listeners [ $ eventName ] [ $ priority ] [ $ i ] ) ; return ; } } }
|
Removes a function as listener .
|
14,033
|
public function getDataTransferObjectName ( $ object ) { $ objectName = TypeHandling :: getTypeForValue ( $ object ) ; if ( ! array_key_exists ( $ objectName , $ this -> classMappingConfiguration ) ) { foreach ( array_reverse ( $ this -> classNameToDtoClassNameReplaceFragments , TRUE ) as $ dtoClassNameFragment => $ classNameFragment ) { $ dtoClassName = str_replace ( $ classNameFragment , $ dtoClassNameFragment , $ objectName ) ; if ( class_exists ( $ dtoClassName ) ) { $ this -> classMappingConfiguration [ $ objectName ] = $ dtoClassName ; break ; } } } if ( ! isset ( $ this -> classMappingConfiguration [ $ objectName ] ) ) { throw new InvalidTargetException ( sprintf ( 'There is no DTO class name for "%s" objects.' , $ objectName ) , 1407499486 ) ; } return $ this -> classMappingConfiguration [ $ objectName ] ; }
|
Returns the class name of the given DataTransferObject .
|
14,034
|
public function getDataTransferObject ( $ object ) { if ( $ object === NULL ) { return NULL ; } $ identifier = $ this -> persistenceManager -> getIdentifierByObject ( $ object ) ; $ dto = $ this -> propertyMapper -> convert ( $ identifier , $ this -> getDataTransferObjectName ( $ object ) ) ; return $ dto ; }
|
Returns a DataTransferObject for the given object name .
|
14,035
|
public function pushClassNameToDtoClassNameReplaceFragments ( array $ classNameToDtoClassNameReplaceFragments , $ mergeWithExistingFragments = TRUE ) { array_push ( $ this -> classNameToDtoClassNameReplaceFragmentsStack , $ this -> classNameToDtoClassNameReplaceFragments ) ; array_push ( $ this -> classMappingConfigurationStack , $ this -> classMappingConfiguration ) ; $ this -> classNameToDtoClassNameReplaceFragments = \ Netlogix \ Crud \ Utility \ ArrayUtility :: arrayMergeRecursiveOverrule ( $ mergeWithExistingFragments ? $ this -> classNameToDtoClassNameReplaceFragments : array ( ) , $ classNameToDtoClassNameReplaceFragments ) ; }
|
Register new class name fragments
|
14,036
|
public function popClassNameToDtoClassNameReplaceFragments ( ) { $ this -> classMappingConfiguration = array_pop ( $ this -> classMappingConfigurationStack ) ; $ this -> classNameToDtoClassNameReplaceFragments = array_pop ( $ this -> classNameToDtoClassNameReplaceFragmentsStack ) ; }
|
Restore old class name fragment settings
|
14,037
|
private function translateData ( ) : void { foreach ( $ this -> db -> data as $ key => $ value ) { $ this -> data [ $ key ] = $ value ; } }
|
Transform clean SQL data to normal data
|
14,038
|
public function setData ( string $ key , $ value ) : bool { if ( $ key !== 'password' || $ key !== 'salt' || $ key !== 'remember_md' ) { $ this -> data [ $ key ] = $ value ; return true ; } else { return false ; } }
|
Set any other field from the table
|
14,039
|
public function getData ( string $ key ) { return ( $ key !== 'password' || $ key !== 'salt' || $ key !== 'remember_me' ) ? $ this -> data [ $ key ] : false ; }
|
Get any other field from the table Will return false is key password salt or remember_me is accessed
|
14,040
|
public function postCacheTranslateObject ( ModelObject $ obj ) { if ( strpos ( $ obj -> Path , $ this -> rootPath ) === FALSE ) $ obj -> setPath ( $ this -> rootPath . DIRECTORY_SEPARATOR . $ obj -> Path ) ; return $ obj ; }
|
Sets the path and returns the object
|
14,041
|
public function param ( $ name , $ value ) { if ( is_integer ( $ name ) ) { if ( array_key_exists ( $ name , $ this -> pathParamNames ) ) { $ this -> path [ $ this -> pathParamNames [ $ name ] ] = $ value ; return $ this ; } throw new \ OutOfBoundsException ( sprintf ( 'No path param at position %u' , $ name ) ) ; } if ( in_array ( $ name , $ this -> pathParamNames , true ) ) { $ this -> path [ ( string ) $ name ] = $ value ; return $ this ; } $ this -> query [ ( string ) $ name ] = $ value ; return $ this ; }
|
Assign a value to a path or query param depending on the URI pattern checking the name of the param .
|
14,042
|
public function pathParam ( $ name , $ value ) { if ( is_integer ( $ name ) ) { if ( array_key_exists ( $ name , $ this -> pathParamNames ) ) { $ this -> path [ $ this -> pathParamNames [ $ name ] ] = $ value ; return $ this ; } throw new \ OutOfBoundsException ( sprintf ( 'Path param %u not found in pattern "%s"' , $ name , $ this -> uri ) ) ; } if ( in_array ( $ name , $ this -> pathParamNames , true ) ) { $ this -> path [ ( string ) $ name ] = $ value ; return $ this ; } throw new \ OutOfBoundsException ( sprintf ( 'Path param "%s" not found in pattern "%s"' , $ name , $ this -> uri ) ) ; }
|
Assign a value to a path param .
|
14,043
|
public function queryParam ( $ name , $ value ) { if ( $ value === NULL ) { unset ( $ this -> query [ ( string ) $ name ] ) ; } else { $ this -> query [ ( string ) $ name ] = $ value ; } return $ this ; }
|
Assign a value to a query param assigning a NULL value will remove the query param .
|
14,044
|
public function queryParams ( array $ query ) { $ this -> query = Arrays :: mergeDeep ( $ this -> query , $ query ) ; return $ this ; }
|
Merges query params recursively .
|
14,045
|
public function setParams ( array $ params ) { $ this -> path = [ ] ; $ this -> query = [ ] ; foreach ( $ params as $ k => $ v ) { if ( is_integer ( $ k ) ) { if ( array_key_exists ( $ k , $ this -> pathParamNames ) ) { $ this -> path [ $ this -> pathParamNames [ $ k ] ] = $ v ; continue ; } throw new \ OutOfBoundsException ( sprintf ( 'No path param at position %u' , $ k ) ) ; } if ( in_array ( $ k , $ this -> pathParamNames , true ) ) { $ this -> path [ $ k ] = $ v ; continue ; } $ this -> query [ $ k ] = $ v ; } return $ this ; }
|
Removes all param values from path and query and re - populates using the given values .
|
14,046
|
public function fragment ( $ fragment ) { $ this -> fragment = ( $ fragment === NULL || $ fragment == '' ) ? NULL : ( string ) $ fragment ; return $ this ; }
|
Set or remove the fragment part of this URI .
|
14,047
|
public function build ( $ trailingSlash = false ) { $ result = '' ; foreach ( preg_split ( "'(\\{(?:(?>[^\\{\\}]+)|(?R))+\\})'S" , $ this -> uri , - 1 , PREG_SPLIT_DELIM_CAPTURE ) as $ part ) { if ( substr ( $ part , 0 , 1 ) == '{' ) { $ result .= Uri :: encode ( $ this -> path [ substr ( $ part , 1 , - 1 ) ] ) ; } else { $ result .= $ part ; } } $ result = $ this -> replaceParams ( $ this -> uri , $ this -> path ) ; if ( $ trailingSlash && substr ( $ result , - 1 ) != '/' ) { $ uri = new Uri ( $ result . '/' ) ; } else { $ uri = new Uri ( $ result ) ; } if ( ! empty ( $ this -> query ) ) { $ uri = $ uri -> setQuery ( $ this -> query ) ; } if ( $ this -> fragment !== NULL ) { if ( false === strpos ( $ this -> fragment , '{' ) ) { $ uri = $ uri -> setFragment ( $ this -> fragment ) ; } else { $ uri = $ uri -> setFragment ( $ this -> replaceParams ( $ this -> fragment , $ this -> path ) ) ; } } return $ uri ; }
|
Build a URI from template and assigned parameters .
|
14,048
|
final protected function _formatLocation ( $ file , $ line , $ format = self :: LOG_FORMAT ) { return sprintf ( $ format , $ file , $ line ) ; }
|
formats the location from backtrace using sprintf
|
14,049
|
final protected function _convert ( $ object ) { if ( ! is_object ( $ object ) ) { return $ object ; } $ this -> _processed [ ] = $ object ; $ object_as_array = array ( ) ; $ object_as_array [ ' class_name' ] = get_class ( $ object ) ; $ object_vars = get_object_vars ( $ object ) ; foreach ( $ object_vars as $ key => $ value ) { if ( $ value === $ object || in_array ( $ value , $ this -> _processed , true ) ) { $ value = 'recursion - parent object [' . get_class ( $ value ) . ']' ; } $ object_as_array [ $ key ] = $ this -> _convert ( $ value ) ; } $ reflection = new \ ReflectionClass ( $ object ) ; foreach ( $ reflection -> getProperties ( ) as $ property ) { if ( array_key_exists ( $ property -> getName ( ) , $ object_vars ) ) { continue ; } $ type = $ this -> _getPropertyKey ( $ property ) ; if ( $ this -> _php_version >= 5.3 ) { $ property -> setAccessible ( true ) ; } try { $ value = $ property -> getValue ( $ object ) ; } catch ( \ ReflectionException $ e ) { $ value = 'only PHP 5.3 can access private/protected properties' ; } if ( $ value === $ object || in_array ( $ value , $ this -> _processed , true ) ) { $ value = 'recursion - parent object [' . get_class ( $ value ) . ']' ; } $ object_as_array [ $ type ] = $ this -> _convert ( $ value ) ; } return $ object_as_array ; }
|
converts an object to a better format for logging
|
14,050
|
final protected function _getPropertyKey ( \ ReflectionProperty $ property ) { $ static = $ property -> isStatic ( ) ? ' static' : '' ; if ( $ property -> isPublic ( ) ) { return 'public' . $ static . ' ' . $ property -> getName ( ) ; } if ( $ property -> isProtected ( ) ) { return 'protected' . $ static . ' ' . $ property -> getName ( ) ; } if ( $ property -> isPrivate ( ) ) { return 'private' . $ static . ' ' . $ property -> getName ( ) ; } }
|
takes a reflection property and returns a nicely formatted key of the property name
|
14,051
|
public function addCachingHeaders ( $ numberOfMinutes = 60 , $ mustRevalidate = true ) { $ numberOfSeconds = $ numberOfMinutes * 60 ; $ header = "Cache-Control: public, max-age=" . ( $ numberOfSeconds ) ; if ( $ mustRevalidate ) $ header .= ", must-revalidate" ; header ( $ header ) ; $ expStr = "Expires: " . gmdate ( "D, d M Y H:i:s" , time ( ) + $ numberOfSeconds ) . " GMT" ; header ( $ expStr ) ; $ lastModified = "Last-Modified: " . gmdate ( "D, d M Y H:i:s" , time ( ) ) . " GMT" ; header ( $ lastModified ) ; header_remove ( "Pragma" ) ; $ etag = '"' . filemtime ( __FILE__ ) . '.' . date ( "U" ) . '"' ; header ( "ETag: $etag" ) ; }
|
Add caching headers to the current request .
|
14,052
|
function autoresolve ( $ symbol ) { if ( \ array_key_exists ( $ symbol , $ this -> state [ 'aliases' ] ) ) { $ this -> autoresolve ( $ this -> state [ 'aliases' ] [ $ symbol ] ) ; $ this -> class_alias ( $ this -> state [ 'aliases' ] [ $ symbol ] , $ symbol ) ; return true ; } if ( \ array_key_exists ( $ symbol , $ this -> state [ 'symbols' ] ) ) { $ this -> requirefile ( $ this -> state [ 'symbols' ] [ $ symbol ] ) ; return true ; } return false ; }
|
Attempt to auto - resolve a symbol based on past state .
|
14,053
|
function save ( ) { if ( $ this -> cacheConf [ 'type' ] == 'noop' ) { } else { $ stateCopy = $ this -> state ; $ stateCopy [ 'loaded' ] = [ ] ; if ( $ this -> cacheConf [ 'type' ] == 'file' ) { $ username = \ get_current_user ( ) ; $ cacheDir = realpath ( $ this -> syspath . '/' . \ trim ( $ this -> cacheConf [ 'path' ] , '\\/' ) ) ; $ cachePath = $ cacheDir . '/freia.' . ( \ php_sapi_name ( ) === 'cli' ? 'cli' : 'server' ) . '.' . $ username . '.symbols.json' ; if ( $ this -> file_exists ( $ cacheDir ) ) { try { $ this -> file_put_contents ( $ cachePath , \ json_encode ( $ stateCopy , JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) ) ; if ( ! $ this -> chmod ( $ cachePath , $ this -> filePermission ( ) ) ) { $ this -> error_log ( "Unable to set permissions on cache file: $cachePath" ) ; } } catch ( \ Exception $ e ) { $ this -> error_log ( 'Failed to save state to cache file [' . $ cachePath . '] Error: ' . $ e -> getMessage ( ) ) ; } } else { $ this -> error_log ( 'Missing cache directory: ' . $ this -> cacheConf [ 'path' ] ) ; } } else if ( $ this -> cacheConf [ 'type' ] == 'memcached' ) { $ mc = $ this -> memcachedInstance ( ) ; $ success = $ mc -> set ( 'freia-symbols' , $ stateCopy , time ( ) + 604800 ) ; if ( ! $ success ) { $ this -> error_log ( "Memcached failed to store key freia-symbols, code: " . $ mc -> getResultCode ( ) ) ; } } } }
|
Save current state to persistent store
|
14,054
|
function load ( ) { if ( $ this -> cacheConf [ 'type' ] == 'noop' ) { return null ; } else { $ loadedState = null ; if ( $ this -> cacheConf [ 'type' ] == 'file' ) { $ username = \ get_current_user ( ) ; $ cacheDir = realpath ( $ this -> syspath . '/' . \ trim ( $ this -> cacheConf [ 'path' ] , '\\/' ) ) ; $ cachePath = $ cacheDir . '/freia.' . ( \ php_sapi_name ( ) === 'cli' ? 'cli' : 'server' ) . '.' . $ username . '.symbols.json' ; if ( $ this -> file_exists ( $ cachePath ) ) { try { $ loadedState = \ json_decode ( $ this -> file_get_contents ( $ cachePath ) , true ) ; } catch ( \ Exception $ e ) { $ this -> error_log ( 'Failed to load cache file: ' . $ cachePath ) ; return null ; } } else { return null ; } } else if ( $ this -> cacheConf [ 'type' ] == 'memcached' ) { $ mc = $ this -> memcachedInstance ( ) ; try { $ loadedState = $ mc -> get ( 'freia-symbols' ) ; } catch ( \ Exception $ e ) { $ loadedState = null ; } } if ( $ loadedState == null ) { return null ; } if ( $ loadedState [ 'version' ] == $ this -> state [ 'version' ] ) { return $ loadedState ; } else { return null ; } } }
|
Load state from persistent store
|
14,055
|
public static function castFrom ( $ value ) : InputStream { if ( $ value instanceof InputStream ) { return $ value ; } if ( is_string ( $ value ) ) { return new self ( $ value ) ; } throw new \ InvalidArgumentException ( 'Given value is neither an instance of' . InputStream :: class . ' nor a string denoting a file' ) ; }
|
casts given value to an input stream
|
14,056
|
protected function getResourceLength ( ) : int { if ( null === $ this -> fileName ) { return parent :: getResourceLength ( ) ; } if ( substr ( $ this -> fileName , 0 , 16 ) === 'compress.zlib://' ) { return filesize ( substr ( $ this -> fileName , 16 ) ) ; } elseif ( substr ( $ this -> fileName , 0 , 17 ) === 'compress.bzip2://' ) { return filesize ( substr ( $ this -> fileName , 17 ) ) ; } return parent :: getResourceLength ( ) ; }
|
helper method to retrieve the length of the resource
|
14,057
|
public function tell ( ) : int { if ( null === $ this -> handle ) { throw new \ LogicException ( 'Can not read from closed input stream.' ) ; } $ position = @ ftell ( $ this -> handle ) ; if ( false === $ position ) { throw new StreamException ( 'Can not read current position in file: ' . lastErrorMessage ( 'unknown error' ) ) ; } return $ position ; }
|
return current position
|
14,058
|
public function checkForToken ( Request $ request ) { if ( ! $ this -> auth -> parser ( ) -> setRequest ( $ request ) -> hasToken ( ) ) { throw new UnauthorizedHttpException ( 'jwTauth' , 'Token not provided' ) ; } }
|
Check the request for the presence of a token .
|
14,059
|
function addDecoratedMethod ( MethodReflection $ sourceMethod , MethodReflection $ decoratorMethodReflection ) { $ weavedMethod = MethodGenerator :: fromReflection ( $ sourceMethod ) ; $ newBody = $ decoratorMethodReflection -> getBody ( ) ; $ newBody = trimBody ( $ newBody ) ; $ parameters = $ sourceMethod -> getParameters ( ) ; $ paramArray = [ ] ; $ searchArray = [ ] ; $ count = 0 ; foreach ( $ parameters as $ parameter ) { $ searchArray [ ] = '$param' . $ count ; $ paramArray [ ] = '$' . $ parameter -> getName ( ) ; } $ paramList = implode ( ', ' , $ paramArray ) ; $ newBody = str_replace ( '$this->__prototype()' , '$this->weavedInstance->' . $ sourceMethod -> getName ( ) . "($paramList)" , $ newBody ) ; $ newBody = str_replace ( $ searchArray , $ paramArray , $ newBody ) ; $ weavedMethod -> setBody ( $ newBody ) ; $ this -> generator -> addMethodFromGenerator ( $ weavedMethod ) ; }
|
Decorate the method and call the instance .
|
14,060
|
function addPlainMethod ( MethodReflection $ sourceMethod ) { $ parameters = $ sourceMethod -> getParameters ( ) ; $ paramArray = [ ] ; foreach ( $ parameters as $ parameter ) { $ paramArray [ ] = '$' . $ parameter -> getName ( ) ; } $ paramList = implode ( ', ' , $ paramArray ) ; $ weavedMethod = MethodGenerator :: fromReflection ( $ sourceMethod ) ; $ body = sprintf ( " return \$this->%s->%s(%s);" , $ this -> implementWeaveInfo -> getInstancePropertyName ( ) , $ sourceMethod -> getName ( ) , $ paramList ) ; $ weavedMethod -> setBody ( $ body ) ; $ this -> generator -> addMethodFromGenerator ( $ weavedMethod ) ; }
|
Add a call to the instance method .
|
14,061
|
function addSourceMethods ( ) { $ methodBindingArray = $ this -> implementWeaveInfo -> getMethodBindingArray ( ) ; $ methods = $ this -> sourceClassReflection -> getMethods ( ) ; foreach ( $ methods as $ sourceMethod ) { if ( $ sourceMethod -> getName ( ) === '__construct' ) { continue ; } $ methodBindingToApply = null ; foreach ( $ methodBindingArray as $ methodBinding ) { if ( $ methodBinding -> matchesMethod ( $ sourceMethod -> getName ( ) ) ) { $ methodBindingToApply = $ methodBinding ; break ; } } if ( $ methodBindingToApply != null ) { $ decoratorMethod = $ methodBindingToApply -> getMethod ( ) ; $ decoratorMethodReflection = $ this -> decoratorReflection -> getMethod ( $ decoratorMethod ) ; $ this -> addDecoratedMethod ( $ sourceMethod , $ decoratorMethodReflection ) ; } else { $ this -> addPlainMethod ( $ sourceMethod ) ; } } }
|
For all of the methods in that need to be decorated generate the decorated version and all the to the generator .
|
14,062
|
public function getSpentBackgroundPoints ( ) : PositiveIntegerObject { if ( $ this -> spentBackgroundPoints === null ) { $ this -> spentBackgroundPoints = new PositiveIntegerObject ( $ this -> getValue ( ) ) ; } return $ this -> spentBackgroundPoints ; }
|
Spent background points are the same as advantage level .
|
14,063
|
public function addClass ( ResponsiveImageClass $ class ) { $ this -> classes_added = true ; if ( array_key_exists ( $ class -> getName ( ) , $ this -> classes ) ) { throw new \ Exception ( sprintf ( 'A responsive image class with name "%s" is already registered' , $ class -> getName ( ) ) ) ; } if ( $ this -> default_filters instanceof FilterInterface ) { $ class -> addFilter ( $ this -> default_filters ) ; } if ( $ this -> default_post_filters instanceof FilterInterface ) { $ class -> addPostFilter ( $ this -> default_post_filters ) ; } if ( $ this -> default_scaling_algorithm != '' ) { $ class -> setScaleAlgorithm ( $ this -> default_scaling_algorithm ) ; } if ( $ this -> default_output_type_map instanceof OutputTypeMap ) { $ class -> setOutputTypeMap ( $ this -> default_output_type_map ) ; } $ this -> classes [ $ class -> getName ( ) ] = $ class ; }
|
Add a ResponsiveImageClass object to the registered responsive image classes
|
14,064
|
public function getClass ( $ classname ) { if ( ( string ) $ classname == '' || ! array_key_exists ( $ classname , $ this -> classes ) ) { throw new ImageClassNotRegisteredException ( $ classname ) ; } return $ this -> classes [ $ classname ] ; }
|
Get a ResponsiveImageClass by it s name
|
14,065
|
public function makeImgElementResponsive ( \ DOMElement & $ img , $ class , $ change_src_attr = false , $ add_default_dimension_attrs = false ) { if ( $ img -> tagName != 'img' ) throw new \ InvalidArgumentException ( '$img must be an "img" element' ) ; if ( ( string ) $ class == '' || ! array_key_exists ( $ class , $ this -> classes ) ) { throw new ImageClassNotRegisteredException ( $ class ) ; } $ imageurl = $ img -> getAttribute ( 'src' ) ; if ( $ imageurl != '' ) { try { $ ri = $ this -> getResponsiveImage ( $ imageurl , $ class ) ; $ img -> setAttribute ( 'srcset' , $ ri -> getSrcsetAttributeValue ( ) ) ; $ img -> setAttribute ( 'sizes' , $ ri -> getSizesAttributeValue ( ) ) ; $ default = $ ri -> getDefaultImageInfo ( ) ; if ( $ default instanceof WebImageInfo ) { if ( $ change_src_attr ) { $ img -> setAttribute ( 'src' , $ default -> getUrl ( ) ) ; } if ( $ add_default_dimension_attrs ) { $ img -> setAttribute ( 'width' , $ default -> getWidth ( ) ) ; $ img -> setAttribute ( 'height' , $ default -> getHeight ( ) ) ; } } } catch ( \ Exception $ e ) { } ; } }
|
Add srcset and sizes attributes to an HTML img tag
|
14,066
|
public function createResizedImageVersions ( $ imageurl , $ imageclass ) { if ( ! $ this -> resizer instanceof ImageResizer ) { throw new \ LogicException ( 'no ImageResizer available, set it using ResponsiveImageHelper::setResizer()' ) ; } $ image = $ this -> getResponsiveImage ( $ imageurl , $ imageclass ) ; $ image -> createResizedVersions ( $ this -> resizer ) ; }
|
Create the resized image versions for an image and a given image class
|
14,067
|
protected function _createException ( $ message = null , $ code = null , $ previous = null ) { return new Exception ( $ message , $ code , $ previous ) ; }
|
Creates a new basic Dhii exception .
|
14,068
|
public function postLoad ( Page $ page , LifecycleEventArgs $ args ) { $ hookManager = $ this -> container -> get ( 'mm_cmf_content.page_hook_manager' ) ; foreach ( $ hookManager -> getHooks ( ) as $ hook ) { $ hook -> process ( $ page , $ this -> container -> get ( 'request_stack' ) -> getCurrentRequest ( ) ) ; } ; }
|
postLoad Callback for Page entity gets all defined PageHooks and calls it
|
14,069
|
public function getCss ( ) { switch ( $ this -> type ) { case self :: TYPE_ERROR : $ css = 'danger' ; break ; case self :: TYPE_WARNING : $ css = 'warning' ; break ; case self :: TYPE_INFO : $ css = 'info' ; break ; case self :: TYPE_SUCCESS : $ css = 'success' ; break ; default : $ css = 'info' ; break ; } return $ css ; }
|
Get css used .
|
14,070
|
public function getHeader ( ) { switch ( $ this -> type ) { case self :: TYPE_ERROR : $ header = 'Error!' ; break ; case self :: TYPE_WARNING : $ header = 'Warning!' ; break ; case self :: TYPE_INFO : $ header = 'Info' ; break ; case self :: TYPE_SUCCESS : $ header = 'Success' ; break ; default : $ header = 'Info' ; break ; } return $ header ; }
|
Get header title .
|
14,071
|
public function match ( $ url = null ) { $ match = parent :: match ( $ url ) ; $ find = $ this -> replaceParameters ( ) ; if ( false !== $ find || true === $ match ) { return true ; } else { return false ; } }
|
make the match
|
14,072
|
private function resolvePregCallback ( $ finded ) { $ matchEx = explode ( ' ' , $ this -> getMatchUrl ( ) ) ; $ requestEx = explode ( ' ' , $ this -> getRequestedUrl ( ) ) ; $ key = array_search ( $ finded [ 0 ] , $ matchEx ) ; $ cln = $ finded [ 1 ] ; if ( strstr ( $ cln , ':' ) ) { list ( $ cln , $ filter ) = explode ( ':' , $ cln ) ; } if ( ! strstr ( $ cln , '?' ) ) { $ add = isset ( $ requestEx [ $ key ] ) && $ requestEx [ $ key ] !== '' ? $ requestEx [ $ key ] : false ; } else { $ add = isset ( $ requestEx [ $ key ] ) ? $ requestEx [ $ key ] : null ; } if ( $ add !== null ) { if ( ! $ this -> runFilter ( isset ( $ filter ) ? $ filter : $ cln , $ add ) ) { throw new FilterMatchException ( 'Your filter do not match' ) ; } } $ this -> parameters [ $ cln ] = $ add ; }
|
resolve the preg callback
|
14,073
|
private function runFilter ( $ filter , $ parameter ) { if ( ! strstr ( $ filter , '(' ) && ! strstr ( $ filter , ')' ) ) { if ( ! $ filter = $ this -> getFilter ( $ filter ) ) { return false ; } } return preg_match ( '@' . $ filter . '@si' , $ parameter ) ? : false ; }
|
execute a filter
|
14,074
|
public function depend ( $ entity , $ type ) { $ depend = $ type === 'count' ? 0 : [ ] ; foreach ( static :: _dependent ( ) as $ model ) { $ results = $ model :: find ( $ type , [ 'conditions' => [ 'tags' => $ entity -> name ] ] ) ; if ( ! $ results ) { continue ; } if ( $ type === 'count' ) { $ depend += $ results ; } else { foreach ( $ results as $ result ) { $ depend [ ] = $ result ; } } } return $ depend ; }
|
Do not use in performance criticial parts .
|
14,075
|
public function reset ( ) { $ this -> table = '' ; $ this -> columns = [ ] ; $ this -> joins = [ ] ; $ this -> wheres = [ ] ; $ this -> whereIn = [ ] ; $ this -> groupBy = false ; $ this -> orderBy = false ; $ this -> offset = 0 ; $ this -> limit = 10 ; $ this -> fields = [ ] ; return $ this ; }
|
Reset to default values
|
14,076
|
public function select ( $ columns ) { if ( is_array ( $ columns ) ) { $ this -> columns = $ columns ; } elseif ( $ columns === '*' ) { $ this -> columns = [ '*' ] ; } return $ this ; }
|
Sets the columns to be selected
|
14,077
|
public function join ( $ table , $ first , $ operator , $ second , $ type = 'LEFT' ) { $ this -> joins [ ] = [ 'table' => $ table , 'first' => $ first , 'operator' => $ operator , 'second' => $ second , 'type' => $ type ] ; return $ this ; }
|
Sets a table to JOIN with
|
14,078
|
public function where ( $ column , $ value , $ operator = '=' , $ table = null ) { $ table = $ table ? $ table : $ this -> table ; $ this -> wheres [ ] = [ 'table' => $ table , 'column' => $ column , 'value' => $ value , 'operator' => $ operator ] ; return $ this ; }
|
Sets a WHERE condition
|
14,079
|
public function whereIn ( $ column , $ values , $ table = null ) { $ table = isset ( $ table ) ? $ table : $ this -> table ; $ this -> whereIn [ ] = [ 'table' => $ table , 'column' => $ column , 'values' => $ values ] ; return $ this ; }
|
Sets a WHERE IN condition
|
14,080
|
public function get ( ) { $ columns = count ( $ this -> columns ) ? $ this -> getColumnsString ( ) : $ this -> table . '.*' ; $ root = 'SELECT ' . $ columns . ' FROM ' . $ this -> table ; $ joins = count ( $ this -> joins ) ? $ this -> getJoinString ( ) : '' ; $ where = $ this -> getWhereString ( ) ; $ whereIn = $ this -> getWhereInString ( ) ; $ groupBy = ( $ this -> groupBy ) ? 'GROUP BY ' . $ this -> groupBy : '' ; $ orderBy = ( $ this -> orderBy ) ? $ this -> getOrderByString ( ) : '' ; $ limit = 'LIMIT ' . $ this -> offset . ',' . $ this -> limit ; $ this -> query = implode ( ' ' , [ $ root , $ joins , $ where , $ whereIn , $ groupBy , $ orderBy , $ limit ] ) ; if ( $ this -> app -> config ( 'queries.log' ) ) { file_put_contents ( $ this -> app -> config ( 'queries.log' ) , date ( 'Y-m-d h:i:s' ) . ' - ' . $ this -> query . "\r\n" , FILE_APPEND ) ; } $ this -> statement = $ this -> pdo -> prepare ( $ this -> query ) ; if ( count ( $ this -> wheres ) ) { $ this -> bindWheres ( ) ; } if ( ! $ this -> statement -> execute ( ) ) { throw new \ PDOException ( 'Error reading from database' , 500 ) ; } $ result = $ this -> statement -> fetchAll ( \ PDO :: FETCH_ASSOC ) ; $ this -> reset ( ) ; return $ result ; }
|
Performs a SELECT query
|
14,081
|
public function count ( $ column ) { $ this -> limit ( pow ( 100 , 3 ) ) ; $ result = $ this -> select ( [ 'COUNT(' . $ this -> table . '.' . $ column . ') as count' ] ) -> get ( ) ; $ this -> reset ( ) ; return ( count ( $ result ) === 1 ) ? ( int ) reset ( $ result ) [ 'count' ] : count ( $ result ) ; }
|
Performs a SELECT COUNT query
|
14,082
|
public function update ( $ fields ) { $ this -> fields ( $ fields ) ; $ fields = $ this -> getUpdateFieldsString ( ) ; $ where = $ this -> getWhereString ( ) ; $ this -> query = 'UPDATE ' . $ this -> table . ' SET ' . $ fields . ' ' . $ where ; $ this -> statement = $ this -> pdo -> prepare ( $ this -> query ) ; $ this -> bindFields ( ) ; if ( count ( $ this -> wheres ) ) { $ this -> bindWheres ( ) ; } $ result = $ this -> statement -> execute ( ) ; $ this -> reset ( ) ; return $ result ; }
|
Performs an UPDATE query
|
14,083
|
private function getWhereString ( ) { if ( ! count ( $ this -> wheres ) ) { return 'WHERE 1=1 ' ; } $ wheres = array_map ( function ( $ where ) { return $ where [ 'table' ] . '.' . $ where [ 'column' ] . ' ' . $ where [ 'operator' ] . ' :' . $ where [ 'table' ] . $ where [ 'column' ] ; } , $ this -> wheres ) ; return 'WHERE 1 AND ' . implode ( ' AND ' , $ wheres ) ; }
|
Returns the wheres array as a WHERE string
|
14,084
|
private function getWhereInString ( ) { $ string = '' ; if ( ! count ( $ this -> whereIn ) ) { return $ string ; } foreach ( $ this -> whereIn as $ where ) { $ string .= ' AND ' . $ where [ 'column' ] . ' IN (' . implode ( ', ' , $ where [ 'values' ] ) . ')' ; } return $ string ; }
|
Returns the where in array as a WHERE IN string
|
14,085
|
private function getColumnsString ( ) { if ( count ( $ this -> columns ) === 1 && $ this -> columns [ 0 ] === '*' ) { return '*' ; } $ columns = array_map ( function ( $ column ) { return ( strpos ( $ column , '.' ) === false ) ? $ this -> table . '.' . $ column : $ column ; } , $ this -> columns ) ; return implode ( ', ' , $ columns ) ; }
|
Returns the columns array as a field list string
|
14,086
|
private function getJoinString ( ) { if ( ! count ( $ this -> orderBy ) ) { return '' ; } $ joins = array_map ( function ( $ join ) { return $ join [ 'type' ] . ' JOIN ' . $ join [ 'table' ] . ' ON ' . $ this -> table . '.' . $ join [ 'first' ] . $ join [ 'operator' ] . $ join [ 'table' ] . '.' . $ join [ 'second' ] ; } , $ this -> joins ) ; return implode ( ' ' , $ joins ) ; }
|
Returns the joins array as a JOIN string
|
14,087
|
private function getInsertFieldsString ( ) { $ fieldKeys = array_keys ( $ this -> fields ) ; $ fieldsPlaceholders = array_map ( function ( $ field ) { return ':' . $ field ; } , $ fieldKeys ) ; return '(' . implode ( ',' , $ fieldKeys ) . ') VALUES (' . implode ( ',' , $ fieldsPlaceholders ) . ')' ; }
|
Returns the fields array as a VALUES string for inserts
|
14,088
|
private function bindWheres ( ) { foreach ( $ this -> wheres as $ where ) { $ this -> statement -> bindValue ( ':' . $ where [ 'table' ] . $ where [ 'column' ] , $ where [ 'value' ] ) ; } }
|
Binds the values of the WHERE conditions
|
14,089
|
private function bindFields ( ) { foreach ( $ this -> fields as $ key => $ value ) { $ this -> statement -> bindValue ( ':' . $ key , $ value ) ; } }
|
Binds the values of the fields to insert or update
|
14,090
|
public function file ( $ key ) { if ( ! isset ( $ this -> files [ $ key ] ) ) { return null ; } return $ this -> createFile ( $ this -> files [ $ key ] ) ; }
|
Get file by key
|
14,091
|
private function createFile ( array $ fileInfo = [ ] ) { $ file = new \ Nuki \ Models \ Data \ File ( $ fileInfo [ 'tmp_name' ] , $ fileInfo [ 'size' ] ) ; $ file -> setExtension ( pathinfo ( $ fileInfo [ 'name' ] , PATHINFO_EXTENSION ) ) ; $ file -> setName ( pathinfo ( $ fileInfo [ 'name' ] , PATHINFO_BASENAME ) ) ; return $ file ; }
|
Create file object
|
14,092
|
protected function openFile ( string $ file , string $ mode ) { $ fp = @ fopen ( $ file , $ mode ) ; if ( false === $ fp ) { throw new StreamException ( 'Can not open file ' . $ file . ' with mode ' . $ mode . ': ' . str_replace ( 'fopen(' . $ file . '): ' , '' , lastErrorMessage ( ) ) ) ; } return $ fp ; }
|
helper method to open a file handle
|
14,093
|
protected function addData ( $ key , $ data = null ) { $ this -> data [ self :: RS_KEY_DATA ] -> { $ key } = $ data ; }
|
Add data to result object
|
14,094
|
public function findPriceByCurrency ( $ currency ) : ? PriceInterface { if ( $ currency instanceof \ Money \ Currency ) { $ currency = $ currency -> getCode ( ) ; } elseif ( $ currency instanceof CurrencyInterface ) { $ currency = $ currency -> getIsoCodeAlpha ( ) ; } if ( ! is_string ( $ currency ) ) { throw new \ InvalidArgumentException ( '$currency has to be a string' ) ; } foreach ( $ this -> prices as $ price ) { if ( $ price -> getCurrency ( ) -> getIsoCodeAlpha ( ) === $ currency ) { return $ price ; } } return null ; }
|
Will try to find a price based on currency .
|
14,095
|
protected function findPrice ( PriceInterface $ searchPrice ) : ? PriceInterface { foreach ( $ this -> prices as $ price ) { if ( $ price -> getAmount ( ) == $ searchPrice -> getAmount ( ) && $ price -> getB2bGroupId ( ) == $ searchPrice -> getB2bGroupId ( ) && $ price -> getCurrency ( ) -> getId ( ) == $ searchPrice -> getCurrency ( ) -> getId ( ) ) { return $ price ; } } return null ; }
|
This method will try to find a price based on the unique constraint defined in price .
|
14,096
|
public function setMessage ( $ type , $ message ) { if ( ! $ this -> session -> has ( 'flashmsgs' ) ) { $ this -> session -> set ( 'flashmsgs' , array ( ) ) ; } $ temp = $ this -> session -> get ( 'flashmsgs' ) ; $ temp [ ] = array ( 'type' => $ type , 'content' => $ message ) ; $ this -> session -> set ( 'flashmsgs' , $ temp ) ; }
|
Add message to session array
|
14,097
|
public function outputMsgs ( ) { $ messages = $ this -> session -> get ( 'flashmsgs' ) ; $ output = null ; if ( $ messages ) { foreach ( $ messages as $ key => $ message ) { $ output .= '<div class="' . $ message [ 'type' ] . '"><p>' . $ message [ 'content' ] . '</p></div>' ; } } return $ output ; }
|
Build HTML of messages in session array
|
14,098
|
public static function escape ( $ value , array $ options = array ( ) ) { $ options = $ options + array ( 'encoding' => 'UTF-8' , 'flags' => ENT_QUOTES , 'double' => false ) ; return htmlentities ( $ value , $ options [ 'flags' ] , $ options [ 'encoding' ] , $ options [ 'double' ] ) ; }
|
Escape a string using the apps encoding .
|
14,099
|
public static function html ( $ value , array $ options = array ( ) ) { $ options = $ options + array ( 'strip' => true , 'whitelist' => '' ) ; if ( $ options [ 'strip' ] ) { $ value = strip_tags ( $ value , $ options [ 'whitelist' ] ) ; } return static :: escape ( $ value , $ options ) ; }
|
Sanitize a string by removing xor escaping HTML characters and entities .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.