idx int64 0 60.3k | question stringlengths 64 4.24k | target stringlengths 5 618 |
|---|---|---|
25,900 | public static function getNamespace ( $ tokens ) { $ count = count ( $ tokens ) ; $ i = 0 ; $ namespace = '' ; $ namespace_ok = false ; while ( $ i < $ count ) { $ token = $ tokens [ $ i ] ; if ( is_array ( $ token ) && $ token [ 0 ] === T_NAMESPACE ) { while ( ++ $ i < $ count ) { if ( $ tokens [ $ i ] === ';' ) { $ namespace_ok = true ; $ namespace = trim ( $ namespace ) ; break ; } $ namespace .= is_array ( $ tokens [ $ i ] ) ? $ tokens [ $ i ] [ 1 ] : $ tokens [ $ i ] ; } break ; } $ i ++ ; } if ( ! $ namespace_ok ) { return null ; } else { return $ namespace ; } } | Look for the namespace declaration . |
25,901 | public function withAttributes ( array $ attributes ) : self { $ result = clone $ this ; $ result -> attributes = new ParameterCollection ( $ attributes ) ; return $ result ; } | Returns a new instance with the specified attributes . |
25,902 | public function overwrite ( $ file , $ content ) { $ written = file_put_contents ( $ file , $ content ) ; if ( $ content and ! $ written ) { throw new RuntimeException ( "Unable to write to {$file}." ) ; } } | Overwrite a file . |
25,903 | public function breadcrumbs_add ( $ url , $ name , $ active = true , $ class = '' , $ children = array ( ) ) { if ( ! isset ( $ this -> controller ) ) { return false ; } $ this -> controller -> breadcrumbs [ ] = ( object ) array ( 'url' => $ url , 'name' => $ name , 'active' => $ active , 'class' => $ class , 'children' => $ children ) ; return true ; } | Add breadcrumbs element . |
25,904 | public function breadcrumbs_add_userdashboard ( ) { $ brouter = BRouter :: getInstance ( ) ; return $ this -> breadcrumbs_add ( '//' . $ brouter -> generateurl ( 'users' , BLang :: $ langcode , array ( 'view' => 'dashboard' ) ) , BLang :: _ ( 'USERS_DASHBOARD_HEADING' ) , true ) ; } | Add breadcrumbs user dashboard |
25,905 | public function breadcrumbs_add_region ( $ id ) { bimport ( 'regions.general' ) ; $ bregions = BRegions :: getInstance ( ) ; $ regions = $ bregions -> regions_get_all ( ) ; $ reg = $ bregions -> region_get ( $ id ) ; if ( empty ( $ reg ) ) { return false ; } $ brouter = BRouter :: getInstance ( ) ; $ url = '//' . $ brouter -> generateURL ( 'regions' , BLang :: $ langcode , array ( 'view' => 'region' , 'id' => $ id ) ) ; $ children = array ( ) ; foreach ( $ regions as $ r ) { $ children [ $ r -> id ] = ( object ) array ( 'active' => true , 'url' => '//' . $ brouter -> generateURL ( 'regions' , BLang :: $ langcode , array ( 'view' => 'region' , 'id' => $ r -> id ) ) , 'name' => $ r -> getname ( ) ) ; } $ name = $ reg -> getname ( ) ; return $ this -> breadcrumbs_add ( $ url , $ name , true , 'region' , $ children ) ; } | Add region breadcrumbs element |
25,906 | public function breadcrumbs_add_city ( $ id ) { bimport ( 'regions.general' ) ; $ bregions = BRegions :: getInstance ( ) ; $ city = $ bregions -> city_get ( $ id ) ; if ( empty ( $ city ) ) { return false ; } $ region = $ city -> getregion ( ) ; if ( empty ( $ region ) ) { return false ; } $ subcities = $ region -> cities_get_all ( ) ; $ brouter = BRouter :: getInstance ( ) ; $ url = '//' . $ brouter -> generateURL ( 'regions' , BLang :: $ langcode , array ( 'view' => 'city' , 'id' => $ id ) ) ; $ name = $ city -> getname ( ) ; if ( ! empty ( $ subcities ) ) { $ children = array ( ) ; foreach ( $ subcities as $ c ) { $ children [ $ c -> id ] = ( object ) array ( 'active' => true , 'url' => '//' . $ brouter -> generateURL ( 'regions' , BLang :: $ langcode , array ( 'view' => 'city' , 'id' => $ c -> id ) ) , 'name' => $ c -> getname ( ) ) ; } return $ this -> breadcrumbs_add ( $ url , $ name , true , 'city' , $ children ) ; } return $ this -> breadcrumbs_add ( $ url , $ name , true , 'city' ) ; } | Add city breadcrumbs element |
25,907 | public function templateLoad ( $ subName = '' , $ absolute = false ) { $ this -> addPathes ( ) ; $ suffix = BBrowserUseragent :: getDeviceSuffix ( ) ; if ( $ absolute ) { $ fNames = array ( $ subName . $ suffix . '.php' , $ subName . '.d.php' ) ; } else { if ( ! empty ( $ subName ) ) { $ subName = '.' . $ subName ; } $ fNames = array ( $ this -> componentname . '.' . $ this -> viewname . $ subName . $ suffix . '.php' , $ this -> componentname . '.' . $ this -> viewname . $ subName . '.d.php' , $ this -> componentname . '.' . $ this -> viewname . $ suffix . '.php' , $ this -> componentname . '.' . $ this -> viewname . '.d.php' ) ; } $ filename = '' ; $ subfname = '' ; foreach ( $ this -> paths as $ fp ) { if ( ! empty ( $ filename ) ) { break ; } foreach ( $ fNames as $ fn ) { if ( DEBUG_MODE ) { BLog :: addToLog ( '[View] try to load template:' . $ fp . $ fn ) ; } if ( file_exists ( $ fp . $ fn ) ) { $ filename = $ fp . $ fn ; $ subfname = $ fn ; break ; } } } if ( empty ( $ filename ) ) { return '' ; } ob_start ( ) ; include $ filename ; $ html = ob_get_clean ( ) ; if ( DEBUG_MODE ) { $ tp = \ Brilliant \ HTTP \ BRequest :: GetInt ( 'tp' ) ; if ( $ tp ) { $ html = '<div style="font-size: 10px; color: #ccc;">' . $ subfname . '</div>' . $ html ; } } return $ html ; } | Rendering layout into string |
25,908 | public function renderSitemap ( array $ entries ) { $ data = '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL ; $ data .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL ; foreach ( $ entries as $ entry ) { $ data .= ' <url>' . PHP_EOL ; $ data .= ' <loc>' . $ entry -> getLoc ( ) . '</loc>' . PHP_EOL ; if ( null !== $ entry -> getLastMod ( ) ) { $ data .= ' <lastmod>' . $ entry -> getLastMod ( ) . '</lastmod>' . PHP_EOL ; } if ( null !== $ entry -> getChangeFreq ( ) ) { $ data .= ' <changefreq>' . $ entry -> getChangeFreq ( ) . '</changefreq>' . PHP_EOL ; } if ( null !== $ entry -> getPriority ( ) ) { $ data .= ' <priority>' . $ entry -> getPriority ( ) . '</priority>' . PHP_EOL ; } $ data .= ' </url>' . PHP_EOL ; } $ data .= '</urlset>' . PHP_EOL ; return $ data ; } | Render sitemap xml . |
25,909 | public function renderSitemapIndex ( array $ entries ) { $ data = '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL ; $ data .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL ; foreach ( $ entries as $ entry ) { $ data .= ' <sitemap>' . PHP_EOL ; $ data .= ' <loc>' . $ entry -> getLoc ( ) . '</loc>' . PHP_EOL ; $ data .= ' <lastmod>' . $ entry -> getLastMod ( ) . '</lastmod>' . PHP_EOL ; $ data .= ' </sitemap>' . PHP_EOL ; } $ data .= '</sitemapindex>' . PHP_EOL ; return $ data ; } | Render sitemap index xml . |
25,910 | public static function readClass ( $ class , $ annotation = null ) { $ ref = $ class instanceof ReflectionClass ? $ class : new ReflectionClass ( $ class ) ; return $ annotation ? static :: reader ( ) -> getClassAnnotation ( $ ref , $ annotation ) : static :: reader ( ) -> getClassAnnotations ( $ ref ) ; } | Retreive class annotations |
25,911 | public static function isUtf8String ( string $ string ) : bool { if ( false !== \ preg_match ( '/\\G/u' , $ string ) ) { return true ; } if ( \ PREG_BAD_UTF8_ERROR === \ preg_last_error ( ) ) { return false ; } throw new \ LogicException ( 'Another unexpected failure happened with PCRE' ) ; } | Checks if a string is valid UTF - 8 string |
25,912 | public static function dumpString ( string $ value ) : string { if ( '' === $ value ) { return "''" ; } if ( ! self :: isUtf8String ( $ value ) ) { return '"' . \ preg_replace_callback ( '/ \\G (?: [\\x20\\x21\\x23\\x25-\\x5B\\x5D-\\x7E]++ | [\\xC2-\\xDF] [\\x80-\\xBF] | \\xE0 [\\xA0-\\xBF] [\\x80-\\xBF] | [\\xE1-\\xEF] [\\x80-\\xBF]{2} | \\xF0 [\\x90-\\xBF] [\\x80-\\xBF]{2} | [\\xF1-\\xF3] [\\x80-\\xBF]{3} | \\xF4 [\\x80-\\x8F] [\\x80-\\xBF]{2} )*+ \\K (?: ( ["$\\\\] ) | ( . ) ) /xs' , \ Closure :: fromCallable ( [ __CLASS__ , '_escapeStringCallback' ] ) , $ value ) . '"' ; } if ( \ preg_match ( '/[\\x00-\\x1F\\x7F]/' , $ value ) ) { return '"' . \ preg_replace_callback ( '/(["$\\\\])|([\\x00-\\x1F\\x7F])/' , \ Closure :: fromCallable ( [ __CLASS__ , '_escapeStringCallback' ] ) , $ value ) . '"' ; } return \ var_export ( $ value , true ) ; } | Dump string to PHP string literal |
25,913 | private static function _escapeStringCallback ( array $ match ) : string { if ( isset ( $ match [ 2 ] ) ) { return self :: ESCAPE_SPECIALS [ $ match [ 2 ] ] ?? \ sprintf ( '\\x%02X' , \ ord ( $ match [ 2 ] ) ) ; } return '\\' . $ match [ 1 ] ; } | Internal callback to escape characters |
25,914 | public function delete ( $ key ) { unset ( $ this -> _datas [ $ key ] ) ; $ this -> _datas = array_values ( $ this -> _datas ) ; } | Delete one element from the collection |
25,915 | public function deleteRange ( $ key , $ length ) { $ badKeys = [ ] ; for ( $ i = $ key ; $ i < $ key + $ length ; $ i ++ ) { array_push ( $ badKeys , $ i ) ; } $ this -> _datas = array_diff_key ( $ this -> _datas , array_flip ( $ badKeys ) ) ; $ this -> _datas = array_values ( $ this -> _datas ) ; } | Delete between 2 keys |
25,916 | public function getRange ( $ key , $ length ) { $ badKeys = [ ] ; for ( $ i = 0 ; $ i < $ key ; $ i ++ ) { array_push ( $ badKeys , $ i ) ; } for ( $ i = $ key + $ length ; $ i < count ( $ this -> _datas ) ; $ i ++ ) { array_push ( $ badKeys , $ i ) ; } return array_diff_key ( $ this -> _datas , array_flip ( $ badKeys ) ) ; } | Get between 2 keys |
25,917 | public function filter ( $ closure ) { $ collection = new Collection ( ) ; foreach ( $ this -> _datas as $ data ) { if ( $ closure ( $ data ) ) { $ collection -> add ( $ data ) ; } } return $ collection ; } | Filter the collection with a closure |
25,918 | public function add ( $ data ) { if ( ! array_search ( $ data , $ this -> _datas , true ) && is_object ( $ data ) ) { $ data = clone $ data ; } if ( is_array ( $ data ) ) { $ this -> _datas = array_merge ( $ this -> _datas , $ data ) ; } else { if ( get_class ( $ data ) != 'Gcs\Framework\Core\Collection\Collection' ) { array_push ( $ this -> _datas , $ data ) ; } else { array_merge ( $ this -> _datas , $ data -> data ( ) ) ; } } } | Add elements to the collection |
25,919 | final public function getResponse ( ) { if ( empty ( $ this -> response ) ) { $ httpMethod = $ this -> getRequest ( ) ? strtoupper ( $ this -> getRequest ( ) -> getMethod ( ) ) : 'GET' ; if ( $ this -> isHttpMethodSupported ( $ httpMethod ) ) { $ functionName = $ this -> getFunctionName ( $ httpMethod ) ; Logger :: get ( ) -> debug ( "Running responder method '$functionName'..." ) ; if ( $ this instanceof \ Eix \ Core \ Responders \ Restricted ) { Users :: getCurrent ( ) -> checkAuthorisation ( $ this , $ functionName ) ; } $ this -> response = $ this -> $ functionName ( ) ; } else { throw new \ Eix \ Services \ Net \ Http \ MethodNotAllowedException ( "This responder does not support {$httpMethod} requests." ) ; } } return $ this -> response ; } | The default behaviour consists of executing a function named after the HTTP method and the eventual action contained in the request to produce a Response object . |
25,920 | private function getFunctionName ( $ httpMethod ) { if ( $ this -> getRequest ( ) ) { $ functionName = null ; $ functionPrefix = 'http' ; $ functionPrefix .= ucfirst ( strtolower ( $ httpMethod ) ) ; $ action = $ this -> getRequest ( ) -> getParameter ( 'action' ) ; if ( $ action ) { $ functionPrefix .= ucfirst ( $ action ) ; if ( ! $ this -> isBaseFunctionAvailable ( $ functionPrefix ) ) { throw new \ Eix \ Services \ Net \ Http \ NotFoundException ( "This responder does not have any methods starting with {$functionPrefix}." ) ; } } $ found = false ; $ acceptedContentTypes = $ this -> getRequest ( ) -> getAcceptedContentTypes ( ) ; foreach ( $ acceptedContentTypes as $ contentType => $ quality ) { try { $ contentTypeToken = \ Eix \ Core \ Requests \ Http :: getContentTypeToken ( $ contentType ) ; $ functionName = $ functionPrefix . 'For' . $ contentTypeToken ; Logger :: get ( ) -> debug ( "Trying {$functionName} for {$contentType}..." ) ; if ( method_exists ( $ this , $ functionName ) ) { return $ functionName ; } } catch ( \ InvalidArgumentException $ exception ) { } } throw new \ Eix \ Services \ Net \ Http \ NotAcceptableException ( "This responder cannot serve content type {$contentType}." ) ; } else { return 'httpGetForAll' ; } } | Returns a function name that represents the method and response s expected content type . |
25,921 | private function isHttpMethodSupported ( $ requestMethod ) { $ requestMethodName = 'http' . ucfirst ( strtolower ( $ requestMethod ) ) ; foreach ( get_class_methods ( $ this ) as $ methodName ) { if ( strpos ( $ methodName , $ requestMethodName ) === 0 ) { return true ; } } return false ; } | Check whether there is at least one function that implements the requested HTTP method . |
25,922 | private function isBaseFunctionAvailable ( $ functionName ) { foreach ( get_class_methods ( $ this ) as $ responderMethodName ) { if ( strpos ( $ responderMethodName , $ functionName ) === 0 ) { return true ; } } return false ; } | Check whether there is at least one function that implements the requested HTTP method and an eventual action . |
25,923 | public function isAjax ( $ ajax = null ) { if ( isset ( $ ajax ) ) { $ this -> ajax = ( bool ) $ ajax ; return $ this ; } else { return $ this -> ajax ; } } | Sets or gets ajax flag . |
25,924 | public function sendalert ( ) { $ alertaClass = $ this -> console -> ask ( "Notification Class?" ) ; if ( class_exists ( $ alertaClass ) ) { $ email = $ this -> console -> anticipate ( "User email?" , [ 'andres.espinosa@grimorum.com' ] ) ; if ( $ toUser = \ App \ User :: where ( "email" , "=" , $ email ) -> first ( ) ) { $ message = $ this -> console -> ask ( "Message?" ) ; $ data = [ ] ; $ data [ 'message' ] = $ message ; $ tiempo = $ this -> console -> ask ( "Send in? (Just a number,next you will select seconds, minutes, etc.)" ) ; if ( ! is_int ( ( int ) $ tiempo ) ) { $ tiempo = $ this -> console -> ask ( "Send in? HAS TO BE AN INTEGER NUMBER" ) ; } if ( is_int ( ( int ) $ tiempo ) ) { $ unidad = $ this -> console -> choice ( '...' , [ 'seconds' , 'minutes' , 'hours' , 'days' ] , 0 ) ; switch ( $ unidad ) { case 'seconds' : $ when = now ( ) -> addSeconds ( $ tiempo ) ; break ; case 'minutes' : $ when = now ( ) -> addMinutes ( $ tiempo ) ; break ; case 'hours' : $ when = now ( ) -> addHours ( $ tiempo ) ; break ; case 'days' : $ when = now ( ) -> addDays ( $ tiempo ) ; break ; default : $ when = now ( ) -> addMinutes ( $ tiempo ) ; break ; } $ toUser -> notify ( ( new $ alertaClass ( $ data ) ) -> delay ( $ when ) ) ; $ this -> console -> info ( "Listo!" ) ; } else { $ this -> console -> error ( "Paila!" ) ; } } else { $ this -> console -> error ( "User not found" ) ; } } else { $ this -> console -> error ( "Class not found" ) ; } } | Broadcast an alert to a user |
25,925 | public function createmodel ( $ table ) { $ this -> console -> line ( "Preparing model attributes" ) ; $ bar = $ this -> console -> output -> createProgressBar ( 4 ) ; $ options = $ this -> console -> options ( 'path' ) ; $ modelName = $ singular = str_singular ( $ table ) ; if ( $ options [ 'path' ] != "" ) { $ path = $ options [ 'path' ] ; } else { $ path = "app/" . ucfirst ( $ modelName ) ; } $ path = str_replace ( "//" , "/" , str_replace ( [ "\\" , " " ] , [ "/" , "" ] , $ path ) ) ; $ AuxclassName = explode ( "/" , str_replace ( ".php" , "" , $ path ) ) ; $ className = "" ; $ justPath = "" ; $ prefijoPath = "/" ; $ prefijo = "" ; $ fileName = "" ; $ nameSpace = "" ; foreach ( $ AuxclassName as $ indice => $ pedazo ) { if ( $ indice == count ( $ AuxclassName ) - 1 ) { $ nameSpace = $ className ; $ fileName = str_finish ( ucfirst ( $ pedazo ) , ".php" ) ; $ modelName = strtolower ( $ pedazo ) ; } else { $ justPath .= $ prefijoPath . $ pedazo ; $ prefijoPath = "/" ; } $ className .= $ prefijo . ucfirst ( $ pedazo ) ; $ prefijo = "\\" ; } $ path = str_finish ( $ path , ".php" ) ; $ bar -> advance ( ) ; $ this -> console -> line ( "Loading details from {$table} table" ) ; $ config = CrudGenerator :: getModelDetailsFromDb ( $ table ) ; $ config [ "modelo" ] = $ config [ "model" ] = $ modelName ; $ config [ "nameSpace" ] = $ nameSpace ; $ bar -> advance ( ) ; $ this -> console -> info ( "Details loaded!" ) ; $ bar -> advance ( ) ; $ confirm = $ this -> console -> choice ( "Do you wisth to continue and save the model to '{$path}' with the className '{$className}'?" , [ 'yes' , 'no' ] , 0 ) ; if ( $ confirm == 'yes' ) { $ this -> console -> line ( "Saving Model for {$modelName} in {$path} with className '{$className}'" ) ; if ( CrudGenerator :: saveResource ( "sirgrimorum::templates.model" , false , base_path ( $ justPath ) , $ fileName , $ config ) ) { $ this -> console -> info ( "Model file saved!" ) ; $ bar -> finish ( ) ; } else { $ this -> console -> error ( "Something went wrong and the model file could not be saved" ) ; $ bar -> finish ( ) ; } } else { $ bar -> finish ( ) ; } } | Create a Model file based on a database table |
25,926 | public function createlang ( $ model ) { $ this -> console -> line ( "Preparing model attributes" ) ; $ bar = $ this -> console -> output -> createProgressBar ( 5 ) ; $ options = $ this -> console -> options ( 'path' ) ; if ( $ options [ 'path' ] != "" ) { $ path = $ options [ 'path' ] ; } else { $ path = "lang/vendor/crudgenerator/" . config ( "app.locale" ) ; } $ path = str_replace ( "//" , "/" , str_replace ( [ "\\" , " " ] , [ "/" , "" ] , $ path ) ) ; $ filename = str_finish ( strtolower ( $ model ) , ".php" ) ; $ bar -> advance ( ) ; $ this -> console -> line ( "Loading config array for {$model}" ) ; $ config = CrudGenerator :: getConfig ( $ model , false ) ; $ bar -> advance ( ) ; $ this -> console -> info ( "Config loaded!" ) ; $ bar -> advance ( ) ; $ this -> console -> line ( "Saving Lang file for {$model} in {$path} with filename '{$filename}'" ) ; if ( CrudGenerator :: saveResource ( "sirgrimorum::templates.lang" , false , resource_path ( $ path ) , $ filename , $ config ) ) { $ this -> console -> info ( "Model Lang file saved!" ) ; } else { $ this -> console -> error ( "Something went wrong and the model lang file could not be saved" ) ; } $ bar -> advance ( ) ; $ confirm = $ this -> console -> choice ( "Do you wisth to create a Lang File for the model in es?" , [ 'yes' , 'no' ] , 0 ) ; if ( $ confirm == 'yes' ) { $ path = "lang/vendor/crudgenerator/es" ; $ filename = str_finish ( strtolower ( $ model ) , ".php" ) ; $ this -> console -> line ( "Saving Lang file for {$model} in {$path} with filename '{$filename}'" ) ; if ( CrudGenerator :: saveResource ( "sirgrimorum::templates.langes" , false , resource_path ( $ path ) , $ filename , $ config ) ) { $ this -> console -> info ( "Model Lang file saved!" ) ; $ bar -> finish ( ) ; } else { $ this -> console -> error ( "Something went wrong and the model lang file could not be saved" ) ; $ bar -> finish ( ) ; } } $ bar -> finish ( ) ; } | Create a Model Lang file from config array |
25,927 | public function setIcon ( $ icon ) { $ this -> icon = $ this -> factory -> create ( 'Fontawesome\Icon' ) ; $ this -> icon -> setIcon ( $ icon ) ; return $ this ; } | Set an icon from fontawesome icon . Use only the name without the leading fa - |
25,928 | public function build ( ) { if ( $ this -> mode == 'ajax' ) { $ this -> data [ 'ajax' ] = 'link' ; } if ( $ this -> text && $ this -> icon ) { $ this -> type = 'imgbutton' ; } if ( $ this -> type == 'icon' ) { $ this -> css [ 'icon' ] = 'icon' ; $ this -> icon -> noStack ( ) ; $ this -> inner = $ this -> icon -> build ( ) ; } if ( $ this -> type == 'button' ) { $ this -> inner = '<span class="button-text">' . $ this -> text . '</span>' ; } if ( $ this -> type == 'link' ) { $ this -> css [ 'link' ] = 'link' ; $ this -> inner = '<span class="link-text">' . $ this -> text . '</span>' ; } if ( $ this -> type == 'imgbutton' ) { $ this -> icon -> noStack ( ) ; $ this -> inner = $ this -> icon -> build ( ) . ' ' . $ this -> text ; } if ( $ this -> type != 'link' ) { $ this -> css [ 'btn' ] = 'btn' ; $ check = [ 'btn-primary' , 'btn-success' , 'btn-warning' , 'btn-info' , 'btn-default' ] ; if ( $ this -> checkCss ( $ check ) == false ) { $ this -> addCss ( 'btn-default' ) ; } } return parent :: build ( ) ; } | Builds and returns button html code |
25,929 | public function buildService ( ) { require_once ( $ this -> classFile ) ; $ wsdl = $ this -> generateWsdl ( ) ; if ( isset ( $ _GET [ 'wsdl' ] ) ) { print $ wsdl ; } else { $ file = 'data://text/plain;base64,' . base64_encode ( $ wsdl ) ; $ server = new \ SoapServer ( $ file ) ; $ server -> setClass ( $ this -> className ) ; $ functions = get_class_methods ( $ this -> className ) ; foreach ( $ functions as $ function ) { $ server -> addFunction ( $ function ) ; } $ server -> handle ( ) ; } } | Construction du service |
25,930 | public function getById ( $ id , $ col = null ) { $ id = ( int ) $ id ; $ model = $ this -> getCacheItem ( $ id ) ; if ( ! $ model ) { $ model = $ this -> getMapper ( ) -> getById ( $ id , $ col ) ; if ( $ this -> useCache ) { $ this -> setCacheItem ( $ id , $ model ) ; } } return $ model ; } | return one or more records from database by id |
25,931 | public function search ( array $ post ) { $ sort = ( isset ( $ post [ 'sort' ] ) ) ? $ post [ 'sort' ] : '' ; unset ( $ post [ 'sort' ] , $ post [ 'count' ] , $ post [ 'offset' ] , $ post [ 'page' ] ) ; $ searches = [ ] ; foreach ( $ post as $ key => $ value ) { $ searches [ ] = [ 'searchString' => $ value , 'columns' => explode ( '-' , $ key ) , ] ; } $ models = $ this -> getMapper ( ) -> search ( $ searches , $ sort ) ; return $ models ; } | basic search on database |
25,932 | public function add ( array $ post , Form $ form = null ) { $ model = $ this -> getModel ( ) ; $ form = ( $ form instanceof Form ) ? $ form -> setData ( $ post ) : $ this -> prepareForm ( $ model , $ post , true , true ) ; $ argv = compact ( 'post' , 'form' ) ; $ argv = $ this -> prepareEventArguments ( $ argv ) ; $ this -> getEventManager ( ) -> trigger ( self :: EVENT_PRE_ADD , $ this , $ argv ) ; if ( ! $ form -> isValid ( ) ) { return $ form ; } $ saved = $ this -> save ( $ form -> getData ( ) ) ; $ argv = compact ( 'post' , 'form' , 'saved' ) ; $ argv = $ this -> prepareEventArguments ( $ argv ) ; $ this -> getEventManager ( ) -> trigger ( self :: EVENT_POST_ADD , $ this , $ argv ) ; return $ saved ; } | prepare and return form |
25,933 | public function edit ( ModelInterface $ model , array $ post , Form $ form = null ) { $ form = ( $ form instanceof Form ) ? $ form -> setData ( $ post ) : $ this -> prepareForm ( $ model , $ post , true , true ) ; $ argv = compact ( 'model' , 'post' , 'form' ) ; $ argv = $ this -> prepareEventArguments ( $ argv ) ; $ this -> getEventManager ( ) -> trigger ( self :: EVENT_PRE_EDIT , $ this , $ argv ) ; if ( ! $ form -> isValid ( ) ) { return $ form ; } $ saved = $ this -> save ( $ form -> getData ( ) ) ; $ argv = compact ( 'model' , 'post' , 'form' , 'saved' ) ; $ argv = $ this -> prepareEventArguments ( $ argv ) ; $ this -> getEventManager ( ) -> trigger ( self :: EVENT_POST_EDIT , $ this , $ argv ) ; $ eventSaved = ( isset ( $ argv [ 'result' ] ) ) ? $ argv [ 'result' ] : false ; return ( ! $ saved && ! $ eventSaved ) ? false : true ; } | prepare data to be updated and saved into database . |
25,934 | public function save ( $ data ) { $ argv = compact ( 'data' ) ; $ argv = $ this -> prepareEventArguments ( $ argv ) ; $ this -> getEventManager ( ) -> trigger ( self :: EVENT_PRE_SAVE , $ this , $ argv ) ; $ data = $ argv [ 'data' ] ; if ( $ data instanceof ModelInterface ) { $ data = $ this -> getHydrator ( ) -> extract ( $ data ) ; } $ pk = $ this -> getMapper ( ) -> getPrimaryKey ( ) ; $ id = $ data [ $ pk ] ; unset ( $ data [ $ pk ] ) ; if ( 0 === $ id || null === $ id || '' === $ id ) { $ result = $ this -> getMapper ( ) -> insert ( $ data ) ; $ this -> clearCacheTags ( ) ; } else { if ( $ this -> getById ( $ id ) ) { $ result = $ this -> getMapper ( ) -> update ( $ data , [ $ pk => $ id ] ) ; } else { throw new ServiceException ( 'ID ' . $ id . ' does not exist' ) ; } $ this -> removeCacheItem ( $ id ) ; } $ argv = compact ( 'data' , 'result' ) ; $ argv = $ this -> prepareEventArguments ( $ argv ) ; $ this -> getEventManager ( ) -> trigger ( self :: EVENT_POST_SAVE , $ this , $ argv ) ; return $ result ; } | updates a row if id is supplied else insert a new row |
25,935 | public function delete ( $ id ) { $ model = $ this -> getById ( $ id ) ; $ argv = compact ( 'id' , 'model' ) ; $ argv = $ this -> prepareEventArguments ( $ argv ) ; $ this -> getEventManager ( ) -> trigger ( self :: EVENT_PRE_DELETE , $ this , $ argv ) ; $ result = $ this -> getMapper ( ) -> delete ( [ $ this -> getMapper ( ) -> getPrimaryKey ( ) => $ id ] ) ; if ( $ result ) { $ this -> removeCacheItem ( $ id ) ; $ argv = compact ( 'id' , 'model' , 'result' ) ; $ argv = $ this -> prepareEventArguments ( $ argv ) ; $ this -> getEventManager ( ) -> trigger ( self :: EVENT_POST_DELETE , $ this , $ argv ) ; } return $ result ; } | delete row from database |
25,936 | public function getMapper ( $ mapperClass = null , array $ options = [ ] ) { $ mapperClass = $ mapperClass ?? $ this -> mapper ?? $ this -> serviceAlias ; if ( ! array_key_exists ( $ mapperClass , $ this -> mappers ) ) { $ this -> setMapper ( $ mapperClass , $ options ) ; } return $ this -> mappers [ $ mapperClass ] ; } | gets the mapper class for this service |
25,937 | public function setMapper ( $ mapperClass , array $ options = [ ] ) { $ sl = $ this -> getServiceLocator ( ) ; $ mapperManager = $ sl -> get ( MapperManager :: class ) ; $ defaultOptions = [ 'model' => $ this -> model ?? $ this -> serviceAlias , 'hydrator' => $ this -> hydrator ?? $ this -> serviceAlias , ] ; $ options = array_merge ( $ defaultOptions , $ options ) ; $ mapper = $ mapperManager -> get ( $ mapperClass , $ options ) ; $ this -> mappers [ $ mapperClass ] = $ mapper ; return $ this ; } | Sets mapper in mapper array for reuse . |
25,938 | protected function buildMappingOnObject ( $ source = null , array $ blacklist = [ ] ) : array { if ( ! is_object ( $ source ) ) { return [ ] ; } try { $ mapping = [ ] ; $ reflection = new \ ReflectionClass ( $ source ) ; $ properties = $ reflection -> getProperties ( ) ; foreach ( $ properties as $ key => $ value ) { if ( ! in_array ( $ value -> name , $ blacklist ) ) $ mapping [ $ value -> name ] = $ value -> name ; } return $ mapping ; } catch ( \ Exception $ exception ) { return [ ] ; } } | Build a mapping based on properties of a entity . |
25,939 | public function getCacheRule ( $ name = null ) { if ( is_null ( $ name ) ) { return $ this -> cacheRules ; } else { foreach ( $ this -> cacheRules as $ r ) { if ( $ r -> getName ( ) == $ name ) { return $ r ; } } return false ; } } | Get a specific cache rule or all of them . |
25,940 | public function setCacheRules ( array $ cacheRules ) { foreach ( $ cacheRules as $ crName => $ cr ) { if ( isset ( $ cr [ 'Ttl' ] ) && isset ( $ cr [ 'Tags' ] ) && isset ( $ cr [ 'Match' ] ) ) { $ this -> cacheRules [ $ crName ] = new CacheRule ( $ crName , $ cr [ 'Ttl' ] , $ cr [ 'Tags' ] , $ cr [ 'Match' ] , $ cr ) ; } else { throw new HrcException ( sprintf ( 'Unable to parse "%s" rule. The rule is missing a definition for one of these attributes: Ttl, Tags or Match' , $ crName ) ) ; } } } | Overwrite the current cache rule list . |
25,941 | public function save ( $ name , $ content , $ cacheRule = null , $ cacheTagsAppend = [ ] ) { $ log = new DebugLog ( ) ; $ log -> addMessage ( 'State' , 'Save' ) ; if ( ! isset ( $ _SERVER [ 'REQUEST_METHOD' ] ) || strtolower ( $ _SERVER [ 'REQUEST_METHOD' ] ) != 'get' ) { $ log -> addMessage ( 'CacheRule-Match' , 'Only GET requests can be cached.' ) ; return false ; } if ( ! ( $ rule = $ this -> getMatchedRule ( $ cacheRule ) ) || $ rule -> getCacheRule ( ) -> getTtl ( ) <= 0 ) { $ log -> addMessage ( 'CacheRule-Match' , 'No rule matched the request.' ) ; return false ; } $ log -> addMessage ( 'CacheRule-Match' , sprintf ( '%s rule matched the request.' , $ rule -> getCacheRule ( ) -> getName ( ) ) ) ; $ rule -> getCacheRule ( ) -> appendTags ( $ cacheTagsAppend ) ; $ key = $ this -> createJointKey ( $ name , $ rule -> getCacheKey ( ) ) ; $ savePayload = new SavePayload ( $ key , $ content , $ rule ) ; foreach ( $ this -> callbacks as $ cb ) { call_user_func_array ( [ $ cb , 'beforeSave' ] , [ $ savePayload ] ) ; } if ( ! $ savePayload -> getSaveFlag ( ) ) { return false ; } $ log -> addMessage ( 'CacheRule-CacheKey' , $ savePayload -> getKey ( ) ) ; $ saved = $ this -> cacheStorage -> save ( $ savePayload -> getKey ( ) , $ savePayload -> getContent ( ) , $ savePayload -> getRule ( ) -> getCacheRule ( ) -> getTtl ( ) ) ; if ( $ saved ) { $ this -> indexStorage -> save ( $ savePayload -> getKey ( ) , $ savePayload -> getRule ( ) -> getCacheRule ( ) -> getTags ( ) , ( $ savePayload -> getRule ( ) -> getCacheRule ( ) -> getTtl ( ) ) ) ; $ log -> addMessage ( 'CacheStorage-Save' , 'Cache saved.' ) ; } else { throw new HrcException ( 'There has been an error while trying to save the cache.' ) ; } $ this -> log = $ log ; foreach ( $ this -> callbacks as $ cb ) { call_user_func_array ( [ $ cb , 'afterSave' ] , [ $ savePayload ] ) ; } return $ savePayload -> getKey ( ) ; } | Save a value into cache . In case if no cache rule was matched false is returned . |
25,942 | public function purgeByCacheKey ( $ cacheKey ) { $ log = new DebugLog ( ) ; $ log -> addMessage ( 'State' , 'Purge by cache key' ) ; $ this -> indexStorage -> deleteEntryByKey ( $ cacheKey ) ; return $ this -> cacheStorage -> purge ( $ cacheKey ) ; } | Purge the given cache key . |
25,943 | public function getMatchedRule ( $ cacheRule = null ) { $ request = $ this -> getRequest ( ) ; if ( ! empty ( $ cacheRule ) ) { if ( isset ( $ this -> cacheRules [ $ cacheRule ] ) ) { $ cr = $ this -> cacheRules [ $ cacheRule ] ; $ cacheKey = $ cr -> match ( $ request ) ; return new MatchedRule ( clone $ cr , $ cacheKey ) ; } } else { foreach ( $ this -> cacheRules as $ cr ) { if ( ( $ cacheKey = $ cr -> match ( $ request ) ) ) { return new MatchedRule ( clone $ cr , $ cacheKey ) ; } } } return false ; } | Returns a MatchedRule instance of the matched cache rule . |
25,944 | private function canPurge ( ) { if ( ! $ this -> request -> matchHeader ( self :: H_PURGE ) ) { return false ; } if ( $ this -> controlKey == '' ) { return true ; } if ( $ this -> request -> matchHeader ( self :: H_CKEY , $ this -> controlKey ) ) { return true ; } return false ; } | Checks if user can purge the cache by validating the control key and purge flag inside the request headers . |
25,945 | private function canDebug ( ) { if ( ! $ this -> request -> matchHeader ( self :: H_DEBUG ) ) { return false ; } if ( $ this -> controlKey == '' ) { return true ; } if ( $ this -> request -> matchHeader ( self :: H_CKEY , $ this -> controlKey ) ) { return true ; } return false ; } | Checks if user can retrieve debug log by validating the control key and debug flag inside the request headers . |
25,946 | public function validate ( $ value ) { $ original = $ value ; if ( is_callable ( $ value ) && $ value instanceof \ Closure ) { $ value = $ value ( $ this -> container ) ; } if ( ! $ value instanceof $ this -> contract ) { throw new \ RuntimeException ( 'The configured value does not implement ' . $ this -> contract ) ; } return $ original ; } | Validate middleware pipeline |
25,947 | public function get ( string $ path ) : SplFileInfo { $ path = ltrim ( $ path , '\\/' ) ; foreach ( $ this -> assets as $ asset ) { if ( $ asset -> getRelativePathname ( ) === $ path ) { return $ asset ; } } throw new NotFoundHttpException ( sprintf ( 'Unknown asset: %s' , $ path ) ) ; } | Get a single relative asset . |
25,948 | public function getAppUri ( ) { $ uri = filter_input ( INPUT_SERVER , 'REQUEST_URI' ) ; $ scriptPath = $ this -> getBaseUrl ( ) ; $ appUri = substr ( $ uri , strlen ( $ scriptPath ) ) ; return $ appUri === false ? '' : $ appUri ; } | Get the application URI calculated from REQUEST_URI |
25,949 | public function getBaseUrl ( bool $ withHostName = false ) : string { if ( ! $ this -> baseUrl ) { $ this -> baseUrl = dirname ( filter_input ( INPUT_SERVER , 'SCRIPT_NAME' ) ) ; } return ( $ withHostName ? self :: getHttpHost ( ) : '' ) . $ this -> baseUrl ; } | Get the application base url |
25,950 | public function route ( $ uri = null ) { if ( $ uri === null ) { $ uri = $ this -> getAppUri ( ) ; } $ urlElements = parse_url ( $ uri ) ; $ uri = isset ( $ urlElements [ 'path' ] ) ? $ urlElements [ 'path' ] : '' ; $ query = isset ( $ urlElements [ 'query' ] ) ? $ urlElements [ 'query' ] : null ; $ fragment = isset ( $ urlElements [ 'fragment' ] ) ? $ urlElements [ 'fragment' ] : null ; $ urlTab = explode ( '/' , trim ( $ uri , ' /' ) ) ; $ request = Container :: getRequest ( ) ; $ request -> setUri ( $ uri ) ; $ request -> setBaseUrl ( $ this -> getBaseUrl ( ) ) ; $ controller = array_shift ( $ urlTab ) ; $ action = array_shift ( $ urlTab ) ; $ request -> setController ( $ controller ? $ controller : self :: DEFAULT_CONTROLLER ) ; $ request -> setAction ( $ action ? $ action : self :: DEFAULT_ACTION ) ; while ( count ( $ urlTab ) ) { $ key = trim ( array_shift ( $ urlTab ) ) ; $ value = array_shift ( $ urlTab ) ; if ( $ value !== null ) { $ request -> setParam ( $ key , $ value ) ; } } if ( $ query !== null ) { $ params = null ; parse_str ( $ query , $ params ) ; foreach ( $ params as $ key => $ value ) { $ request -> setParam ( $ key , $ value ) ; } } return $ this ; } | Update Request with params from url |
25,951 | public function buildUri ( array $ params = null , $ controller = null , $ action = null , $ prepareUri = true ) { $ request = Container :: getRequest ( ) ; $ request -> setBaseUrl ( $ this -> getBaseUrl ( ) ) ; if ( $ prepareUri ) { [ $ params , $ controller , $ action ] = $ this -> prepareUri ( $ params , $ controller , $ action ) ; } else { $ params = $ params ?? [ ] ; $ controller = $ controller ?? self :: DEFAULT_CONTROLLER ; $ action = $ action ?? self :: DEFAULT_ACTION ; } if ( ! is_array ( $ params ) ) { $ params = [ ] ; } if ( isset ( $ params [ 'controller' ] ) && ( $ controller === self :: DEFAULT_CONTROLLER ) ) { $ controller = $ params [ 'controller' ] ; unset ( $ params [ 'controller' ] ) ; } if ( isset ( $ params [ 'action' ] ) && ( $ action === self :: DEFAULT_ACTION ) ) { $ action = $ params [ 'action' ] ; unset ( $ params [ 'action' ] ) ; } $ hasParams = count ( $ params ) ; $ hasController = $ controller != self :: DEFAULT_CONTROLLER ; $ hasAction = $ action != self :: DEFAULT_ACTION ; $ uri = $ hasParams || $ hasAction || $ hasController ? '/' . $ controller : '/' ; $ uri .= $ hasParams || $ hasAction ? '/' . $ action : '' ; foreach ( $ params as $ key => $ value ) { $ uri .= '/' . $ key . '/' . $ value ; } $ uri = '/' . ltrim ( rtrim ( $ request -> getBaseUrl ( ) , '/' ) . $ uri , '/' ) ; return $ uri ; } | Build an URL from specified params |
25,952 | protected function getEventAdapter ( EventArgs $ args ) { $ class = get_class ( $ args ) ; if ( preg_match ( '@Doctrine\\\([^\\\]+)@' , $ class , $ m ) && in_array ( $ m [ 1 ] , [ 'ODM' , 'ORM' ] ) ) { if ( ! isset ( $ this -> adapters [ $ m [ 1 ] ] ) ) { $ adapterClass = 'Gedmo\\Mapping\\Event\\Adapter\\' . $ m [ 1 ] ; $ this -> adapters [ $ m [ 1 ] ] = new $ adapterClass ( ) ; } $ this -> adapters [ $ m [ 1 ] ] -> setEventArgs ( $ args ) ; return $ this -> adapters [ $ m [ 1 ] ] ; } throw new \ InvalidArgumentException ( 'Session continaer does not support event arg class: ' . $ class ) ; } | Get an event adapter to handle event specific methods |
25,953 | private function registerAllThemes ( ) { $ directories = $ this -> app [ 'files' ] -> directories ( base_path ( 'themes' ) ) ; foreach ( $ directories as $ directory ) { $ this -> app [ 'stylist' ] -> registerPath ( $ directory ) ; } } | Register all themes with activating them . |
25,954 | private function setActiveTheme ( ) { if ( $ this -> inAdministration ( ) ) { $ themeName = $ this -> app [ 'config' ] -> get ( 'society.core.core.admin-theme' ) ; return $ this -> app [ 'stylist' ] -> activate ( $ themeName , true ) ; } return $ this -> app [ 'stylist' ] -> activate ( $ this -> app [ 'config' ] -> get ( 'society.core.core.frontend-theme' ) , true ) ; } | Set the active theme based on the settings . |
25,955 | public function camelize ( $ s ) { $ s = preg_replace ( '/[_-]+/' , '_' , trim ( $ s ) ) ; $ s = str_replace ( ' ' , '_' , $ s ) ; $ camelized = '' ; for ( $ i = 0 , $ n = strlen ( $ s ) ; $ i < $ n ; ++ $ i ) { if ( $ s [ $ i ] == '_' && $ i + 1 < $ n ) $ camelized .= strtoupper ( $ s [ ++ $ i ] ) ; else $ camelized .= $ s [ $ i ] ; } $ camelized = trim ( $ camelized , ' _' ) ; if ( strlen ( $ camelized ) > 0 ) $ camelized [ 0 ] = strtolower ( $ camelized [ 0 ] ) ; return $ camelized ; } | Turn a string into its camelized version . |
25,956 | public function uncamelize ( $ s ) { $ normalized = '' ; for ( $ i = 0 , $ n = strlen ( $ s ) ; $ i < $ n ; ++ $ i ) { if ( ctype_alpha ( $ s [ $ i ] ) && self :: is_upper ( $ s [ $ i ] ) ) $ normalized .= '_' . strtolower ( $ s [ $ i ] ) ; else $ normalized .= $ s [ $ i ] ; } return trim ( $ normalized , ' _' ) ; } | Convert a camelized string to a lowercase underscored string . |
25,957 | public static function compressFid ( $ fid ) { $ fid = preg_replace ( '/^FID:/' , '' , $ fid ) ; $ fid = preg_replace_callback ( '/:([0-9]{10}):/' , function ( $ v ) { return ':' . base_convert ( $ v [ 1 ] , 10 , 36 ) . ':' ; } , $ fid ) ; return str_replace ( ':' , '-' , $ fid ) ; } | Compress a fid into a short url friendly format |
25,958 | public static function expandFid ( $ compressedFid ) { $ fid = str_replace ( '-' , ':' , $ compressedFid ) ; $ fid = preg_replace_callback ( '/:([0-9a-z]{5,6}):/' , function ( $ v ) { return ':' . base_convert ( $ v [ 1 ] , 36 , 10 ) . ':' ; } , $ fid ) ; return 'FID:' . $ fid ; } | Decompress a compressed fid into its full version |
25,959 | private function importAndSetPublisher ( $ name , $ locale ) { $ translation = $ this -> em -> getRepository ( 'VipaJournalBundle:PublisherTranslation' ) -> findOneBy ( [ 'name' => $ name ] ) ; $ publisher = $ translation !== null ? $ translation -> getTranslatable ( ) : null ; if ( ! $ publisher ) { $ url = ! empty ( $ this -> settings [ $ locale ] [ 'publisherUrl' ] ) ? $ this -> settings [ $ locale ] [ 'publisherUrl' ] : null ; $ publisher = $ this -> createPublisher ( $ this -> settings [ $ locale ] [ 'publisherInstitution' ] , $ url , $ locale ) ; $ publisher -> setStatus ( PublisherStatuses :: STATUS_COMPLETE ) ; foreach ( $ this -> settings as $ fieldLocale => $ fields ) { $ publisher -> setCurrentLocale ( mb_substr ( $ fieldLocale , 0 , 2 , 'UTF-8' ) ) ; ! empty ( $ fields [ 'publisherNote' ] ) ? $ publisher -> setAbout ( $ fields [ 'publisherNote' ] ) : $ publisher -> setAbout ( '-' ) ; } } $ this -> journal -> setPublisher ( $ publisher ) ; } | Imports the publisher with given name and assigns it to the journal . It uses the one from the database in case it exists . |
25,960 | private function getUnknownPublisher ( $ locale ) { $ translation = $ this -> em -> getRepository ( 'VipaJournalBundle:PublisherTranslation' ) -> findOneBy ( [ 'name' => 'Unknown Publisher' ] ) ; $ publisher = $ translation !== null ? $ translation -> getTranslatable ( ) : null ; if ( ! $ publisher ) { $ publisher = $ this -> createPublisher ( 'Unknown Publisher' , 'http://example.com' , $ locale ) ; $ publisher -> setCurrentLocale ( mb_substr ( $ locale , 0 , 2 , 'UTF-8' ) ) -> setAbout ( '-' ) ; $ this -> em -> persist ( $ publisher ) ; } return $ publisher ; } | Fetches the publisher with the name Unknown Publisher . |
25,961 | private function createPublisher ( $ name , $ url , $ locale ) { $ publisher = new Publisher ( ) ; $ publisher -> setCurrentLocale ( mb_substr ( $ locale , 0 , 2 , 'UTF-8' ) ) -> setName ( $ name ) -> setEmail ( 'publisher@example.com' ) -> setAddress ( '-' ) -> setPhone ( '-' ) -> setUrl ( $ url ) ; $ this -> em -> persist ( $ publisher ) ; return $ publisher ; } | Creates a publisher with given properties . |
25,962 | public function setAttributes ( $ values , $ safeOnly = true ) { $ flags = $ this -> cachedFlags ( ) ; $ notFlags = array ( ) ; foreach ( $ values as $ key => $ val ) { if ( array_key_exists ( $ key , $ flags ) ) { $ this -> setFlag ( $ key , $ val ) ; } else { $ notFlags [ $ key ] = $ val ; } } parent :: setAttributes ( $ notFlags , $ safeOnly ) ; } | Sets the attribute and flags values in a massive way . |
25,963 | public function getAttributes ( $ names = null ) { $ attributes = parent :: getAttributes ( $ names ) ; if ( is_array ( $ names ) ) { $ flags = $ this -> cachedFlags ( ) ; $ flagNames = array_intersect ( array_keys ( $ flags ) , $ names ) ; foreach ( $ flagNames as $ name ) { $ attributes [ $ name ] = $ this -> getFlag ( $ flags [ $ name ] ) ; } } return $ attributes ; } | Returns all attribute and flags values . |
25,964 | public function withFlag ( $ flag ) { $ flagValue = ( is_string ( $ flag ) ) ? $ this -> flagsFromText ( $ flag ) : $ flag ; if ( $ flagValue ) { $ this -> getDbCriteria ( ) -> mergeWith ( array ( 'condition' => $ this -> getTableAlias ( ) . '.' . $ this -> flagsField . '&' . $ flagValue . '<>0' , ) ) ; } return $ this ; } | Scope for select records with given flag |
25,965 | public function applyFlags ( $ criteria , $ flags , $ operator = 'AND' ) { $ flagList = $ this -> cachedFlags ( ) ; $ flags = CPropertyValue :: ensureArray ( $ flags ) ; $ newCriteria = new CDbCriteria ( ) ; foreach ( $ flags as $ flag ) { if ( is_string ( $ flag ) ) { if ( $ invert = ( $ flag [ 0 ] == '!' ) ) { $ flag = substr ( $ flag , 1 ) ; } $ flagValue = $ flagList [ trim ( strtolower ( $ flag ) ) ] ; } else { $ flagValue = $ flag ; } if ( empty ( $ flagValue ) === false ) { $ equality = $ invert ? '=' : '<>' ; $ newCriteria -> addCondition ( $ this -> flagsField . '&' . $ flagValue . $ equality . '0' , $ operator ) ; } } $ criteria -> mergeWith ( $ newCriteria ) ; return $ criteria ; } | Apply flags conditions to given criteria |
25,966 | protected static function convertToLowercase ( $ str ) { $ explodedStr = explode ( '_' , $ str ) ; if ( count ( $ explodedStr ) > 1 ) { $ lowerCasedStr = [ ] ; foreach ( $ explodedStr as $ value ) { $ lowerCasedStr [ ] = strtolower ( $ value ) ; } $ str = implode ( '_' , $ lowerCasedStr ) ; } return $ str ; } | Convert strings with underscores to be all lowercase before camelCase is preformed . |
25,967 | public function downloadAction ( $ fileId ) { $ volumeManager = $ this -> get ( 'phlexible_media_manager.volume_manager' ) ; try { $ volume = $ volumeManager -> getByFileId ( $ fileId ) ; } catch ( \ Exception $ e ) { throw $ this -> createNotFoundException ( $ e -> getMessage ( ) , $ e ) ; } $ file = $ volume -> findFile ( $ fileId ) ; $ filePath = $ file -> getPhysicalPath ( ) ; if ( ! file_exists ( $ filePath ) ) { throw $ this -> createNotFoundException ( 'File not found.' ) ; } $ mimeType = $ file -> getMimeType ( ) ; $ response = new BinaryFileResponse ( $ filePath , 200 , array ( 'Content-Type' => $ mimeType ) ) ; $ response -> setContentDisposition ( ResponseHeaderBag :: DISPOSITION_ATTACHMENT , $ file -> getName ( ) ) ; return $ response ; } | Download a media file . |
25,968 | private function AddTypeField ( ) { $ name = 'Type' ; $ select = new Select ( $ name , $ this -> textfield -> GetType ( ) ) ; $ select -> AddOption ( '' , Trans ( 'Core.PleaseSelect' ) ) ; $ values = TextfieldType :: AllowedValues ( ) ; foreach ( $ values as $ value ) { $ select -> AddOption ( $ value , Trans ( 'Forms.TextfieldType.' . ucfirst ( $ value ) ) ) ; } $ this -> AddField ( $ select ) ; $ this -> SetRequired ( $ name ) ; } | Adds the type field |
25,969 | public function execute ( Framework $ framework , RequestAbstract $ request , Response $ response ) { $ response -> setOutputPart ( '404' , 'The requested route is not available. We can\'t execute the request. Route: "' . $ request -> getRoute ( ) . '"' ) ; } | The DefaultRouteNotFound event handler will generate a route not found error message . |
25,970 | public function connect ( array $ config , $ username = null , $ password = null , array $ options = array ( ) ) { if ( ! isset ( $ config [ 'host' ] , $ config [ 'database' ] ) ) { throw new DatabaseDriverException ( "No 'host' or 'database' given in the configuration of the connection!" ) ; } $ port = isset ( $ config [ 'port' ] ) ? $ config [ 'port' ] : 3306 ; $ charset = isset ( $ config [ 'charset' ] ) ? $ config [ 'charset' ] : 'utf8' ; $ dsn = "mysql:host={$config['host']};port=$port;dbname={$config['database']};charset=$charset" ; $ connection = new Connection ( $ dsn , $ username , $ password , $ options ) ; $ connection -> setAttribute ( \ PDO :: ATTR_ERRMODE , \ PDO :: ERRMODE_EXCEPTION ) ; return $ connection ; } | Create the connection . Will return a connection instance . |
25,971 | public static function createObject ( $ class , ... $ args ) : object { $ work = self :: wrapObject ( $ class ) ; $ work -> __gentryConstruct ( ... $ args ) ; return $ work ; } | Creates an anonymous object based on a reflection . |
25,972 | private static function tostring ( $ value ) : string { if ( ! isset ( $ value ) ) { return 'NULL' ; } if ( $ value === true ) { return 'true' ; } if ( $ value === false ) { return 'false' ; } if ( is_numeric ( $ value ) ) { return $ value ; } if ( is_string ( $ value ) ) { return "'$value'" ; } if ( is_array ( $ value ) ) { $ out = '[' ; $ i = 0 ; foreach ( $ value as $ key => $ entry ) { if ( $ i ) { $ out .= ', ' ; } $ out .= $ key . ' => ' . self :: tostring ( $ entry ) ; $ i ++ ; } $ out .= ']' ; return $ out ; } if ( is_object ( $ value ) ) { if ( method_exists ( $ value , '__toString' ) ) { return "$value" ; } else { return get_class ( $ value ) ; } } } | Internal helper method to get an echo able representation of a random value for reporting and code generation . |
25,973 | public static function none ( ) { if ( self :: $ empty === null ) self :: $ empty = new Option ( null ) ; return self :: $ empty ; } | Get an empty option |
25,974 | public function pipeFromDI ( string $ p_middleware ) { $ middleware = \ FreeFW \ DI \ DI :: get ( $ p_middleware ) ; $ this -> middlewares -> enqueue ( $ middleware ) ; return $ this ; } | Add new middleware to pipeline |
25,975 | public function setCookieParams ( $ lifetime , $ path = NULL , $ domain = NULL , $ secure = FALSE , $ httponly = FALSE ) { session_set_cookie_params ( $ lifetime , $ path , $ domain , $ secure , $ httponly ) ; } | Setea parametros de cookie |
25,976 | public function setContentType ( $ contentType , $ charset = NULL ) { $ this -> setHeader ( "Content-Type" , $ contentType ) ; if ( $ charset != NULL ) { $ this -> setHeader ( "charset" , $ charset ) ; } } | Setea el tipo de contenido a enviar |
25,977 | public function sendFile ( $ file , $ name = NULL , $ contentType = 'application/octet-stream' , $ contentDisposition = 'attachment' ) { if ( $ name == NULL ) { $ name = basename ( $ file ) ; } header ( 'Content-Description: File Transfer' ) ; header ( 'Content-Type: ' . $ contentType ) ; header ( 'Content-Disposition: ' . $ contentDisposition . '; filename="' . $ name . '"' ) ; header ( 'Pragma: public' ) ; header ( 'Content-Length: ' . filesize ( $ file ) ) ; readfile ( $ file ) ; } | Envia un archivo como respuesta . Se indican distintos parametros del header |
25,978 | public function sendApiRestEncode ( $ code = 200 , $ data = NULL , $ options = 0 , $ contentType = 'application/json' ) { $ this -> sendApiRest ( $ code , json_encode ( $ data , $ options ) , $ contentType ) ; } | Metodo para API REST . Envia una respuesta json con un codigo de respuesta codificando los datos |
25,979 | public function sendApiRest ( $ code = 200 , $ jsonString = '' , $ contentType = 'application/json' ) { $ this -> setStatusCode ( $ code ) ; $ this -> setContentType ( $ contentType ) ; $ this -> setContent ( $ jsonString ) ; $ this -> sendContent ( ) ; } | Metodo para API REST . Envia una respuesta json con un codigo de respuesta |
25,980 | public static function connect ( Container $ oContainerConnection ) { if ( self :: getContainer ( ) === null ) { self :: setContainer ( $ oContainerConnection ) ; } if ( ! isset ( self :: $ _oPdo [ $ oContainerConnection -> getName ( ) ] ) ) { if ( $ oContainerConnection -> getType ( ) == 'mysql' ) { try { if ( $ oContainerConnection -> getDbName ( ) ) { $ dbText = ";dbname=" . $ oContainerConnection -> getDbName ( ) ; } else { $ dbText = "" ; } self :: $ _oPdo [ $ oContainerConnection -> getName ( ) ] = new \ PDO ( 'mysql:host=' . $ oContainerConnection -> getHost ( ) . $ dbText , $ oContainerConnection -> getUser ( ) , $ oContainerConnection -> getPassword ( ) , array ( \ PDO :: MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8" ) ) ; self :: $ _oPdo [ $ oContainerConnection -> getName ( ) ] -> setAttribute ( \ PDO :: ATTR_FETCH_TABLE_NAMES , 1 ) ; self :: $ _oPdo [ $ oContainerConnection -> getName ( ) ] -> setAttribute ( \ PDO :: MYSQL_ATTR_USE_BUFFERED_QUERY , true ) ; } catch ( \ Exception $ oException ) { echo $ oException -> getMessage ( ) ; } } else if ( $ oContainerConnection -> getType ( ) == 'mssql' ) { if ( $ oContainerConnection -> getDbName ( ) ) { $ dbText = ";dbname=" . $ oContainerConnection -> getDbName ( ) ; } else { $ dbText = "" ; } self :: $ _oPdo [ $ oContainerConnection -> getName ( ) ] = new \ PDO ( 'mssql:host=' . $ oContainerConnection -> getHost ( ) . $ dbText , $ oContainerConnection -> getUser ( ) , $ oContainerConnection -> getPassword ( ) ) ; self :: $ _oPdo [ $ oContainerConnection -> getName ( ) ] -> setAttribute ( \ PDO :: ATTR_FETCH_TABLE_NAMES , 1 ) ; self :: $ _oPdo [ $ oContainerConnection -> getName ( ) ] -> setAttribute ( \ PDO :: MYSQL_ATTR_USE_BUFFERED_QUERY , true ) ; } else if ( $ oContainerConnection -> getType ( ) == 'sqlite' ) { self :: $ _oPdo [ $ oContainerConnection -> getName ( ) ] = new \ PDO ( 'sqlite:' . $ oContainerConnection -> getHost ( ) ) ; self :: $ _oPdo [ $ oContainerConnection -> getName ( ) ] -> setAttribute ( \ PDO :: ATTR_FETCH_TABLE_NAMES , 1 ) ; self :: $ _oPdo [ $ oContainerConnection -> getName ( ) ] -> setAttribute ( \ PDO :: MYSQL_ATTR_USE_BUFFERED_QUERY , true ) ; } } return self :: $ _oPdo [ $ oContainerConnection -> getName ( ) ] ; } | get instance of Pdo |
25,981 | public static function trim_to_nearest_word ( $ text , $ char_limit ) { if ( strlen ( $ text ) <= $ char_limit ) { return $ text ; } $ wrapped_text = explode ( '\n' , wordwrap ( $ text , $ char_limit , '\n' ) ) ; return is_array ( $ wrapped_text ) ? $ wrapped_text [ 0 ] : substr ( $ text , 0 , $ char_limit ) ; } | Get text trimmed to the nearest word . |
25,982 | public function log ( $ message , $ args , $ priority = 'LOG_INFO' ) { if ( array_key_exists ( 'FILENAME' , $ args ) === false ) { $ backtrace = debug_backtrace ( ) ; $ args [ 'FILENAME' ] = $ backtrace [ 0 ] [ 'file' ] ; $ args [ 'LINENO' ] = $ backtrace [ 0 ] [ 'line' ] ; } $ newArgs = array ( ) ; $ fileParts = explode ( '/' , $ args [ 'FILENAME' ] ) ; $ newArgs [ ] = array_pop ( $ fileParts ) . "#" . $ args [ 'LINENO' ] ; unset ( $ args [ 'LINENO' ] ) ; unset ( $ args [ 'FILENAME' ] ) ; foreach ( $ args as $ arg ) { $ newArgs [ ] = $ arg ; } if ( $ this -> _isSecure ( $ message ) === true ) { } else { if ( empty ( $ this -> _logPatterns ) ) { $ this -> _logPatterns [ Logger :: ALL ] = new FileLogHandler ( ) ; } foreach ( $ this -> _logPatterns as $ pattern => $ handler ) { if ( preg_match ( $ pattern , $ message ) ) $ handler -> writeLog ( $ message , $ priority , $ newArgs ) ; } } } | Implementation of log method in Logger |
25,983 | public function info ( $ message , $ args = array ( ) ) { $ backtrace = debug_backtrace ( ) ; $ args [ 'FILENAME' ] = $ backtrace [ 0 ] [ 'file' ] ; $ args [ 'LINENO' ] = $ backtrace [ 0 ] [ 'line' ] ; $ this -> log ( $ message , $ args , 'LOG_INFO' ) ; } | Implementation of Info in Logger |
25,984 | public function debug ( $ message , $ args = array ( ) ) { $ backtrace = debug_backtrace ( ) ; $ args [ 'FILENAME' ] = $ backtrace [ 0 ] [ 'file' ] ; $ args [ 'LINENO' ] = $ backtrace [ 0 ] [ 'line' ] ; $ this -> log ( $ message , $ args , 'LOG_DEBUG' ) ; } | Implementation of debug in Logger |
25,985 | public function warn ( $ message , $ args = array ( ) ) { $ backtrace = debug_backtrace ( ) ; $ args [ 'FILENAME' ] = $ backtrace [ 0 ] [ 'file' ] ; $ args [ 'LINENO' ] = $ backtrace [ 0 ] [ 'line' ] ; $ this -> log ( $ message , $ args , 'LOG_WARNING' ) ; } | Implementation of warn in Logger |
25,986 | public function error ( $ message , $ args = array ( ) ) { $ backtrace = debug_backtrace ( ) ; $ args [ 'FILENAME' ] = $ backtrace [ 0 ] [ 'file' ] ; $ args [ 'LINENO' ] = $ backtrace [ 0 ] [ 'line' ] ; $ this -> log ( $ message , $ args , 'LOG_ERR' ) ; } | Implementation of error in Logger |
25,987 | public function alert ( $ message , $ args = array ( ) ) { $ backtrace = debug_backtrace ( ) ; $ args [ 'FILENAME' ] = $ backtrace [ 0 ] [ 'file' ] ; $ args [ 'LINENO' ] = $ backtrace [ 0 ] [ 'line' ] ; $ this -> log ( $ message , $ args , 'LOG_ALERT' ) ; } | Implementation of alert in Logger |
25,988 | public function addHandler ( $ destination , $ pattern = Logger :: ALL , $ level = 'LOG_INFO' , $ type = 'file' ) { $ this -> _logPatterns [ $ pattern ] = $ this -> buildHandler ( $ destination , $ level , $ type ) ; } | Implementation of addHandler in Logger |
25,989 | public function viewAction ( ) { $ params = $ this -> params ( ) ; $ service = $ this -> getServiceLocator ( ) ; $ displayn = $ params -> fromRoute ( 'displayName' ) ; if ( ! mb_check_encoding ( $ displayn , 'UTF-8' ) ) { $ this -> getResponse ( ) -> setStatusCode ( 404 ) ; return ; } $ model = $ service -> get ( 'Grid\User\Model\User\Model' ) ; $ user = $ model -> findByDisplayName ( $ displayn ) ; $ this -> paragraphLayout ( ) ; if ( empty ( $ user ) ) { $ this -> getResponse ( ) -> setStatusCode ( 404 ) ; return ; } return new MetaContent ( 'user.datasheet' , array ( 'user' => $ user , 'edit' => $ this -> getPermissionsModel ( ) -> isAllowed ( $ user , 'edit' ) , 'password' => $ this -> getPermissionsModel ( ) -> isAllowed ( $ user , 'password' ) , 'delete' => $ this -> getPermissionsModel ( ) -> isAllowed ( $ user , 'delete' ) , ) ) ; } | View a user |
25,990 | public function persist ( $ model ) { $ class = $ this -> manager -> getClassMetadata ( get_class ( $ model ) ) ; $ managers = $ class -> getFieldManagerNames ( ) ; $ pool = $ this -> manager -> getPool ( ) ; $ priority = $ pool -> getPriority ( 'transaction' ) ; $ id = null ; if ( $ class -> hasManagerReferenceGenerator ( ) ) { $ managerName = $ class -> getManagerReferenceGenerator ( ) ; $ referenceModel = $ model -> { 'get' . ucfirst ( $ managerName ) } ( ) ; $ pool -> getManager ( $ managerName ) -> persist ( $ referenceModel ) ; $ id = $ referenceModel -> getId ( ) ; unset ( $ managers [ $ managerName ] ) ; } foreach ( $ managers as $ key => $ managerName ) { if ( isset ( $ priority [ $ managerName ] ) ) { $ this -> doPersist ( $ managerName , $ model , $ id ) ; unset ( $ managers [ $ key ] ) ; } } foreach ( $ managers as $ managerName ) { $ this -> addQueue ( self :: QUEUE_ACTION_PERSIST , $ managerName , $ model , $ id ) ; } } | Saves a model . |
25,991 | public function commit ( ) { $ this -> launch ( function ( $ manager ) { $ manager -> commit ( ) ; } ) ; $ this -> executeQueue ( ) ; $ this -> manager -> flush ( ) ; } | Commits a transaction on the underlying database connection . |
25,992 | protected function launch ( \ Closure $ func ) { foreach ( $ this -> manager -> getPool ( ) -> getPriority ( 'transaction' ) as $ managerName ) { $ func ( $ this -> manager -> getPool ( ) -> getManager ( $ managerName ) ) ; } } | Launch function for each manager in transaction priority . |
25,993 | protected function addQueue ( $ action , $ managerName , $ model , $ id = null ) { if ( ! in_array ( $ action , array ( self :: QUEUE_ACTION_PERSIST , self :: QUEUE_ACTION_REMOVE ) ) ) { throw new \ InvalidArgumentException ( sprintf ( 'Action unknown, manager name : "%s".' , $ managerName ) ) ; } $ this -> queueActions [ ] = $ action ; $ this -> queueManagerNames [ ] = $ managerName ; $ this -> queueModels [ ] = $ model ; $ this -> queueIds [ ] = $ id ; } | Add action with model reference in queue . |
25,994 | protected function executeQueue ( ) { foreach ( $ this -> queueActions as $ key => $ action ) { if ( self :: QUEUE_ACTION_PERSIST === $ action ) { $ this -> doPersist ( $ this -> queueManagerNames [ $ key ] , $ this -> queueModels [ $ key ] , $ this -> queueIds [ $ key ] ) ; } else { $ this -> manager -> getPool ( ) -> getManager ( $ this -> queueManagerNames [ $ key ] ) -> remove ( $ this -> queueModels [ $ key ] ) ; } } $ this -> cleanQueue ( ) ; } | Execute all data in queue . |
25,995 | public static function addSerializerToDriver ( Serializer $ serializer , FileDriverProvider $ provider ) : FileDriverProvider { if ( $ provider instanceof FileDriverWithSerializer ) { $ provider -> addSerializer ( $ serializer ) ; return $ provider ; } return new FileDriverWithSerializer ( $ serializer , $ provider ) ; } | Add a serializer to a FileDriverProvider |
25,996 | public function get_section ( $ section ) { if ( $ this -> isInitialized === true ) { $ retval = $ this -> fullConfig [ $ section ] ; } else { throw new exception ( __METHOD__ . ": not initialized" ) ; } return ( $ retval ) ; } | Retrieve all data about the given section . |
25,997 | public function build ( ) : array { $ reflector = new \ ReflectionMethod ( $ this -> class_name , $ this -> method_name ) ; $ dependencies = $ this -> get_dependencies ( $ reflector , $ this -> arguments ) ; $ obj = $ this -> make ( $ this -> class_name , $ this -> arguments ) ; return [ $ obj , $ dependencies , $ this -> validators ] ; } | Build the object its dependencies and list any validators that should be checked |
25,998 | private function get_dependencies ( \ ReflectionMethod $ reflector , $ named_arguments ) : array { $ reflector_parameters = $ reflector -> getParameters ( ) ; $ dependencies = $ this -> resolve_dependencies ( $ reflector_parameters , $ named_arguments ) ; return $ dependencies ; } | Get the dependencies for a given reflection object |
25,999 | private function make ( $ class_name , $ named_arguments ) { $ reflector = new \ ReflectionClass ( $ class_name ) ; $ constructor = $ reflector -> getConstructor ( ) ; if ( is_subclass_of ( $ class_name , Singleton :: class ) ) { return $ class_name :: get_instance ( ) ; } if ( $ reflector -> isAbstract ( ) ) { return null ; } if ( null === $ constructor ) { return new $ class_name ( ) ; } $ dependencies = $ this -> get_dependencies ( $ constructor , $ named_arguments ) ; $ obj = $ reflector -> newInstanceArgs ( $ dependencies ) ; if ( $ obj instanceof Request ) { $ this -> validators [ ] = $ obj ; } return $ obj ; } | Given a class and arguments to inject into that class this will create an instance of the given object . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.