idx int64 0 60.3k | question stringlengths 92 4.62k | target stringlengths 7 635 |
|---|---|---|
1,400 | public function addTemplate ( $ template , $ vars = [ ] ) { $ tpl = new Template ( $ template , 'template-mail' , 0 ) ; foreach ( $ vars as $ key => $ var ) { $ tpl -> assign ( $ key , $ var ) ; } $ message = $ tpl -> show ( ) ; array_push ( $ this -> _message , $ message ) ; } | You can use a template |
1,401 | public function addFile ( $ file , $ name = 'attachment' , $ mime = Mime :: TXT ) { $ this -> _fileTransfert = 'multipart/mixed' ; $ this -> _hasAttachment = true ; if ( file_exists ( $ file ) ) { $ data = file_get_contents ( $ file ) ; if ( $ name == self :: ATTACHMENT ) { $ name = $ name . uniqid ( ) ; } if ( isset ( $ this -> _attachments [ $ name ] ) ) { $ name = $ name . uniqid ( ) ; } $ this -> _attachments [ $ name ] = [ chunk_split ( base64_encode ( $ data ) , $ mime ) ] ; } } | You can add attachments |
1,402 | public function media ( $ entity , array $ options = [ ] ) { $ options += [ 'internal' => false ] ; $ results = [ ] ; if ( $ options [ 'internal' ] ) { return [ ] ; } $ entities = $ entity -> raw [ 'entities' ] ; if ( ! isset ( $ entities [ 'media' ] ) ) { return $ results ; } foreach ( $ entities [ 'media' ] as $ item ) { if ( $ item [ 'type' ] !== 'photo' ) { continue ; } $ results [ ] = [ 'type' => 'image' , 'url' => $ item [ 'media_url_https' ] , 'display_url' => $ item [ 'display_url' ] ] ; } return $ results ; } | FIXME Find a way to support internal media URLs . |
1,403 | public function setCreated ( $ date , $ format = null ) { $ this -> created = $ this -> inputDate ( $ date , $ format ) ; return $ this ; } | Set created date |
1,404 | public function setLastModified ( $ date , $ format = null ) { $ this -> _lastModified = $ this -> inputDate ( $ date , $ format ) ; return $ this ; } | Set last - modified date |
1,405 | public function init ( PushPipe $ pushPipe , PushSettings $ pushSettings ) { $ this -> pushPipe = $ pushPipe ; $ this -> pushSettings = $ pushSettings ; if ( $ pushSettings -> isPurgeOnStartup ( ) ) { $ this -> brokerModel -> purgeQueue ( $ pushSettings -> getInputQueue ( ) ) ; } } | It initializes the message pusher with the pipe it will send messages through . The pipe is invoked for each incoming message . |
1,406 | public function start ( ) { $ this -> brokerModel -> consume ( $ this -> pushSettings -> getInputQueue ( ) , function ( \ AMQPEnvelope $ envelope , \ AMQPQueue $ queue ) { return $ this -> messageProcessor -> process ( $ envelope , $ queue , $ this -> pushPipe , $ this -> pushSettings -> getErrorQueue ( ) , new ReceiveCancellationToken ( ) , new EndpointControlToken ( ) ) ; } ) ; } | Starts pushing messages |
1,407 | public function getChildren ( ) { uasort ( $ this -> children , function ( AdminMenuItem $ first , AdminMenuItem $ second ) { if ( $ first -> getPriority ( ) <= $ second -> getPriority ( ) ) { return 1 ; } return - 1 ; } ) ; return $ this -> children ; } | Get children . |
1,408 | public function onKernelView ( GetResponseForControllerResultEvent $ event ) : void { $ presentation = $ event -> getControllerResult ( ) ; if ( ! $ presentation instanceof PresentationInterface ) { return ; } $ data = null ; $ headers = [ ] ; if ( $ presentation -> getResource ( ) ) { $ acceptableMediaTypes = $ event -> getRequest ( ) -> getAcceptableContentTypes ( ) ; $ serializer = $ this -> serializerResolver -> resolveByMediaTypes ( get_class ( $ presentation -> getResource ( ) ) , $ acceptableMediaTypes , $ acceptableMediaType ) ; $ serializationContext = $ this -> serializationContextCollector -> collect ( ) ; $ data = $ serializer -> serialize ( $ presentation -> getResource ( ) , $ serializationContext ) ; $ headers = [ 'Content-Type' => $ acceptableMediaType , ] ; } $ response = new Response ( $ data , $ presentation -> getStatusCode ( ) ) ; $ response -> headers -> add ( $ headers ) ; $ event -> setResponse ( $ response ) ; } | Handle for transform presentation to content for send to client |
1,409 | public function truncateHtml ( $ str , $ length , $ suffix = '…' ) { $ stringUitl = new StringUtil ( ) ; return $ stringUitl -> truncatePreservingTags ( $ str , $ length , $ suffix ) ; } | Truncate text preserving html tags . |
1,410 | public function getMemoryData ( $ wmiConnection ) { $ Computersystem = $ wmiConnection -> query ( "SELECT TotalPhysicalMemory from Win32_ComputerSystem" ) ; $ OperatingSystem = $ wmiConnection -> query ( "SELECT FreePhysicalMemory, TotalVisibleMemorySize FROM Win32_OperatingSystem" ) ; $ PageFileUsage = $ wmiConnection -> query ( "SELECT AllocatedBaseSize, CurrentUsage FROM Win32_PageFileUsage" ) ; $ return = Array ( ) ; foreach ( $ Computersystem as $ wmi_computersystem ) { $ return [ 'total_ram_machine' ] = $ wmi_computersystem -> TotalPhysicalMemory ; } foreach ( $ OperatingSystem as $ wmi_operatingsystem ) { $ return [ 'avaliable_ram_real' ] = \ Cityware \ Format \ Number :: convertByteFormat ( $ wmi_operatingsystem -> FreePhysicalMemory , 'KB' , 'B' ) ; } $ return [ 'total_memory_used' ] = $ return [ 'total_ram_machine' ] - $ return [ 'avaliable_ram_real' ] ; $ return [ 'perc_memory_used' ] = round ( ( ( $ return [ 'total_memory_used' ] / $ return [ 'total_ram_machine' ] ) * 100 ) , 2 ) ; foreach ( $ PageFileUsage as $ wmi_pagefileusage ) { $ return [ 'total_swap_size' ] = \ Cityware \ Format \ Number :: convertByteFormat ( $ wmi_pagefileusage -> AllocatedBaseSize , 'MB' , 'B' ) ; $ return [ 'total_swap_used' ] = \ Cityware \ Format \ Number :: convertByteFormat ( $ wmi_pagefileusage -> CurrentUsage , 'MB' , 'B' ) ; } $ return [ 'avaliable_swap_size' ] = $ return [ 'total_swap_size' ] - $ return [ 'total_swap_used' ] ; $ return [ 'perc_swap_used' ] = round ( ( ( $ return [ 'total_swap_used' ] / $ return [ 'total_swap_size' ] ) * 100 ) , 2 ) ; return $ return ; } | Return Memory Data |
1,411 | private function translate_application ( $ application , $ directory ) { $ log = '' ; $ log .= 'translating ' . $ application . ' (' . $ directory . ')' . "\n" ; $ templates = $ this -> get_templates ( $ directory ) ; $ strings = [ ] ; foreach ( $ templates as $ template ) { $ log .= $ template . "\n" ; $ strings = array_merge ( $ strings , $ this -> get_strings ( $ template , $ directory ) ) ; } $ language_interface = \ Skeleton \ I18n \ Config :: $ language_interface ; if ( ! class_exists ( $ language_interface ) ) { throw new \ Exception ( 'The language interface does not exists: ' . $ language_interface ) ; } $ languages = $ language_interface :: get_all ( ) ; foreach ( $ languages as $ language ) { if ( $ language -> name_short == \ Skeleton \ I18n \ Config :: $ base_language ) { continue ; } $ log .= ' ' . $ language -> name_short ; if ( file_exists ( \ Skeleton \ I18n \ Config :: $ po_directory . '/' . $ language -> name_short . '/' . $ application . '.po' ) ) { $ translated = \ Skeleton \ I18n \ Util :: load ( \ Skeleton \ I18n \ Config :: $ po_directory . '/' . $ language -> name_short . '/' . $ application . '.po' ) ; $ old_translated = \ Skeleton \ I18n \ Util :: load ( \ Skeleton \ I18n \ Config :: $ po_directory . '/' . $ language -> name_short . '.po' ) ; $ translated = array_merge ( $ translated , $ old_translated ) ; } else { $ translated = [ ] ; } $ new_po = [ ] ; foreach ( $ strings as $ string ) { if ( isset ( $ translated [ $ string ] ) and $ translated [ $ string ] != '' ) { $ new_po [ $ string ] = $ translated [ $ string ] ; } else { $ new_po [ $ string ] = '' ; } } $ result1 = array_diff_key ( $ new_po , $ translated ) ; $ result2 = array_diff_key ( $ translated , $ new_po ) ; if ( count ( $ result1 ) == 0 and count ( $ result2 ) == 0 ) { continue ; } if ( count ( $ new_po ) == 0 ) { } \ Skeleton \ I18n \ Util :: save ( \ Skeleton \ I18n \ Config :: $ po_directory . '/' . $ language -> name_short . '/' . $ application . '.po' , $ application , $ language , $ new_po ) ; } $ log .= "\n" ; return $ log ; } | Translate an application |
1,412 | private function get_strings ( $ file , $ directory ) { $ parts = explode ( '.' , strrev ( $ file ) , 2 ) ; $ filename = strrev ( $ parts [ 1 ] ) ; $ extension = strrev ( $ parts [ 0 ] ) ; switch ( $ extension ) { case 'twig' : $ strings = $ this -> get_twig_strings ( $ file , $ directory ) ; break ; case 'tpl' : $ strings = $ this -> get_smarty_strings ( $ file , $ directory ) ; break ; default : throw new \ Exception ( 'Unknown template type' ) ; } return $ strings ; } | Parse all translatable stings out of a file |
1,413 | private function unescape_strings ( $ strings , $ escape ) { if ( strlen ( $ escape ) <> 1 ) { throw new Exception ( 'Escape parameter can only be one character' ) ; } $ escaped_strings = [ ] ; foreach ( $ strings as $ string ) { $ escaped_strings [ ] = ( string ) str_replace ( '\\' . $ escape , $ escape , $ string ) ; } return $ escaped_strings ; } | Unescape strings in an array |
1,414 | private function get_templates ( $ directory ) { $ templates = [ ] ; foreach ( new \ RecursiveIteratorIterator ( new \ RecursiveDirectoryIterator ( $ directory ) , \ RecursiveIteratorIterator :: LEAVES_ONLY ) as $ file ) { if ( $ file -> isFile ( ) === false ) { continue ; } if ( $ file -> getExtension ( ) != 'twig' && $ file -> getExtension ( ) != 'tpl' ) { continue ; } $ resource = str_replace ( $ directory , '' , $ file ) ; $ templates [ ] = $ resource ; } return $ templates ; } | Find all template files in a given directory |
1,415 | public static function Delete ( string $ folder , bool $ clear = false ) { if ( empty ( $ folder ) && ! \ is_dir ( $ folder ) ) { return ; } $ folder = \ rtrim ( $ folder , '\\/' ) . \ DIRECTORY_SEPARATOR ; $ openDir = \ opendir ( $ folder ) ; \ readdir ( $ openDir ) ; \ readdir ( $ openDir ) ; while ( false !== ( $ item = \ readdir ( $ openDir ) ) ) { $ path = $ folder . $ item ; if ( ! \ is_dir ( $ path ) ) { File :: Delete ( $ path ) ; } else { static :: Delete ( $ path ) ; } } \ closedir ( $ openDir ) ; if ( ! $ clear ) { return ; } try { \ rmdir ( $ folder ) ; } catch ( \ Throwable $ ex ) { throw new IOException ( $ folder , 'Could not delete the defined folder.' , \ E_USER_ERROR , $ ex ) ; } } | Deletes the defined folder recursive with all contained files and sub folders . |
1,416 | public static function ListAllFiles ( string $ folder , bool $ recursive = false ) : array { $ files = [ ] ; if ( ! @ \ is_dir ( $ folder ) ) { return $ files ; } if ( ! $ recursive ) { $ d = \ dir ( $ folder ) ; $ d -> read ( ) ; $ d -> read ( ) ; while ( false !== ( $ entry = $ d -> read ( ) ) ) { $ tmp = Path :: Combine ( $ folder , $ entry ) ; if ( ! \ is_file ( $ tmp ) ) { continue ; } $ files [ ] = $ tmp ; } $ d -> close ( ) ; return $ files ; } static :: _listRecursive ( $ files , $ folder ) ; return $ files ; } | Returns all file paths inside the defined folder . |
1,417 | public function createPaginator ( $ dql , $ page , $ limit ) { $ offset = ( $ page - 1 ) * $ limit ; $ query = $ this -> entityManager -> createQuery ( $ dql ) -> setMaxResults ( $ limit ) -> setFirstResult ( $ offset ) ; $ paginator = new Paginator ( $ query ) ; $ adapter = new DoctrinePaginatorAdapter ( $ paginator ) ; $ zendPaginator = new ZendPaginator ( $ adapter ) ; $ zendPaginator -> setCurrentPageNumber ( $ page ) ; $ zendPaginator -> setItemCountPerPage ( $ limit ) ; return $ zendPaginator ; } | Uses doctrine to create a paginator |
1,418 | public function remove ( $ name ) { $ segments = $ this -> getSegments ( $ name ) ; $ target = & $ this -> fields ; while ( count ( $ segments ) > 1 ) { $ path = array_shift ( $ segments ) ; if ( ! array_key_exists ( $ path , $ target ) ) { return ; } $ target = & $ target [ $ path ] ; } unset ( $ target [ array_shift ( $ segments ) ] ) ; } | Removes a field and its children from the registry . |
1,419 | public function & get ( $ name ) { $ segments = $ this -> getSegments ( $ name ) ; $ target = & $ this -> fields ; while ( $ segments ) { $ path = array_shift ( $ segments ) ; if ( ! array_key_exists ( $ path , $ target ) ) { throw new \ InvalidArgumentException ( sprintf ( 'Unreachable field "%s"' , $ path ) ) ; } $ target = & $ target [ $ path ] ; } return $ target ; } | Returns the value of the field and its children . |
1,420 | public function set ( $ name , $ value ) { $ target = & $ this -> get ( $ name ) ; if ( ( ! is_array ( $ value ) && $ target instanceof Field \ FormField ) || $ target instanceof Field \ ChoiceFormField ) { $ target -> setValue ( $ value ) ; } elseif ( is_array ( $ value ) ) { $ fields = self :: create ( $ name , $ value ) ; foreach ( $ fields -> all ( ) as $ k => $ v ) { $ this -> set ( $ k , $ v ) ; } } else { throw new \ InvalidArgumentException ( sprintf ( 'Cannot set value on a compound field "%s".' , $ name ) ) ; } } | Set the value of a field and its children . |
1,421 | public function setControllerName ( $ controllerName ) { $ controllerName = strtolower ( $ controllerName ) ; $ controllerName = str_replace ( "controller" , "" , $ controllerName ) ; $ controllerName = ucfirst ( $ controllerName ) . "Controller" ; $ this -> _controllerName = $ controllerName ; } | Formats a controllerName correctly iNDeXCOntrLleR - > indexController |
1,422 | public static function parse ( $ yaml ) { $ options = null ; if ( function_exists ( 'yaml_parse' ) ) { $ options = yaml_parse ( $ yaml ) ; } else { $ options = spyc_load ( $ yaml ) ; } if ( $ options === null ) { throw new YamlParseException ( 'There was an error parsing your YAML front matter' ) ; } return $ options ; } | Parse YAML data and return an array . |
1,423 | public static function convert ( array $ array ) { if ( function_exists ( 'yaml_emit' ) ) { $ yaml = yaml_emit ( $ array ) ; $ yaml = explode ( "\n" , $ yaml ) ; array_shift ( $ yaml ) ; array_pop ( $ yaml ) ; array_pop ( $ yaml ) ; return implode ( "\n" , $ yaml ) ; } return spyc_dump ( $ array ) ; } | Convert an array into a YAML string . |
1,424 | public function offsetExists ( $ key ) { $ langs = Languages :: getInstance ( $ this -> getCategory ( ) ) ; return isset ( $ langs [ $ this -> code ] [ $ key ] ) ; } | Checking of existence of a content by key |
1,425 | public function offsetGet ( $ key ) { $ langs = Languages :: getInstance ( $ this -> getCategory ( ) ) ; return ( isset ( $ langs [ $ this -> code ] [ $ key ] ) ) ? $ langs [ $ this -> code ] [ $ key ] : $ langs [ $ langs -> getDefault ( ) ] [ $ key ] ; } | Get a text by key |
1,426 | public function copySubtree ( $ fromLocationID , $ toLocationID , $ name = false ) { $ this -> repository -> setCurrentUser ( $ this -> repository -> getUserService ( ) -> loadUser ( $ this -> adminID ) ) ; $ locationService = $ this -> repository -> getLocationService ( ) ; $ contentService = $ this -> repository -> getContentService ( ) ; try { $ fromLocation = $ locationService -> loadLocation ( $ fromLocationID ) ; $ toLocation = $ locationService -> loadLocation ( $ toLocationID ) ; $ newLocation = $ locationService -> copySubtree ( $ fromLocation , $ toLocation ) ; if ( $ name ) { $ contentInfo = $ newLocation -> getContentInfo ( ) ; $ contentDraft = $ contentService -> createContentDraft ( $ contentInfo ) ; $ contentUpdateStruct = $ contentService -> newContentUpdateStruct ( ) ; $ fields = $ contentDraft -> fields ; foreach ( $ fields as $ key => $ field ) { switch ( $ key ) { case 'title' : $ contentUpdateStruct -> setField ( 'title' , $ name ) ; break ; case 'activated' : $ contentUpdateStruct -> setField ( 'activated' , new Value ( false ) ) ; break ; default : break ; } } $ contentUpdateStruct -> initialLanguageCode = $ contentInfo -> mainLanguageCode ; $ contentDraft = $ contentService -> updateContent ( $ contentDraft -> versionInfo , $ contentUpdateStruct ) ; $ contentService -> publishVersion ( $ contentDraft -> versionInfo ) ; } return $ newLocation -> getContentInfo ( ) -> mainLocationId ; } catch ( UnauthorizedException $ e ) { throw new \ RuntimeException ( $ e -> getMessage ( ) ) ; } catch ( NotFoundException $ e ) { throw new \ RuntimeException ( $ e -> getMessage ( ) ) ; } catch ( InvalidArgumentException $ e ) { throw new \ RuntimeException ( $ e -> getMessage ( ) ) ; } catch ( BadStateException $ e ) { throw new \ RuntimeException ( $ e -> getMessage ( ) ) ; } catch ( ContentFieldValidationException $ e ) { throw new \ RuntimeException ( $ e -> getMessage ( ) ) ; } catch ( ContentValidationException $ e ) { throw new \ RuntimeException ( $ e -> getMessage ( ) ) ; } } | Copy content subtree |
1,427 | public function get ( $ key ) { if ( isset ( $ this -> map [ $ key ] ) ) { return $ this -> map [ $ key ] ; } return null ; } | Get the context identified by the given key . |
1,428 | public static function formatMDC ( $ ctxData ) { if ( $ ctxData ) { $ stack = array ( ) ; foreach ( $ ctxData as $ key => $ value ) { $ stack [ ] = "{$key}={$value}" ; } $ ctx = implode ( ' ' , $ stack ) ; } else { $ ctx = '' ; } return $ ctx ; } | Format a context as a space separated key = value string . |
1,429 | protected function getCellOptions ( $ options ) { $ cellOptions = $ options [ 'cell-options' ] ; $ inheritableOptions = $ this -> getInheritableOptions ( ) ; foreach ( $ inheritableOptions as $ inheritableOption ) { $ cellOptions [ $ inheritableOption ] = isset ( $ cellOptions [ $ inheritableOption ] ) ? $ cellOptions [ $ inheritableOption ] : $ options [ $ inheritableOption ] ; } if ( isset ( $ cellOptions [ 'translate_content' ] ) && $ cellOptions [ 'translate_content' ] ) { $ cellOptions [ 'translator' ] = $ this -> translator ; } return $ cellOptions ; } | Returns the options for the cell |
1,430 | protected function getHeaderOptions ( $ options ) { $ headerOptions = $ options [ 'header-options' ] ; $ inheritableOptions = $ this -> getInheritableOptions ( ) ; foreach ( $ inheritableOptions as $ inheritableOption ) { $ headerOptions [ $ inheritableOption ] = isset ( $ headerOptions [ $ inheritableOption ] ) ? $ headerOptions [ $ inheritableOption ] : $ options [ $ inheritableOption ] ; } return $ headerOptions ; } | Returns the options for the header |
1,431 | public function main ( ) { if ( ! class_exists ( 'Robo\Runner' ) ) { $ this -> err ( '<error>Unable to load Robo\Runner.</error>' ) ; $ this -> err ( '' ) ; $ this -> err ( 'Make sure you have installed robo as a dependency,' ) ; $ this -> err ( 'and that Robo\Runner is registered in your autoloader.' ) ; $ this -> err ( '' ) ; $ this -> err ( 'If you are using composer run' ) ; $ this -> err ( '' ) ; $ this -> err ( '<info>$ php composer.phar require codegyre/robo</info>' ) ; $ this -> err ( '' ) ; return 1 ; } array_shift ( $ _SERVER [ 'argv' ] ) ; $ runner = new Runner ( ) ; $ runner -> file = $ this -> params [ 'config' ] ; $ runner -> execute ( ) ; } | Start the shell and interactive console . |
1,432 | public function breakParts ( $ string ) { $ parts = preg_split ( '/[\n]+(```|~~~).*[\n]/' , $ string ) ; $ string = '' ; foreach ( $ parts as $ key => $ part ) { if ( $ key % 2 === 0 ) { $ part = $ this -> removeStars ( $ part ) ; $ part = $ this -> parseComments ( $ part ) ; } else { $ part = $ this -> parseCode ( $ part ) ; } if ( $ part != '' ) { $ string .= "{$part}" ; } } return $ string ; } | Breaks a string in Markdown syntax into parts . Every other part is PHP code the rest is Markdown and will be turned into PHP comments |
1,433 | public function parseComments ( $ string ) { $ return = '' ; $ multiLineComment = false ; $ lines = preg_split ( '/[\r\n]/' , $ string ) ; foreach ( $ lines as $ key => $ line ) { if ( preg_match ( '/#\s.*/' , $ line ) ) { $ return .= str_replace ( '# ' , "// " , $ line ) . "\n" ; } elseif ( $ line != '' ) { if ( ! $ multiLineComment ) { $ multiLineComment = true ; $ return .= '/**' ; } $ return .= "\n * {$line}" ; } } if ( $ multiLineComment ) { $ return .= "\n */\n" ; } return $ return ; } | Parses a string of Markdown and returns a PHP comment block containing its text |
1,434 | public function getTableColumns ( $ tableName ) { $ sql = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = :database AND TABLE_NAME = :tableName;" ; $ columns = $ this -> raw ( $ sql , [ ':database' => $ this -> getDatabaseName ( ) , ':tableName' => $ tableName ] , 'fetchAll' ) ; $ return_array = [ ] ; foreach ( $ columns as $ c ) { $ return_array [ ] = $ c -> COLUMN_NAME ; } return $ return_array ; } | get a list of columns from a table in the current database |
1,435 | function run ( ) { $ res = $ this -> resolve ( ) ; $ ctrl = isset ( $ res [ 'controller' ] ) && $ res [ 'controller' ] !== null ? $ res [ 'controller' ] : $ this -> defaultController ; $ action = isset ( $ res [ 'action' ] ) && $ res [ 'action' ] !== null ? $ res [ 'action' ] : $ this -> defaultAction ; $ tmp = explode ( '\\' , str_replace ( '/' , '\\' , $ ctrl ) ) ; $ ctrl = '\\Controller' ; foreach ( $ tmp as $ tmp1 ) { $ ctrl .= '\\' . ucfirst ( $ tmp1 ) ; } $ controller = new $ ctrl ( [ 'params' => $ res [ 'params' ] , 'request' => $ this -> request ] ) ; $ this -> params = $ res [ 'params' ] ; if ( method_exists ( $ controller , $ action ) ) return $ controller -> $ action ( ) ; else return $ controller -> { static :: $ defaultAction } ( ) ; } | Run controller by user request |
1,436 | private function searchRouter ( $ routes ) { foreach ( $ routes as $ route ) { if ( ! preg_match_all ( '#^' . $ route [ 'request' ] . '$#' , $ this -> request , $ matches , PREG_OFFSET_CAPTURE ) ) continue ; $ matches = array_slice ( $ matches , 1 ) ; $ params = array_map ( function ( $ match , $ index ) use ( $ matches ) { if ( isset ( $ matches [ $ index + 1 ] ) && isset ( $ matches [ $ index + 1 ] [ 0 ] ) && is_array ( $ matches [ $ index + 1 ] [ 0 ] ) ) { return trim ( substr ( $ match [ 0 ] [ 0 ] , 0 , $ matches [ $ index + 1 ] [ 0 ] [ 1 ] - $ match [ 0 ] [ 1 ] ) , '/' ) ; } else { return ( isset ( $ match [ 0 ] [ 0 ] ) ? trim ( $ match [ 0 ] [ 0 ] , '/' ) : null ) ; } } , $ matches , array_keys ( $ matches ) ) ; $ route [ 'params' ] = $ params ; return $ route ; } return false ; } | Search for valide router |
1,437 | public function getConnection ( ) { if ( null === $ this -> _conn && null !== $ this -> _tableName ) { $ this -> _conn = \ Doctrine :: getConnectionByTableName ( $ this -> _tableName ) ; } return $ this -> _conn ; } | Get the connection to the database |
1,438 | public function getAuthObject ( ) { if ( ! $ this -> _resultRow ) { return false ; } if ( null === $ this -> _tableName || null === $ this -> _identityColumn || null === $ this -> _identity ) { return false ; } $ dbSelect = \ Doctrine_Query :: create ( ) -> from ( "$this->_tableName table" ) -> where ( "table.$this->_identityColumn = ?" , $ this -> _identity ) ; foreach ( $ this -> _conditions as $ condition => $ value ) { $ dbSelect -> addWhere ( $ condition , $ value ) ; } $ returnObject = $ dbSelect -> fetchOne ( ) ; if ( $ returnObject ) { return $ returnObject ; } else { return false ; } } | getAuthObject - method return auth user object with all connections between tables or false when search object doesn t exsist |
1,439 | public function Init ( $ url ) { $ urlParts = explode ( "/" , $ url ) ; $ baseUrl = "/" ; $ baseUrlConstainsVirtualPath = ! ( strcasecmp ( "/" , $ baseUrl ) === 0 ) ; $ startIndex = $ baseUrlConstainsVirtualPath ? self :: StartIndexWithVirtualPath : self :: StartIndexNoVirtualPath ; $ this -> setUrl ( $ url ) ; if ( array_key_exists ( $ startIndex , $ urlParts ) && array_key_exists ( $ startIndex + 1 , $ urlParts ) ) { $ this -> setModule ( $ urlParts [ $ startIndex ] ) ; $ this -> setAction ( $ urlParts [ $ startIndex + 1 ] ) ; } else { $ this -> Init ( $ this -> defaultUrl ) ; } } | Sets the url module and action of the current route . |
1,440 | public function setAction ( $ action ) { if ( empty ( $ action ) ) { throw new \ Exception ( "Action cannot be empty" , 0 , null ) ; } else if ( ! is_string ( $ action ) ) { throw new \ Exception ( "Action must be a string" , 0 , null ) ; } else { $ this -> action = $ action ; } } | Sets the action of the route . |
1,441 | public function setModule ( $ module ) { if ( empty ( $ module ) ) { throw new \ Exception ( "Module cannot be empty" , 0 , null ) ; } else if ( ! is_string ( $ module ) ) { throw new \ Exception ( "Module must be a string" , 0 , null ) ; } else { $ this -> module = $ module ; } } | Sets the module of the route . |
1,442 | public function save ( $ entity , $ flush = true ) { $ this -> getEntityManager ( ) -> persist ( $ entity ) ; if ( $ flush ) { $ this -> getEntityManager ( ) -> flush ( $ entity ) ; } return $ this ; } | Save and optionally flush an entity |
1,443 | public function delete ( $ entity , $ flush = true ) { $ this -> getEntityManager ( ) -> remove ( $ entity ) ; if ( $ flush ) { $ this -> getEntityManager ( ) -> flush ( ) ; } return $ this ; } | Remove and optionally flush an entity |
1,444 | protected function validService ( ) { $ empty = empty ( $ this -> service ) ; $ instance = $ this -> service instanceof \ MySQLi ; if ( $ this -> connected && $ instance && ! $ empty ) { return true ; } return false ; } | This method checks if there is a valid database connection instance |
1,445 | public function connect ( ) { if ( ! $ this -> validService ( ) ) { try { $ this -> service = new \ MySQLi ( $ this -> host , $ this -> username , $ this -> password , $ this -> database , $ this -> port ) ; if ( $ this -> service -> connect_error ) { throw new MySQLException ( "Unable to connect to Database service with the provided settings" ) ; } $ this -> connected = true ; } catch ( MySQLException $ MySQLExceptionObject ) { $ MySQLExceptionObject -> errorShow ( ) ; } } return $ this ; } | This method makes a connection to the database |
1,446 | public function disconnect ( ) { if ( $ this -> validService ( ) ) { $ this -> connected = false ; $ this -> service -> close ( ) ; } return $ this ; } | This method disconnects from this database conection |
1,447 | public function execute ( $ sql ) { try { if ( ! $ this -> validService ( ) ) { throw new MySQLException ( "Not connected to a valid database service" ) ; } return $ this -> service -> query ( $ sql ) ; } catch ( MySQLException $ MySQLExceptionObject ) { $ MySQLExceptionObject -> errorShow ( ) ; } } | This method excecutes the provided SQL statement |
1,448 | public function escape ( $ value ) { try { if ( ! $ this -> validService ( ) ) { throw new MySQLException ( "Not connected to a valid database service" ) ; } return $ this -> service -> real_escape_string ( $ value ) ; } catch ( MySQLException $ MySQLExceptionObject ) { $ MySQLExceptionObject -> errorShow ( ) ; } } | This method escapes the provided value to make it safe for queries |
1,449 | public function lastInsertId ( ) { try { if ( ! $ this -> validService ( ) ) { throw new MySQLException ( "Not connected to a valid database service" ) ; } return $ this -> service -> insert_id ; } catch ( MySQLException $ MySQLExceptionObject ) { $ MySQLExceptionObject -> errorShow ( ) ; } } | This method returns the last Id if the row inserted |
1,450 | public function affectedRows ( ) { try { if ( ! $ this -> validService ( ) ) { throw new MySQLException ( "Not connected to a valid database service" ) ; } return $ this -> service -> affected_rows ; } catch ( MySQLException $ MySQLExceptionObject ) { $ MySQLExceptionObject -> errorShow ( ) ; } } | This method returns the number of rows affected by the last SQL query executed |
1,451 | public function lastError ( ) { try { if ( ! $ this -> validService ( ) ) { throw new MySQLException ( "Not connected to a valid database service" ) ; } return $ this -> service -> error ; } catch ( MySQLException $ MySQLExceptionObject ) { $ MySQLExceptionObject -> errorShow ( ) ; } } | This method returns the last error message for the most recent MySQLi function call |
1,452 | private function insert ( $ index , $ type , $ hrefOrScript ) { self :: $ scriptList -> insert ( $ index , array ( $ type , $ hrefOrScript ) ) ; return $ this ; } | Insert a script to script list |
1,453 | public function render ( ) { $ htmlContent = '' ; foreach ( self :: $ scriptList -> toArray ( ) as $ script ) { if ( $ script [ 0 ] == 'script' ) { $ htmlContent .= '<script type="text/javascript">' . $ script [ 1 ] . '</script>' . PHP_EOL ; } else { if ( Configuration :: read ( 'html.script.test_file_existance' ) === true ) { $ scriptPath = APP_ROOT . '/public' . $ script [ 1 ] ; if ( ! file_exists ( $ scriptPath ) ) { trigger_error ( 'Script file "' . $ scriptPath . '" doesn\'t exist.' , E_USER_WARNING ) ; } } $ htmlContent .= '<script src="' . $ script [ 1 ] . '" type="text/javascript"></script>' . PHP_EOL ; } } return $ htmlContent ; } | Return HTML code for initialize all script in script list |
1,454 | public function adapt ( PDOException $ e , $ stmt = null , array $ params = null ) { if ( $ e instanceof DatabaseException ) { return $ e ; } $ dbe = new DatabaseException ( $ e , $ stmt , $ params ) ; $ code = $ e -> getCode ( ) ; switch ( $ code ) { case '42501' : $ dbe -> isAuthorizationError ( true ) ; break ; case '42710' : $ dbe -> userAlreadyExists ( true ) ; break ; case '42P04' : $ dbe -> databaseAlreadyExists ( true ) ; break ; case '42P01' : $ dbe -> tableDoesNotExist ( true ) ; break ; } return $ dbe ; } | Standard implementation of adapt that detects ANSI standard SQL states . Driver implementations should only need to override this if they report non - standard SQLSTATE codes for supported error types . |
1,455 | public function getWidth ( ) { if ( $ this -> width === null ) { $ this -> width = intval ( $ this -> systemCall ( 'tput cols' ) ) ; } return $ this -> width ; } | Returns the window s width |
1,456 | public function getHeight ( ) { if ( $ this -> height === null ) { $ this -> height = intval ( $ this -> systemCall ( 'tput lines' ) ) ; } return $ this -> height ; } | Returns the window s height |
1,457 | public function load ( array $ config = [ ] ) { $ this -> config = array_replace_recursive ( $ this -> config , $ config ) ; $ this -> enviroment ( ) ; $ this -> errors ( ) ; $ this -> templates ( ) ; $ this -> orm ( ) ; $ this -> router ( ) ; return $ this ; } | Load framework . |
1,458 | private function errors ( ) { if ( env ( 'DEV_MODE' ) ) { $ whoops = new \ Whoops \ Run ( ) ; $ whoops -> pushHandler ( new \ Whoops \ Handler \ PrettyPageHandler ( ) ) ; $ whoops -> register ( ) ; } } | Load errors strategy . |
1,459 | private function orm ( ) { if ( env ( 'LOAD_ORM' ) ) { $ capsule = new \ Illuminate \ Database \ Capsule \ Manager ( ) ; $ connections = require $ this -> config [ 'paths' ] [ 'database' ] ; foreach ( $ connections as $ connection ) { $ name = $ connection [ 'name' ] ; unset ( $ connection [ 'name' ] ) ; $ capsule -> addConnection ( $ connection , $ name ) ; } $ capsule -> setEventDispatcher ( new \ Illuminate \ Events \ Dispatcher ( new \ Illuminate \ Container \ Container ( ) ) ) ; $ capsule -> setAsGlobal ( ) ; $ capsule -> bootEloquent ( ) ; } } | Load orm strategy . |
1,460 | private function router ( ) { $ routes = require $ this -> config [ 'paths' ] [ 'routes' ] ; $ request = \ Zend \ Diactoros \ ServerRequestFactory :: fromGlobals ( ) ; $ cacheFileName = 'routes.' . filemtime ( $ this -> config [ 'paths' ] [ 'routes' ] ) . '.cache' ; $ cacheFile = $ this -> config [ 'paths' ] [ 'routesCache' ] . '/' . $ cacheFileName ; if ( ! file_exists ( $ cacheFile ) ) { array_map ( 'unlink' , glob ( $ this -> config [ 'paths' ] [ 'routesCache' ] . '/*.cache' ) ) ; } $ dispatcher = \ FastRoute \ cachedDispatcher ( function ( \ FastRoute \ RouteCollector $ r ) use ( $ routes ) { foreach ( $ routes as $ route ) { $ r -> addRoute ( $ route [ 'methods' ] , $ route [ 'endpoint' ] , $ route [ 'call' ] ) ; } } , [ 'cacheFile' => $ cacheFile , ] ) ; $ request = $ request -> withHeader ( 'lang' , $ this -> config [ 'lang' ] ) ; $ request = $ request -> withHeader ( 'config' , json_encode ( $ this -> config ) ) ; $ routeInfo = $ dispatcher -> dispatch ( $ request -> getMethod ( ) , $ request -> getUri ( ) -> getPath ( ) ) ; $ response = new \ Zend \ Diactoros \ Response ( ) ; switch ( $ routeInfo [ 0 ] ) { case \ FastRoute \ Dispatcher :: METHOD_NOT_ALLOWED : $ response -> getBody ( ) -> write ( 'METHOD NOT ALLOWED' ) ; $ response = $ response -> withStatus ( 405 ) ; $ this -> response = $ response ; break ; case \ FastRoute \ Dispatcher :: NOT_FOUND : case \ FastRoute \ Dispatcher :: FOUND : $ handler = isset ( $ routeInfo [ 1 ] ) ? $ routeInfo [ 1 ] : $ this -> config [ 'config' ] [ 'not_found_controller' ] ; $ vars = isset ( $ routeInfo [ 2 ] ) ? $ routeInfo [ 2 ] : [ ] ; $ handler = explode ( '::' , $ handler ) ; $ class = $ handler [ 0 ] ; $ method = $ handler [ 1 ] ; $ response = ( new \ SideDevOrg \ MiniPhpFw \ Resolver ( ) ) -> dispatch ( $ class , $ method , $ vars , $ request , $ response , $ middlewares = require $ this -> config [ 'paths' ] [ 'middlewares' ] ) ; if ( ! isset ( $ routeInfo [ 1 ] ) ) { $ response = $ response -> withStatus ( 404 ) ; } $ this -> response = $ response ; break ; } } | Load router strategy . |
1,461 | private function base64Decode ( $ char ) { if ( ! array_key_exists ( $ char , $ this -> charToInt ) ) { throw new \ Exception ( 'Not a valid base 64 digit: ' . $ char ) ; } return $ this -> charToInt [ $ char ] ; } | Decode single 6 - bit digit from base64 . |
1,462 | public function put ( $ key , $ value ) { return $ this -> session -> put ( $ this -> getSessionKey ( $ key ) , $ value ) ; } | Put an item in the session . |
1,463 | function & add_row ( $ name = null ) { if ( ! $ name ) { $ name = uniqid ( microtime ( true ) , true ) ; } $ this -> rows [ $ name ] = new Table_Row ( ) ; return $ this -> rows [ $ name ] ; } | Add named row in table |
1,464 | public function add ( $ name , array $ dependencies , Spec $ node ) { $ this -> nodes [ $ name ] = $ node ; $ this -> incomingEdges [ $ name ] = $ dependencies ; if ( count ( $ dependencies ) === 0 ) { $ this -> pending [ ] = $ name ; } } | Add a node to the graph . |
1,465 | public function check ( array $ input ) { if ( count ( $ this -> pending ) === 0 ) { foreach ( Arr :: keys ( $ this -> nodes ) as $ name ) { if ( count ( $ this -> incomingEdges [ $ name ] ) === 0 ) { $ this -> pending [ ] = $ name ; } } $ this -> checked = [ ] ; $ this -> results = [ ] ; $ this -> failed = false ; } while ( count ( $ this -> checked ) < count ( $ this -> nodes ) ) { if ( count ( $ this -> pending ) === 0 ) { throw new CoreException ( 'Unable to resolve constraint graph.' ) ; } $ this -> iterate ( $ input ) ; if ( $ this -> failed ) { $ this -> pending = [ ] ; break ; } } $ missing = [ ] ; $ failed = [ ] ; array_map ( function ( SpecResult $ result ) use ( & $ missing , & $ failed ) { $ missing [ ] = $ result -> getMissing ( ) ; $ failed [ ] = $ result -> getFailed ( ) ; } , $ this -> checked ) ; return new SpecResult ( Arr :: mergev ( $ missing ) , Arr :: mergev ( $ failed ) , $ this -> failed ? SpecResult :: STATUS_FAIL : SpecResult :: STATUS_PASS ) ; } | Check an input array against the SpecGraph . |
1,466 | public static function SerializeRow ( & $ Row ) { foreach ( $ Row as $ Name => & $ Value ) { if ( is_array ( $ Value ) && in_array ( $ Name , array ( 'Attributes' , 'Data' ) ) ) $ Value = empty ( $ Value ) ? NULL : serialize ( $ Value ) ; } } | Serialize Attributes and Data columns in a row . |
1,467 | public function FilterSchema ( $ Data ) { $ Fields = $ this -> Schema -> Fields ( $ this -> Name ) ; $ Result = array_intersect_key ( $ Data , $ Fields ) ; return $ Result ; } | Returns an array with only those keys that are actually in the schema . |
1,468 | public function GetWhere ( $ Where = FALSE , $ OrderFields = '' , $ OrderDirection = 'asc' , $ Limit = FALSE , $ Offset = FALSE ) { $ this -> _BeforeGet ( ) ; return $ this -> SQL -> GetWhere ( $ this -> Name , $ Where , $ OrderFields , $ OrderDirection , $ Limit , $ Offset ) ; } | Get a dataset for the model with a where filter . |
1,469 | protected function findDataByItemIds ( string $ recipeProperty , array $ itemIds , array $ modCombinationIds ) : array { $ result = [ ] ; if ( count ( $ itemIds ) > 0 ) { $ columns = [ 'r.id AS id' , 'r.name AS name' , 'r.mode AS mode' , 'IDENTITY(r2.item) AS itemId' , 'mc.order AS order' ] ; $ queryBuilder = $ this -> entityManager -> createQueryBuilder ( ) ; $ queryBuilder -> select ( $ columns ) -> from ( Recipe :: class , 'r' ) -> innerJoin ( 'r.' . $ recipeProperty , 'r2' ) -> innerJoin ( 'r.modCombinations' , 'mc' ) -> andWhere ( 'r2.item IN (:itemIds)' ) -> setParameter ( 'itemIds' , array_values ( $ itemIds ) ) -> addOrderBy ( 'r.name' , 'ASC' ) -> addOrderBy ( 'r.mode' , 'ASC' ) ; if ( count ( $ modCombinationIds ) > 0 ) { $ queryBuilder -> andWhere ( 'mc.id IN (:modCombinationIds)' ) -> setParameter ( 'modCombinationIds' , array_values ( $ modCombinationIds ) ) ; } $ result = $ this -> mapRecipeDataResult ( $ queryBuilder -> getQuery ( ) -> getResult ( ) ) ; } return $ result ; } | Finds the data of recipes having a specific item involved . |
1,470 | public function findDataByKeywords ( array $ keywords , array $ modCombinationIds = [ ] ) : array { $ result = [ ] ; if ( count ( $ keywords ) > 0 ) { $ columns = [ 'r.id AS id' , 'r.name AS name' , 'r.mode AS mode' , 'mc.order AS order' ] ; $ queryBuilder = $ this -> entityManager -> createQueryBuilder ( ) ; $ queryBuilder -> select ( $ columns ) -> from ( Recipe :: class , 'r' ) -> innerJoin ( 'r.modCombinations' , 'mc' ) ; $ index = 0 ; foreach ( $ keywords as $ keyword ) { $ queryBuilder -> andWhere ( 'r.name LIKE :keyword' . $ index ) -> setParameter ( 'keyword' . $ index , '%' . addcslashes ( $ keyword , '\\%_' ) . '%' ) ; ++ $ index ; } if ( count ( $ modCombinationIds ) > 0 ) { $ queryBuilder -> andWhere ( 'mc.id IN (:modCombinationIds)' ) -> setParameter ( 'modCombinationIds' , array_values ( $ modCombinationIds ) ) ; } $ result = $ this -> mapRecipeDataResult ( $ queryBuilder -> getQuery ( ) -> getResult ( ) ) ; } return $ result ; } | Finds the data of the recipes with the specified keywords . |
1,471 | protected function mapRecipeDataResult ( array $ recipeData ) : array { $ result = [ ] ; foreach ( $ recipeData as $ data ) { $ result [ ] = RecipeData :: createFromArray ( $ data ) ; } return $ result ; } | Maps the query result to instances of RecipeData . |
1,472 | public function removeOrphans ( ) : void { $ recipeIds = $ this -> findOrphanedIds ( ) ; if ( count ( $ recipeIds ) > 0 ) { $ this -> removeIds ( $ recipeIds ) ; } } | Removes any orphaned recipes i . e . recipes no longer used by any combination . |
1,473 | protected function removeIds ( array $ recipeIds ) : void { $ queryBuilder = $ this -> entityManager -> createQueryBuilder ( ) ; $ queryBuilder -> delete ( RecipeIngredient :: class , 'ri' ) -> andWhere ( 'ri.recipe IN (:recipeIds)' ) -> setParameter ( 'recipeIds' , array_values ( $ recipeIds ) ) ; $ queryBuilder -> getQuery ( ) -> execute ( ) ; $ queryBuilder = $ this -> entityManager -> createQueryBuilder ( ) ; $ queryBuilder -> delete ( RecipeProduct :: class , 'rp' ) -> andWhere ( 'rp.recipe IN (:recipeIds)' ) -> setParameter ( 'recipeIds' , array_values ( $ recipeIds ) ) ; $ queryBuilder -> getQuery ( ) -> execute ( ) ; $ queryBuilder = $ this -> entityManager -> createQueryBuilder ( ) ; $ queryBuilder -> delete ( Recipe :: class , 'r' ) -> andWhere ( 'r.id IN (:recipeIds)' ) -> setParameter ( 'recipeIds' , array_values ( $ recipeIds ) ) ; $ queryBuilder -> getQuery ( ) -> execute ( ) ; } | Removes the recipes with the specified ids from the database . |
1,474 | public function replace ( array $ config ) : ConfigInterface { foreach ( $ config as $ key => $ configuration ) { $ this -> set ( $ key , $ configuration ) ; } return $ this ; } | Merge array replace config |
1,475 | final protected function mergeConfigInstance ( ConfigInterface $ config , ConfigInterface $ instance = null ) : ConfigInterface { $ instance = $ instance ? : $ this ; $ arrayInstance = get_object_vars ( $ instance ) ; $ arrayInstance [ ] = true ; end ( $ arrayInstance ) ; $ increment = key ( $ arrayInstance ) ; unset ( $ arrayInstance ) ; foreach ( get_object_vars ( $ config ) as $ key => $ value ) { if ( isset ( $ instance -> { $ key } ) ) { if ( $ value instanceof Config ) { if ( $ instance -> { $ key } instanceof Config ) { $ instance -> mergeConfigInstance ( $ value , $ instance -> { $ key } ) ; continue ; } $ instance -> { $ key } = $ value ; continue ; } if ( is_numeric ( $ key ) && is_int ( abs ( $ key ) ) ) { $ key = $ increment ; $ increment ++ ; } } $ instance -> { $ key } = $ value ; } return $ instance ; } | Method to handle merge config |
1,476 | public function execute ( $ state , Event & $ event ) { $ method = 'on_' . $ state ; if ( method_exists ( $ this , $ method ) ) { call_user_func_array ( array ( $ this , $ method ) , array ( $ event ) ) ; } } | entry point . determines which on_ method to call based on configuration and state . |
1,477 | protected function getLayoutType ( ) { $ detector = new MobileDetect ( ) ; $ isMobile = $ detector -> isMobile ( ) ; $ isTablet = $ detector -> isTablet ( ) ; unset ( $ detector ) ; return array ( 'isMobile' => $ isMobile , 'isTablet' => $ isTablet , 'isDesktop' => ( ! $ isMobile && ! $ isTablet ) ) ; } | determines if we are dealing with a computer or mobile device |
1,478 | public function getCol ( string $ query , array $ criteria = [ ] ) : array { try { $ results = $ this -> dbConn -> fetchCol ( $ query , $ criteria ) ; return is_array ( $ results ) ? $ results : [ ] ; } catch ( \ PDOException $ pdoException ) { throw $ this -> prepareDatabaseException ( $ pdoException , $ query , $ criteria ) ; } } | given a query returns all of the returns the first column for all returned rows . returns an empty array if nothing is selected or nothing could be selected . |
1,479 | protected function prepareDatabaseException ( \ PDOException $ pdoException , string $ query , array $ criteria = [ ] ) : DatabaseException { $ databaseException = new DatabaseException ( $ pdoException -> getMessage ( ) , ( int ) $ pdoException -> getCode ( ) , $ pdoException ) ; $ query = $ this -> getStatement ( $ query , $ criteria ) ; $ databaseException -> setQuery ( $ query ) ; return $ databaseException ; } | uses the parameters to prepare one of our own exceptions and returns it . |
1,480 | public function getVar ( string $ query , array $ criteria = [ ] ) { try { return $ this -> dbConn -> fetchValue ( $ query , $ criteria ) ; } catch ( \ PDOException $ pdoException ) { throw $ this -> prepareDatabaseException ( $ pdoException , $ query , $ criteria ) ; } } | given a query returns the first column of the first row . returns null if nothing is selected or nothing could be selected . |
1,481 | public function getRow ( string $ query , array $ criteria = [ ] ) : array { try { $ results = $ this -> dbConn -> fetchOne ( $ query , $ criteria ) ; return is_array ( $ results ) ? $ results : [ ] ; } catch ( \ PDOException $ pdoException ) { throw $ this -> prepareDatabaseException ( $ pdoException , $ query , $ criteria ) ; } } | given a query returns all columns of the first row returned . returns an empty array if nothing is selected or nothing could be selected . |
1,482 | public function getMap ( string $ query , array $ criteria = [ ] ) : array { try { $ map = [ ] ; foreach ( $ this -> dbConn -> yieldAll ( $ query , $ criteria ) as $ result ) { $ key = array_shift ( $ result ) ; $ value = sizeof ( $ result ) === 1 ? array_shift ( $ result ) : $ result ; $ map [ $ key ] = $ value ; } return $ map ; } catch ( \ PDOException $ pdoException ) { throw $ this -> prepareDatabaseException ( $ pdoException , $ query , $ criteria ) ; } } | given a query returns an array indexed by the first column and containing the subsequent columns as the values . returns an empty array if nothing is selected or could be selected |
1,483 | public function getResults ( string $ query , array $ criteria = [ ] ) : array { try { $ results = $ this -> dbConn -> fetchAll ( $ query , $ criteria ) ; return is_array ( $ results ) ? $ results : [ ] ; } catch ( \ PDOException $ pdoException ) { throw $ this -> prepareDatabaseException ( $ pdoException , $ query , $ criteria ) ; } } | returns an array of all results selected or an empty array if nothing was selected or nothing could be selected . |
1,484 | protected function insertMultiple ( string $ table , array $ values ) : ? array { $ columns = array_keys ( $ values [ 0 ] ) ; if ( $ this -> verifyColumns ( $ columns , $ values ) ) { $ parenthetical = $ this -> placeholders ( sizeof ( $ columns ) ) ; $ parentheticals = $ this -> placeholders ( sizeof ( $ values ) , $ parenthetical , false ) ; $ columns = join ( ", " , $ columns ) ; $ statement = "INSERT INTO $table ($columns) VALUES $parentheticals" ; return $ this -> insertExecute ( $ statement , $ this -> mergeBindings ( $ values ) ) ; } return null ; } | used when inserting multiple rows into the database in a single query . more complex than inserting a single row multiple times but some tests online indicate this is faster . |
1,485 | protected function mergeBindings ( array ... $ arrays ) : array { $ bindings = [ ] ; array_walk_recursive ( $ arrays , function ( $ x ) use ( & $ bindings ) { $ bindings [ ] = $ x ; } ) ; return $ bindings ; } | merges the list of arrays it receives from the calling scope into a single array adding each value sequentially without overriding keys or other such problems . |
1,486 | protected function insertSingle ( string $ table , array $ values ) : ? array { $ statement = $ this -> insertBuild ( $ table , $ values ) ; return $ this -> insertExecute ( $ statement , $ values ) ; } | produces a SQL query using the parameters |
1,487 | protected function insertBuild ( string $ table , array $ values ) : string { $ columns = array_keys ( $ values ) ; $ separator = $ this -> columnSuffix . ", " . $ this -> columnPrefix ; $ columns = $ this -> columnPrefix . join ( $ separator , $ columns ) . $ this -> columnSuffix ; $ bindings = $ this -> placeholders ( sizeof ( $ values ) ) ; return "INSERT INTO $table ($columns) VALUES $bindings" ; } | as the mysql implementation of this object includes an upsert query which begins with teh same syntax as our insert here this method builds the insert and returns it . this allows us to use the same logic for both the general insert query as well as the mysql specific upsert one . |
1,488 | public static function parseTag ( $ tag ) { $ tag = explode ( '_' , strtr ( trim ( $ tag ) , '-' , '_' ) ) ; $ language = self :: getLanguage ( strtolower ( $ tag [ 0 ] ) ) ; $ region = '' ; if ( isset ( $ tag [ 1 ] ) ) { $ region = self :: getRegion ( strtoupper ( $ tag [ 1 ] ) ) ; } return array ( $ language , $ region ) ; } | Parse language tag . |
1,489 | private function loadStaticFiles ( ) { $ staticDir = $ this -> registry -> get ( "_staticDir" ) ; $ staticDir = str_replace ( "\\" , "/" , $ staticDir ) ; if ( ! empty ( $ staticDir ) ) { $ dItr = new \ RecursiveDirectoryIterator ( $ staticDir ) ; $ rItrItr = new \ RecursiveIteratorIterator ( $ dItr , \ RecursiveIteratorIterator :: SELF_FIRST ) ; foreach ( $ rItrItr as $ file ) { $ path = $ file -> getRealPath ( ) ; if ( $ file -> isFile ( ) ) { $ path = str_replace ( "\\" , "/" , $ path ) ; $ shortUrl = str_replace ( $ staticDir , "" , $ path ) ; $ mimeTypes = $ this -> registry -> get ( "mimeTypes" ) ; $ ext = strtolower ( pathinfo ( $ path , PATHINFO_EXTENSION ) ) ; if ( in_array ( $ ext , array_keys ( $ mimeTypes ) ) ) { $ res = $ this -> registry -> get ( "Response.Ok" ) -> exec ( ) ; $ res -> headers -> set ( 'Content-Type' , $ mimeTypes [ $ ext ] ) ; $ res -> setContent ( Fs :: cat ( $ path ) ) ; } else { $ res = $ this -> registry -> get ( "Response.Forbidden" ) -> exec ( ) ; } $ this -> get ( $ shortUrl , function ( ) use ( $ res , $ mimeTypes ) { return $ res ; } ) ; } } } } | Handle static files |
1,490 | public function find ( ) { $ cond = call_user_func_array ( array ( $ this , 'toCondition' ) , func_get_args ( ) ) ; $ cond -> limit ( 1 ) ; $ entities = $ this -> findAll ( $ cond ) ; return $ entities -> first ( ) ; } | find by id or condtion . return first entity . |
1,491 | public function findAll ( ) { $ cond = call_user_func_array ( array ( $ this , 'toCondition' ) , func_get_args ( ) ) ; $ sql = $ cond -> toSQL ( ) ; var_dump ( $ sql , $ cond -> getParams ( ) ) ; $ sth = $ this -> query ( $ sql , $ cond -> getParams ( ) ) ; $ entities = new Entities ( $ this , $ sth ) ; return $ entities ; } | find by condition . return all entities . |
1,492 | public function update ( ) { $ args = func_get_args ( ) ; $ attributes = array_shift ( $ args ) ; $ cond = call_user_func_array ( array ( $ this , 'toCondition' ) , $ args ) ; $ sql = $ cond -> toUpdateSQL ( $ attributes ) ; var_dump ( $ sql , $ cond -> getParams ( ) ) ; $ sth = $ this -> query ( $ sql , $ cond -> getParams ( ) ) ; return $ sth -> isSuccess ( ) ; } | update by condition . |
1,493 | public function condition ( ) { $ cond = new Condition \ Condition ( ) ; $ cond -> from ( $ this -> getTableName ( ) ) ; $ cond -> setModel ( $ this ) ; return $ cond ; } | get condition instance . |
1,494 | public function toCondition ( ) { $ args = func_get_args ( ) ; $ first = array_shift ( $ args ) ; $ cond = $ this -> condition ( ) ; if ( $ first instanceof Condition \ Condition ) { return $ first ; } if ( is_numeric ( $ first ) ) { $ cond -> where -> add ( sprintf ( '%s = ?' , $ this -> getPrimaryKey ( ) ) , $ first ) ; } elseif ( is_string ( $ first ) ) { array_unshift ( $ args , $ first ) ; call_user_func_array ( array ( $ cond -> where , 'add' ) , $ args ) ; } elseif ( is_array ( $ first ) ) { if ( isset ( $ first [ 0 ] ) ) { call_user_func_array ( array ( $ cond -> where , 'add' ) , $ args ) ; } else { $ cond -> import ( $ first ) ; } } return $ cond ; } | convert to condition . |
1,495 | public function where ( ) { $ args = func_get_args ( ) ; $ cond = $ this -> condition ( ) ; $ cond = call_user_func_array ( array ( $ cond , 'where' ) , $ args ) ; return $ cond ; } | where add condition and return . |
1,496 | public static function core ( $ str ) { $ str = _String :: normalizePunctuationSpaces ( $ str ) ; $ str = mb_strtolower ( trim ( $ str ) ) ; $ str = _String :: normalizeSpaces ( $ str ) ; return $ str ; } | clean string and leaves only matter |
1,497 | public static function autoConfigure ( $ configFile = null ) { Maestrano_Config_Client :: with ( 'dev-platform' ) -> configure ( $ configFile ) ; Maestrano_Config_Client :: with ( 'dev-platform' ) -> loadMarketplacesConfig ( ) ; } | Method to fetch config from the dev - platform |
1,498 | public static function paramWithPreset ( $ preset , $ parameter ) { if ( empty ( $ preset ) ) { throw new Maestrano_Config_Error ( 'Empty preset name, make sure you are using \'Maestrano::with($marketplace)->someMethod()\'' ) ; } if ( ! array_key_exists ( $ preset , self :: $ config ) ) { throw new Maestrano_Config_Error ( "Maestrano was not configured for preset '$preset'" ) ; } if ( array_key_exists ( $ parameter , self :: $ config [ $ preset ] ) ) { return self :: $ config [ $ preset ] [ $ parameter ] ; } else { throw new Maestrano_Config_Error ( "Preset '$preset' does not contain parameter '$parameter'" ) ; } } | Return a configuration parameter from a present |
1,499 | public static function toMetadataWithPreset ( $ preset ) { $ config = array ( 'nid' => Maestrano :: with ( $ preset ) -> param ( 'nid' ) , 'marketplace' => Maestrano :: with ( $ preset ) -> param ( 'marketplace' ) , 'environment' => Maestrano :: with ( $ preset ) -> param ( 'environment' ) , 'app' => array ( 'host' => Maestrano :: with ( $ preset ) -> param ( 'app.host' ) , 'synchronization_start_path' => Maestrano :: with ( $ preset ) -> param ( 'app.synchronization_start_path' ) , 'synchronization_toggle_path' => Maestrano :: with ( $ preset ) -> param ( 'app.synchronization_toggle_path' ) , 'synchronization_status_path' => Maestrano :: with ( $ preset ) -> param ( 'app.synchronization_status_path' ) ) , 'api' => array ( 'id' => Maestrano :: with ( $ preset ) -> param ( 'api.id' ) , 'key' => Maestrano :: with ( $ preset ) -> param ( 'api.key' ) , 'host' => Maestrano :: with ( $ preset ) -> param ( 'api.host' ) , 'base' => Maestrano :: with ( $ preset ) -> param ( 'api.base' ) , 'version' => Maestrano :: with ( $ preset ) -> param ( 'api.version' ) , 'lang' => Maestrano :: with ( $ preset ) -> param ( 'api.lang' ) , 'lang_version' => Maestrano :: with ( $ preset ) -> param ( 'api.lang_version' ) ) , 'sso' => array ( 'idm' => Maestrano :: with ( $ preset ) -> param ( 'sso.idm' ) , 'init_path' => Maestrano :: with ( $ preset ) -> param ( 'sso.init_path' ) , 'consume_path' => Maestrano :: with ( $ preset ) -> param ( 'sso.consume_path' ) , 'idp' => Maestrano :: with ( $ preset ) -> param ( 'sso.idp' ) , ) , 'connec' => array ( 'host' => Maestrano :: with ( $ preset ) -> param ( 'connec.host' ) , 'base_path' => Maestrano :: with ( $ preset ) -> param ( 'connec.base_path' ) , 'timeout' => Maestrano :: with ( $ preset ) -> param ( 'connec.timeout' ) ) , 'webhooks' => array ( 'account' => array ( 'group_path' => Maestrano :: with ( $ preset ) -> param ( 'webhooks.account.group_path' ) , 'group_user_path' => Maestrano :: with ( $ preset ) -> param ( 'webhooks.account.group_user_path' ) ) , 'connec' => array ( 'external_ids' => Maestrano :: with ( $ preset ) -> param ( 'webhooks.connec.external_ids' ) , 'initialization_path' => Maestrano :: with ( $ preset ) -> param ( 'webhooks.connec.initialization_path' ) , 'notification_path' => Maestrano :: with ( $ preset ) -> param ( 'webhooks.connec.notification_path' ) ) ) ) ; return json_encode ( $ config ) ; } | Return a json string describing the configuration currently used by the PHP bindings |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.