idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
27,400
public function getIndexOf ( string $ name ) : int { if ( array_key_exists ( $ name , $ this -> record ) == false ) { return - 1 ; } $ keyArray = array_keys ( $ this -> record ) ; return array_search ( $ name , $ keyArray ) ; }
Returns the position of the field called name within the record or - 1 if it cannot be found . Field names are not case - sensitive . If more than one field matches the first one is returned .
27,401
public function setNull ( $ name ) : void { if ( $ this -> contains ( $ name ) == false ) { return ; } $ this -> record [ $ name ] = null ; }
Sets the value of field index to null . If the field does not exist nothing happens .
27,402
public function makeTwigEnvironment ( ContainerInterface $ dic ) { $ config = $ this -> app -> getConfig ( ) ; $ options = [ 'debug' => $ config -> get ( 'app.debug' ) ] ; if ( $ config -> has ( 'path.templates_cache' ) ) { $ options [ 'cache' ] = $ config -> get ( 'path.templates_cache' ) ; } else if ( $ config -> has ( 'path.storage' ) ) { $ options [ 'cache' ] = $ config -> get ( 'path.storage' ) . '/twig' ; } $ env = new TwigEnvironment ( $ dic -> resolve ( 'Twig_LoaderInterface' ) , $ options ) ; $ extensions = array_merge ( [ 'Autarky\TwigTemplating\Extensions\PartialExtension' , 'Autarky\TwigTemplating\Extensions\UrlGenerationExtension' => [ 'Autarky\Routing\UrlGenerator' ] , 'Autarky\TwigTemplating\Extensions\SessionExtension' => [ 'Symfony\Component\HttpFoundation\Session\Session' ] , ] , $ this -> app -> getConfig ( ) -> get ( 'twig.extensions' , [ ] ) ) ; foreach ( $ extensions as $ extension => $ dependencies ) { if ( is_int ( $ extension ) ) { $ env -> addExtension ( $ dic -> resolve ( $ dependencies ) ) ; } else { foreach ( ( array ) $ dependencies as $ dependency ) { if ( ! $ dic -> isBound ( $ dependency ) ) { continue 2 ; } } $ env -> addExtension ( $ dic -> resolve ( $ extension ) ) ; } } return $ env ; }
Make the twig environment .
27,403
public function move ( $ move ) { $ last_move = $ this -> getLastMoveIndex ( ) ; if ( is_array ( $ last_move ) && array_shift ( $ last_move ) === false ) { throw new RockPaperScissorsSpockLizardException ( 'Cannot set another move until the previous move has been played' ) ; } if ( empty ( $ move ) ) { throw new RockPaperScissorsSpockLizardException ( 'Move cannot be empty' ) ; } $ this -> moves [ ] = [ $ move => false ] ; return $ this ; }
Queue a play
27,404
public function lastMoveIsPlayed ( ) { $ moves = $ this -> getMoveHistory ( ) ; $ offset = count ( $ moves ) - 1 ; $ last_item = $ this -> moves [ $ offset ] ; $ this -> moves [ $ offset ] [ key ( $ last_item ) ] = true ; return $ this ; }
Mark Last Move As Played
27,405
public function getLastMoveIndex ( ) { $ move_history = $ this -> getMoveHistory ( ) ; $ last_move = end ( $ move_history ) ; reset ( $ this -> moves ) ; return $ last_move ; }
Get Last Move
27,406
public function isBot ( $ is_bot = null ) { if ( $ is_bot === null ) { return $ this -> is_bot ; } $ this -> is_bot = ( bool ) $ is_bot ; return $ this ; }
Is Bot? or set as a bot
27,407
public static function code_403 ( $ message = null , $ exit = true ) { if ( $ message !== null ) { $ message = ' (' . $ message . ')' ; } header ( 'HTTP/1.1 403 Forbidden' , true ) ; echo '403 Forbidden' . $ message ; if ( $ exit ) { exit ( ) ; } }
Throw a 403 error
27,408
public static function code_404 ( $ message = null , $ exit = true ) { if ( $ message !== null ) { $ message = ' (' . $ message . ')' ; } header ( 'HTTP/1.1 404 Not Found' . $ message , true ) ; echo '404 Not Found' . $ message ; if ( $ exit ) { exit ( ) ; } }
Throw a 404 error
27,409
public function createService ( ServiceLocatorInterface $ serviceLocator , $ cName = null , $ rName = null ) { $ config = $ serviceLocator -> has ( 'Config' ) ? $ serviceLocator -> get ( 'Config' ) : array ( ) ; $ routerClass = 'Zend\Mvc\Router\Http\TreeRouteStack' ; $ routerConfig = isset ( $ config [ 'router' ] ) ? $ config [ 'router' ] : array ( ) ; if ( $ rName === 'ConsoleRouter' || ( $ cName === 'router' && Console :: isConsole ( ) ) ) { $ routerClass = 'Zend\Mvc\Router\Console\SimpleRouteStack' ; $ routerConfig = isset ( $ config [ 'console' ] [ 'router' ] ) ? $ config [ 'console' ] [ 'router' ] : array ( ) ; } else { $ annotationRouter = $ serviceLocator -> get ( 'TjoAnnotationRouter\AnnotationRouter' ) ; $ annotationRouter -> updateRouteConfig ( $ routerConfig ) ; } if ( isset ( $ routerConfig [ 'router_class' ] ) && class_exists ( $ routerConfig [ 'router_class' ] ) ) { $ routerClass = $ routerConfig [ 'router_class' ] ; } if ( ! isset ( $ routerConfig [ 'route_plugins' ] ) ) { $ routePluginManager = $ serviceLocator -> get ( 'RoutePluginManager' ) ; $ routerConfig [ 'route_plugins' ] = $ routePluginManager ; } $ factory = sprintf ( '%s::factory' , $ routerClass ) ; return call_user_func ( $ factory , $ routerConfig ) ; }
Create and return the router
27,410
public static function readConfigFile ( $ path = '' ) { $ path = str_replace ( '..' , '' , $ path ) ; $ realPath = self :: $ configDir . DIRECTORY_SEPARATOR . str_replace ( '/' , DIRECTORY_SEPARATOR , $ path ) ; $ cachedFile = self :: $ cachePath . DIRECTORY_SEPARATOR . str_replace ( '/' , DIRECTORY_SEPARATOR , $ path ) . '.php' ; if ( file_exists ( $ cachedFile ) && self :: $ config [ 'cache' ] === true ) { $ conf = require_once ( $ cachedFile ) ; } else { if ( file_exists ( $ realPath ) ) { switch ( self :: $ configExt ) { case 'xml' : $ objConfig = simplexml_load_file ( $ realPath ) ; $ conf = json_decode ( json_encode ( $ objConfig ) , true ) ; break ; case 'yaml' : $ conf = Yaml :: parse ( file_get_contents ( $ realPath ) ) ; break ; default : $ conf = require_once $ realPath ; break ; } if ( self :: $ config [ 'cache' ] === true ) { touch ( $ cachedFile ) ; $ str = "<?php\nreturn " . var_export ( $ conf , true ) . ";\n" ; file_put_contents ( $ cachedFile , $ str ) ; } } } return $ conf ; }
Read XML Config File
27,411
public function editAction ( ) { $ this -> view -> disable ( ) ; $ id = $ this -> request -> getPost ( 'hidden_id' ) ; $ user = Users :: findFirstById ( $ id ) ; $ msg = "" ; if ( ! $ user ) { $ alert = "sukses" ; $ msg .= "User was not found" ; } if ( $ this -> request -> isPost ( ) ) { $ user -> assign ( [ 'name' => $ this -> request -> getPost ( 'name' , 'striptags' ) , 'profilesId' => $ this -> request -> getPost ( 'profile' , 'int' ) , 'email' => $ this -> request -> getPost ( 'email' , 'email' ) , 'banned' => $ this -> request -> getPost ( 'banned' ) , 'suspended' => $ this -> request -> getPost ( 'suspended' ) , 'active' => $ this -> request -> getPost ( 'active' ) ] ) ; if ( ! $ user -> save ( ) ) { $ alert = "error" ; foreach ( $ user -> getMessages ( ) as $ message ) { $ msg .= $ message . " " ; } } else { $ alert = "sukses" ; $ msg .= "User was updated successfully" ; } } $ response = new \ Phalcon \ Http \ Response ( ) ; $ response -> setContentType ( 'application/json' , 'UTF-8' ) ; $ response -> setJsonContent ( array ( '_id' => $ this -> request -> getPost ( "name" ) , 'alert' => $ alert , 'msg' => $ msg ) ) ; return $ response -> send ( ) ; }
Saves the user from the edit action
27,412
public function changePasswordAction ( ) { $ form = new ChangePasswordForm ( ) ; if ( $ this -> request -> isPost ( ) ) { if ( ! $ form -> isValid ( $ this -> request -> getPost ( ) ) ) { foreach ( $ form -> getMessages ( ) as $ message ) { $ this -> flash -> error ( $ message ) ; } } else { $ user = $ this -> auth -> getUser ( ) ; $ user -> password = $ this -> security -> hash ( $ this -> request -> getPost ( 'password' ) ) ; $ user -> mustChangePassword = 'N' ; $ passwordChange = new PasswordChanges ( ) ; $ passwordChange -> user = $ user ; $ passwordChange -> ipAddress = $ this -> request -> getClientAddress ( ) ; $ passwordChange -> userAgent = $ this -> request -> getUserAgent ( ) ; if ( ! $ passwordChange -> save ( ) ) { $ this -> flash -> error ( $ passwordChange -> getMessages ( ) ) ; } else { $ this -> flash -> success ( 'Your password was successfully changed' ) ; Tag :: resetInput ( ) ; } } } $ this -> view -> form = $ form ; }
Users must use this action to change its password
27,413
public function cleanArray ( array $ data ) { $ cleanedArray = [ ] ; foreach ( $ data as $ key => $ value ) { $ cleanedArray [ $ key ] = \ is_array ( $ value ) ? $ this -> cleanArray ( $ value ) : $ this -> getSafeArray ( $ key , $ data ) ; } return $ cleanedArray ; }
Scrub an entire array of potentially harmful client data with htmlspecialchars .
27,414
public function getFromArray ( string $ key , array $ data , string $ default = null ) { $ value = $ default ; if ( \ array_key_exists ( $ key , $ data ) ) { $ value = $ data [ $ key ] ; } return $ value ; }
Get a value from an array returning the default value when not present in the array .
27,415
public function getSafeArray ( string $ key , array & $ data , string $ default = null ) { $ value = $ this -> getFromArray ( $ key , $ data , $ default ) ; return \ htmlspecialchars ( $ value ) ; }
Get a value from an array returning the default value when not present in the array and stripping HTML tags .
27,416
function loadJsonAsArray ( $ pFile ) { $ contents = \ file_get_contents ( $ pFile ) ; $ returnValue = \ json_decode ( $ contents , true ) ; if ( ! $ this -> isArray ( $ returnValue ) ) { $ returnValue = [ ] ; } return $ returnValue ; }
Load the attribute map from file .
27,417
function saveFile ( $ pFileName , $ pContent ) { $ directory = \ dirname ( $ pFileName ) ; if ( ! \ is_dir ( $ directory ) ) { try { $ madeDir = \ mkdir ( $ directory , 0755 , TRUE ) ; } catch ( \ Exception $ err ) { throw new \ Exception ( "mkdir: Unable make directory '{$directory}'." ) ; } } $ fileSaved = \ file_put_contents ( $ pFileName , $ pContent ) ; if ( $ fileSaved === FALSE ) { throw new \ Exception ( "file_put_contents: Unable to save file '{$pFileName}'." ) ; } return $ fileSaved ; }
Save content to a file ; but will also make the directory if it does not exists .
27,418
public static function create ( string $ extension = '' ) : array { static :: init ( ) ; $ filePath = $ fileName = '' ; if ( static :: verifyPath ( static :: $ hashFileDir ) ) { $ exists = true ; while ( $ exists === true ) { $ hash = Random :: hash ( ) ; $ hashDir = \ implode ( '/' , \ str_split ( \ substr ( $ hash , 0 , static :: $ hashFileDirDepth ) , 1 ) ) ; $ filePath = static :: normalizePath ( \ sprintf ( '%s%s' , static :: $ hashFileDir , $ hashDir ) ) ; $ filePath .= DIRECTORY_SEPARATOR ; $ fileName = \ sprintf ( '%s.%s' , $ hash , $ extension ) ; $ exists = File :: exists ( $ filePath . $ fileName ) ; } } return [ 'path' => $ filePath , 'name' => $ fileName ] ; }
Returns unique hash file name .
27,419
public static function getPath ( string $ hash = '' ) : string { static :: init ( ) ; $ hashDir = \ implode ( '/' , \ str_split ( \ substr ( $ hash , 0 , static :: $ hashFileDirDepth ) , 1 ) ) ; $ filePath = static :: normalizePath ( \ sprintf ( '%s%s' , static :: $ hashFileDir , $ hashDir ) ) ; $ filePath .= DIRECTORY_SEPARATOR ; return $ filePath ; }
Returns hash file path
27,420
public function checkModified ( BuildInterface $ build ) { $ result = new Result ( ) ; $ result -> setSource ( 'build always task' ) ; $ result -> setStatus ( Result :: CHANGED ) ; return $ result ; }
Check if this modification set has been modified .
27,421
public static function makeFirstLevelArray ( $ multilevelData ) { $ it = new \ RecursiveIteratorIterator ( new \ RecursiveArrayIterator ( $ multilevelData ) ) ; $ keyValueArr = [ ] ; foreach ( $ it as $ k => $ v ) { $ decoded = json_decode ( $ v ) ; if ( ! $ decoded || is_int ( $ decoded ) ) { throw new JsonException ( 'Not json.' ) ; } if ( is_array ( $ decoded ) || is_object ( $ decoded ) ) { $ nestedIt = new \ RecursiveIteratorIterator ( new \ RecursiveArrayIterator ( $ decoded ) ) ; foreach ( $ nestedIt as $ nK => $ nV ) { $ keyValueArr [ $ nK ] = $ nV ; } continue ; } $ keyValueArr [ $ k ] = $ v ; } return $ keyValueArr ; }
Receive data and make first - level array
27,422
public static function getDelimitersKeys ( array $ data , $ delimitersNumbers ) { $ delimiterKeys = [ ] ; $ elementsNumbers = count ( $ data ) ; if ( $ elementsNumbers <= $ delimitersNumbers ) { throw new RestructureException ( "Elements number not bigger than delimiter." ) ; } $ portion = ( $ elementsNumbers - 1 ) / $ delimitersNumbers ; $ portion = ( int ) $ portion ; $ stablePortion = $ portion ; foreach ( $ data as $ key => $ value ) { if ( ! is_int ( $ key ) ) { throw new RestructureException ( "Associative array. Expect indexed." ) ; } if ( $ key === $ portion ) { $ delimiterKeys [ ] = $ key ; $ portion += $ stablePortion ; } } return $ delimiterKeys ; }
Allow to detect arrays keys that divide array into portions by delimiter number .
27,423
public function validateTemplate ( $ attribute , array $ params ) { if ( ! isset ( self :: $ config -> templates [ $ this -> template ] ) ) { $ this -> addError ( 'template' , "Unable to find template '{$this->template}'." ) ; } }
Validates the template for this generator .
27,424
protected function runProviders ( array $ providers , array $ properties = array ( ) ) { $ data = array ( ) ; foreach ( $ providers as $ config ) { if ( is_string ( $ config ) ) { $ config = array ( $ config ) ; } $ className = array_shift ( $ config ) ; if ( isset ( self :: $ config -> providers [ $ className ] ) ) { $ config = \ CMap :: mergeArray ( self :: $ config -> providers [ $ className ] , $ config ) ; } else { $ config [ 'class' ] = $ className ; } if ( ! class_exists ( $ config [ 'class' ] ) ) { throw new Exception ( "Provider '{$config['class']}' does not exist." ) ; } $ class = new \ ReflectionClass ( $ config [ 'class' ] ) ; foreach ( $ class -> getProperties ( \ ReflectionProperty :: IS_PUBLIC ) as $ property ) { $ name = $ property -> getName ( ) ; if ( ! isset ( $ config [ $ name ] ) && isset ( $ properties [ $ name ] ) ) { $ config [ $ name ] = $ properties [ $ name ] ; } } $ provider = \ Yii :: createComponent ( $ config ) ; $ data = array_merge ( $ data , $ provider -> provide ( ) ) ; } return $ data ; }
Runs a set of providers for this generator .
27,425
protected function getTemplatePath ( ) { if ( ! isset ( $ this -> templatePath ) ) { $ this -> templatePath = self :: $ config -> templates [ $ this -> template ] . '/' . $ this -> name ; } return $ this -> templatePath ; }
Returns the template path for this generator .
27,426
protected function resolveTemplateFile ( array $ templates = array ( ) ) { $ templatePath = $ this -> getTemplatePath ( ) ; $ templates = array_merge ( $ templates , $ this -> getDefaultTemplates ( ) ) ; if ( empty ( $ templates ) ) { throw new Exception ( "No templates available." ) ; } foreach ( $ templates as $ templateFile ) { $ filePath = "$templatePath/$templateFile" ; if ( is_file ( $ filePath ) ) { return $ filePath ; } } return null ; }
Determines the template file to use for generating the file .
27,427
protected function compileInternal ( $ templateFile , array $ providers = array ( ) , array $ properties = array ( ) ) { $ providers = array_merge ( $ this -> providers , $ providers ) ; $ templateData = ! empty ( $ providers ) ? $ this -> runProviders ( $ providers , $ properties ) : array ( ) ; return $ this -> compileTemplate ( $ templateFile , $ templateData ) ; }
Compiles a specific template file using a set of providers .
27,428
protected function compileTemplate ( $ templateFile , array $ templateData ) { if ( ! isset ( self :: $ compiler ) ) { self :: $ compiler = new Compiler ( ) ; } if ( ! is_file ( $ templateFile ) ) { throw new Exception ( "Could not find template file '$templateFile'." ) ; } return self :: $ compiler -> compile ( file_get_contents ( $ templateFile ) , $ templateData ) ; }
Compiles a specific template file using the given data .
27,429
public static function findFileReferenceObjects ( array $ fileUids ) { $ entities = new ObjectStorage ( ) ; if ( ! empty ( $ fileUids ) ) { $ resourceFactory = GeneralUtility :: makeInstance ( 'TYPO3\\CMS\\Core\\Resource\\ResourceFactory' ) ; foreach ( $ fileUids as $ uid ) { $ fileReference = $ resourceFactory -> getFileReferenceObject ( $ uid ) ; $ entities -> attach ( $ fileReference -> getProperties ( ) ) ; } } return $ entities ; }
Finds FAL objects by uid
27,430
public static function downloadFile ( $ fileUid , $ additionalHeaders = array ( ) ) { $ fileRepository = GeneralUtility :: makeInstance ( 'TYPO3\\CMS\\Core\\Resource\\FileRepository' ) ; $ entity = $ fileRepository -> findByUid ( $ fileUid ) ; if ( ! $ entity ) { return false ; } $ properties = $ entity -> getProperties ( ) ; $ headers = array ( 'Pragma' => 'public' , 'Expires' => 0 , 'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0' , 'Cache-Control' => 'public' , 'Content-Description' => 'File Transfer' , 'Content-Type' => $ properties [ 'mime_type' ] , 'Content-Disposition' => 'attachment; filename="' . $ entity -> getName ( ) . '"' , 'Content-Transfer-Encoding' => 'binary' , 'Content-Length' => $ properties [ 'size' ] , ) ; if ( ! empty ( $ additionalHeaders ) ) { array_merge ( $ headers , $ additionalHeaders ) ; } try { $ response = GeneralUtility :: makeInstance ( 'TYPO3\\CMS\\Extbase\\Mvc\\Web\\Response' ) ; foreach ( $ headers as $ header => $ data ) { $ response -> setHeader ( $ header , $ data ) ; } $ response -> sendHeaders ( ) ; echo $ entity -> getContents ( ) ; exit ; } catch ( Exception $ e ) { return $ e ; } }
Download a FAL - File
27,431
static public function toJson ( $ str ) { $ data = \ json_decode ( $ str , true ) ; switch ( json_last_error ( ) ) { case JSON_ERROR_NONE : return $ data ; case JSON_ERROR_DEPTH : return array ( 'error' => 'Maximum stack depth exceeded' ) ; case JSON_ERROR_STATE_MISMATCH : return array ( 'error' => 'Underflow or the modes mismatch' ) ; case JSON_ERROR_CTRL_CHAR : return array ( 'error' => 'Unexpected control character found' ) ; case JSON_ERROR_SYNTAX : return array ( 'error' => 'Syntax error, malformed JSON' ) ; case JSON_ERROR_UTF8 : return array ( 'error' => 'Malformed UTF-8 characters, possibly incorrectly encoded' ) ; default : return array ( 'error' => 'Unknown error on JSON file' ) ; } }
Parses a json string into an array
27,432
static public function parse ( $ str , $ content_type ) { switch ( $ content_type ) { case 'json' : return self :: toJson ( $ str ) ; case 'xml' : return self :: toXml ( $ str ) ; default : return $ str ; } }
Parses the data passed into the requested data type
27,433
public function addFieldsBefore ( $ fields , $ insertBefore = null ) { foreach ( $ fields as $ field ) { if ( $ insertBefore ) { $ this -> owner -> insertBefore ( $ insertBefore , $ field ) ; } elseif ( ( $ name = $ field -> getName ( ) ) && $ this -> owner -> fieldByName ( $ name ) ) { $ this -> owner -> replaceField ( $ field -> getName ( ) , $ field ) ; } else { $ this -> owner -> push ( $ field ) ; } } }
Inserts a fields into a FieldList before a particular field if specified
27,434
protected function getEndpoint ( ) { $ locale = $ this -> getLocale ( ) ; $ account = $ this -> getAccountId ( ) ; $ method = $ this -> getPaymentMethod ( ) ; return '/' . $ locale . '/api/' . $ account . '/transactions/' . $ method . '/new' ; }
Generate the endpoint based on the current options .
27,435
public function build ( ) { $ view = new View \ AtomicKitten ; $ resultFile = new SplFileObject ( $ this -> buildSettings [ 'target' ] . 'index.html' , 'w' ) ; $ resultFile -> fwrite ( $ view -> render ( 'Generator/Index' ) ) ; }
Generate files from framework .
27,436
protected function hasContentForKey ( $ key , $ content ) : bool { if ( $ content instanceof Treadable ) { return $ content -> hasChildForKey ( $ key ) ; } if ( is_array ( $ content ) || $ content instanceof \ ArrayAccess ) { return isset ( $ content [ $ key ] ) ; } if ( is_object ( $ content ) ) { return property_exists ( $ content , $ key ) ; } return false ; }
Returns true if and only if the content provided has content at the key provided .
27,437
public function current ( ) { $ key = $ this -> keys [ $ this -> index ] ; $ this -> content = $ this -> getContentForKey ( $ key , $ this -> content ) ; return $ this -> content ; }
Returns the current content based on the current key .
27,438
public function valid ( ) { if ( ! isset ( $ this -> keys [ $ this -> index ] ) ) { return false ; } $ hasContent = $ this -> hasContentForKey ( $ this -> keys [ $ this -> index ] , $ this -> content ) ; if ( ! $ hasContent && $ this -> throwOnNotReachable ) { $ message = sprintf ( 'No current content contains new content at a key of "%s".' , $ this -> keys [ $ this -> index ] ) ; throw new PathNotReachableException ( $ this -> keys [ $ this -> index ] , $ message ) ; } return $ hasContent ; }
Returns true if content exists for the current key .
27,439
public function call ( ) { $ args = func_get_args ( ) ; $ this -> build ( $ args ) ; return $ this -> mapper -> merge ( $ this -> config ) -> execute ( $ this -> expression , $ args ) ; }
Invokes a stored procedure with the given list of arguments
27,440
public function callWith ( $ args ) { $ this -> build ( $ args ) ; return $ this -> mapper -> merge ( $ this -> config ) -> execute ( $ this -> expression , $ args ) ; }
Invokes a stored procedure with the given array of arguments
27,441
public function argTypes ( $ types ) { is_array ( $ types ) ? $ this -> argumentTypes = $ types : $ this -> argumentTypes = func_get_args ( ) ; return $ this ; }
Configures argument types
27,442
protected function filter ( array $ filter ) { if ( array_key_exists ( 'authEmail' , $ filter ) && strlen ( $ filter [ 'authEmail' ] ) > 0 ) { $ this -> select -> where -> like ( 'auth.auth_email' , $ filter [ 'authEmail' ] . '%' ) ; } if ( array_key_exists ( 'authId' , $ filter ) && $ filter [ 'authId' ] > 0 ) { $ this -> select -> where ( array ( 'history.auth_id = ?' => $ filter [ 'authId' ] ) ) ; } return $ this ; }
Filters and search
27,443
public function render ( $ __template , array $ __variables = [ ] ) { extract ( $ __variables ) ; try { ob_start ( ) ; include $ this -> getResolver ( ) -> resolve ( $ __template ) ; $ __return = ob_get_clean ( ) ; } catch ( Error $ __error ) { ob_end_clean ( ) ; throw $ __error ; } catch ( Exception $ __exception ) { ob_end_clean ( ) ; throw $ __exception ; } return $ __return ; }
Renders template .
27,444
protected function outputMultipleValues ( array $ output , $ key , $ value , $ longKey ) { $ newValue = str_replace ( $ longKey . ' ' , '' , trim ( $ value ) ) ; if ( trim ( $ value ) !== $ newValue ) { $ output [ $ key ] [ ] = $ newValue ; } else { $ last = count ( $ output [ $ key ] ) - 1 ; $ output [ $ key ] [ $ last ] = $ output [ $ key ] [ $ last ] . ' ' . $ newValue ; } return $ output ; }
Handle output with multiple values
27,445
protected function outputSingleValue ( array $ output , $ key , $ value , $ longKey ) { $ oldValue = $ output [ $ key ] ; $ newValue = trim ( str_replace ( $ longKey . ' ' , '' , trim ( $ value ) ) ) ; if ( trim ( $ value ) !== $ newValue ) { $ output [ $ key ] = [ $ oldValue , $ newValue ] ; } else { $ output [ $ key ] .= ' ' . $ newValue ; } return $ output ; }
Handle output with single value
27,446
private function convertFromDB ( $ obj ) { foreach ( $ this -> fields as $ field ) { switch ( $ field -> type ( ) ) { case self :: FIELD_TYPE_BOOL : $ obj -> { $ field -> identifier ( ) } = ( bool ) $ obj -> { $ field -> identifier ( ) } ; break ; case self :: FIELD_TYPE_INT : $ obj -> { $ field -> identifier ( ) } = ( int ) $ obj -> { $ field -> identifier ( ) } ; break ; case self :: FIELD_TYPE_FLOAT : $ obj -> { $ field -> identifier ( ) } = ( float ) $ obj -> { $ field -> identifier ( ) } ; break ; case self :: FIELD_TYPE_STR : break ; case self :: FIELD_TYPE_DATETIME : if ( $ obj -> { $ field -> identifier ( ) } === '0' ) { $ obj -> { $ field -> identifier ( ) } = false ; } else { $ d = new \ DateTime ( ) ; if ( ! is_object ( $ obj -> { $ field -> identifier ( ) } ) ) { $ d -> setTimestamp ( $ obj -> { $ field -> identifier ( ) } ) ; $ obj -> { $ field -> identifier ( ) } = $ d ; } $ obj -> { $ field -> identifier ( ) } = $ d ; } break ; case self :: FIELD_TYPE_STR_ARRAY : $ delimiter = '(^!)' ; if ( empty ( $ obj -> { $ field -> identifier ( ) } ) ) $ obj -> { $ field -> identifier ( ) } = [ ] ; else $ obj -> { $ field -> identifier ( ) } = array_map ( function ( $ v ) use ( $ delimiter ) { return stripslashes ( $ v ) ; } , explode ( $ delimiter , $ obj -> { $ field -> identifier ( ) } ) ) ; break ; case self :: FIELD_TYPE_INT_ARRAY : $ arr = empty ( $ obj -> { $ field -> identifier ( ) } ) ? [ ] : explode ( ',' , $ obj -> { $ field -> identifier ( ) } ) ; $ obj -> { $ field -> identifier ( ) } = array_map ( function ( $ v ) { return ( int ) str_replace ( '\'' , '' , $ v ) ; } , $ arr ) ; break ; case self :: FIELD_TYPE_OBJ : $ obj -> { $ field -> identifier ( ) } = empty ( $ obj -> { $ field -> identifier ( ) } ) ? new \ StdClass ( ) : json_decode ( $ obj -> { $ field -> identifier ( ) } ) ; break ; default : throw new TypeNotExistException ( ) ; } } return $ obj ; }
Check & convert Fields for Select
27,447
private function convertToDB ( $ obj ) { $ o = $ this -> getEmptyObject ( ) ; foreach ( $ this -> fields as $ field ) { if ( ! property_exists ( $ obj , $ field -> identifier ( ) ) ) continue ; if ( is_null ( $ obj -> { $ field -> identifier ( ) } ) ) { $ o -> { $ field -> identifier ( ) } = 'NULL' ; continue ; } $ val = $ obj -> { $ field -> identifier ( ) } ; switch ( $ field -> type ( ) ) { case self :: FIELD_TYPE_BOOL : $ o -> { $ field -> identifier ( ) } = $ val ? 1 : 0 ; break ; case self :: FIELD_TYPE_INT : $ o -> { $ field -> identifier ( ) } = ( int ) $ val ; break ; case self :: FIELD_TYPE_FLOAT : $ o -> { $ field -> identifier ( ) } = ( float ) $ val ; break ; case self :: FIELD_TYPE_STR : $ o -> { $ field -> identifier ( ) } = $ this -> escape ( $ val ) ; break ; case self :: FIELD_TYPE_DATETIME : if ( $ val && ! is_null ( $ val ) ) { $ o -> { $ field -> identifier ( ) } = $ val -> getTimestamp ( ) ; } else { $ o -> { $ field -> identifier ( ) } = 0 ; } break ; case self :: FIELD_TYPE_STR_ARRAY : $ delimiter = '(^!)' ; $ o -> { $ field -> identifier ( ) } = '"' . implode ( $ delimiter , array_map ( function ( $ v ) use ( $ delimiter ) { str_replace ( $ delimiter , '' , $ v ) ; } , $ val ) ) . '"' ; break ; case self :: FIELD_TYPE_INT_ARRAY : $ val = array_map ( function ( $ v ) { return "'" . ( int ) $ v . "'" ; } , $ val ) ; $ o -> { $ field -> identifier ( ) } = '"' . implode ( ',' , $ val ) . '"' ; break ; case self :: FIELD_TYPE_OBJ : $ o -> { $ field -> identifier ( ) } = '"' . addslashes ( json_encode ( $ val ) ) . '"' ; break ; default : throw new TypeNotExistException ( ) ; } } return $ o ; }
Check & convert Fields for Insert Update
27,448
public function getPK ( $ require = true ) { foreach ( $ this -> fields as $ field ) { if ( $ field -> pk ( ) ) { return $ field ; } } if ( $ require ) { throw new NoPKException ( ) ; } }
Get primary key
27,449
public function get ( $ offset ) { if ( ! $ this -> has ( $ offset ) ) { throw OutOfRangeException :: offsetNotFound ( $ offset ) ; } return $ this -> collection [ $ offset ] ; }
Return value for given offset
27,450
public function certified ( ) { if ( ! is_null ( $ this -> submitted ) ) { return $ this -> certified ; } $ errors = array ( ) ; $ this -> values = array ( ) ; $ this -> submitted = false ; foreach ( $ this -> data as $ field => $ data ) { if ( ! is_null ( $ data [ 'value' ] ) ) { $ this -> submitted = true ; } if ( ! empty ( $ data [ 'value' ] ) ) { $ this -> values [ $ field ] = $ data [ 'value' ] ; } elseif ( strpos ( $ field , '[]' ) !== false ) { $ this -> values [ $ field ] = array ( ) ; } else { $ this -> values [ $ field ] = ( isset ( $ data [ 'rules' ] [ 'default' ] ) ) ? $ data [ 'rules' ] [ 'default' ] : '' ; } if ( ! is_null ( $ data [ 'error' ] ) ) { $ errors [ $ field ] = $ data [ 'error' ] ; } } if ( $ this -> submitted ) { $ submitted = array ( ) ; foreach ( $ this -> data as $ field => $ data ) { $ value = & $ submitted ; foreach ( $ data [ 'field' ] as $ index ) { $ value = & $ value [ $ index ] ; } $ value = $ this -> values [ $ field ] ; if ( isset ( $ data [ 'rules' ] [ 'required' ] ) && empty ( $ value ) ) { $ errors [ $ field ] = $ this -> errorMessage ( 'required' ) ; } elseif ( ! isset ( $ errors [ $ field ] ) ) { if ( isset ( $ data [ 'rules' ] [ 'equalTo' ] ) && $ value != $ this -> value ( $ data [ 'rules' ] [ 'equalTo' ] ) ) { $ errors [ $ field ] = $ this -> errorMessage ( 'equalTo' ) ; } elseif ( isset ( $ data [ 'rules' ] [ 'notEqualTo' ] ) && $ value == $ this -> value ( $ data [ 'rules' ] [ 'notEqualTo' ] ) ) { $ errors [ $ field ] = $ this -> errorMessage ( 'notEqualTo' ) ; } } } $ this -> certified = ( ! empty ( $ errors ) ) ? false : $ submitted ; } $ this -> errors = $ errors ; return $ this -> certified ; }
This method goes through all of the fields you set above determines if the form has been sent and picks out any errors .
27,451
private function errorMessage ( $ rule , $ param = null ) { if ( $ rule == 'remote' && isset ( $ this -> errors [ $ param ] ) ) { return $ this -> errorMessage ( $ param ) ; } if ( is_null ( $ param ) ) { $ param = '' ; } $ params = array_pad ( ( array ) $ param , 2 , '' ) ; return ( isset ( $ this -> errors [ $ rule ] ) ) ? str_replace ( array ( '{0}' , '{1}' ) , $ params , $ this -> errors [ $ rule ] ) : null ; }
A helper method to retrieve the associated error message when something goes wrong .
27,452
public static function subnetMatch ( $ subnet , $ ip , & $ prefix = - 1 ) { $ ip = ip2long ( $ ip ) ; if ( strpos ( $ subnet , '/' ) !== false ) { list ( $ net , $ prefix ) = explode ( '/' , $ subnet , 2 ) ; if ( ! ctype_digit ( $ prefix ) || $ prefix > 32 ) { $ prefix = - 1 ; return false ; } $ net = ip2long ( $ net ) ; $ prefix = ( int ) $ prefix ; } else { $ net = ip2long ( $ subnet ) ; $ prefix = 32 ; } if ( empty ( $ ip ) || $ net === false ) { return false ; } if ( $ prefix === 0 ) { if ( ! empty ( $ net ) ) { ExceptionHandler :: notice ( "Invalid CIDR-notation '$subnet', assuming '0.0.0.0/0'" ) ; } return true ; } if ( $ prefix < 32 ) { $ mask = 0xffffffff << ( 32 - $ prefix ) ; $ net_mask = $ net & $ mask ; $ ip_mask = $ ip & $ mask ; if ( $ net_mask !== $ net ) { ExceptionHandler :: notice ( "Invalid CIDR-notation '$subnet', assuming " . long2ip ( $ net_mask ) . "/$prefix" ) ; } return ( ( $ net_mask ^ $ ip_mask ) === 0 ) ; } else { return ( $ net === $ ip ) ; } }
Check if an IP - address falls within a given subnet .
27,453
public function set ( string $ mode ) : bool { $ auth = false ; file_exists ( $ mode ) ; switch ( $ mode ) { case Debug :: HOMOLOGATION : case Debug :: DEVELOPER : ini_set ( 'display_errors' , true ) ; error_reporting ( E_ALL ) ; $ auth = true ; break ; case Debug :: PRODUCTION : $ auth = true ; default : ini_set ( 'display_errors' , false ) ; error_reporting ( E_ERROR ) ; $ auth = $ auth ?? false ; break ; } return $ auth ; }
- Set debug mode
27,454
public static function Call ( $ sName , $ aParams = null ) { $ oThis = self :: CreateInstanceIfNotExists ( ) ; $ sName = strtolower ( str_replace ( array ( "/" , "\\" , "--" ) , "-" , $ sName ) ) ; if ( array_key_exists ( $ sName , $ oThis -> aEvents ) ) { switch ( $ oThis -> aEvents [ $ sName ] [ "type" ] ) { case "perroute" : $ sCurrentRoute = strtolower ( str_replace ( array ( "/" , "\\" , "--" ) , "-" , Storage :: Get ( "route" ) ) ) ; $ sRoute = strtolower ( $ oThis -> aEvents [ $ sName ] [ "method" ] . "_" . $ oThis -> aEvents [ $ sName ] [ "route" ] ) ; if ( $ sRoute == $ sCurrentRoute ) return call_user_func ( $ oThis -> aEvents [ $ sName ] [ "func" ] , $ aParams ) ; break ; case "default" : return call_user_func ( $ oThis -> aEvents [ $ sName ] [ "func" ] , $ aParams ) ; break ; } } else { return false ; } }
Function to call the event
27,455
public static function Set ( $ sName , $ fCallback ) { $ oThis = self :: CreateInstanceIfNotExists ( ) ; $ sName = strtolower ( str_replace ( array ( "/" , "\\" , "--" ) , "-" , $ sName ) ) ; $ oThis -> aEvents [ $ sName ] = array ( "type" => "default" , "func" => $ fCallback ) ; }
Function to set the event
27,456
public static function SetPerRoute ( $ sName , $ sRoute , $ sMethod , $ fCallback ) { $ oThis = self :: CreateInstanceIfNotExists ( ) ; $ sRoute = strtolower ( str_replace ( array ( "/" , "\\" , "--" ) , "-" , $ sRoute ) ) ; $ oThis -> aEvents [ strtolower ( $ sMethod . "_" . $ sRoute . "_" . $ sName ) ] = array ( "type" => "perroute" , "func" => $ fCallback , "route" => $ sRoute , "method" => $ sMethod ) ; }
Function to ser the evenet per route
27,457
public static function Has ( $ sName ) { $ oThis = self :: CreateInstanceIfNotExists ( ) ; $ sName = strtolower ( str_replace ( array ( "/" , "\\" , "--" ) , "-" , $ sName ) ) ; return array_key_exists ( $ sName , $ oThis -> aEvents ) ; }
Function to check existence of event
27,458
public function copyTo ( StreamInterface $ source , StreamInterface $ dest ) { $ source -> rewind ( ) ; $ dest -> write ( $ source -> getContents ( ) ) ; return $ dest ; }
Non - Psr
27,459
private function getIgnore ( & $ parameters ) { $ lastParam = end ( $ parameters ) ; $ lastParam = array_map ( 'trim' , explode ( '=' , $ lastParam ) ) ; if ( ! preg_match ( '/^[1-9][0-9]*$/' , $ lastParam [ 0 ] ) ) { return array ( null , null ) ; } $ ignoreId = $ lastParam [ 0 ] ; $ ignoreColumn = ( sizeof ( $ lastParam ) > 1 ) ? end ( $ lastParam ) : null ; array_pop ( $ parameters ) ; return array ( $ ignoreId , $ ignoreColumn ) ; }
Returns an array with value and column name for an optional ignore . Shaves of the ignore_id from the end of the array if there is one .
27,460
public function composeIndex ( View $ view ) { $ this -> composeWithTitle ( $ view ) ; $ this -> composeWithLayout ( $ view ) ; $ this -> composeWithAllRouteNames ( $ view ) ; $ this -> composeWithRequiredFields ( $ view ) ; $ this -> composeWithValidationRules ( $ view ) ; $ this -> composeWithPartialsLocation ( $ view ) ; $ this -> composeWithResourceLocation ( $ view ) ; }
Compose Index view .
27,461
public function composeShow ( View $ view ) { $ this -> composeWithTitle ( $ view ) ; $ this -> composeWithLayout ( $ view ) ; $ this -> composeWithAllRouteNames ( $ view ) ; $ this -> composeWithPartialsLocation ( $ view ) ; $ this -> composeWithResourceLocation ( $ view ) ; }
Compose Show view .
27,462
public function getFormattedQueries ( ) { $ formattedQueries = array ( ) ; foreach ( $ this -> getQueries ( ) as $ query ) { if ( ! isset ( $ query [ 'type' ] ) ) { print_r ( $ query ) ; exit ( ) ; } $ formattedQuery = array ( 'connection' => $ query [ 'connection' ] , 'database' => $ query [ 'database' ] , 'type' => $ query [ 'type' ] , 'time' => $ query [ 'time' ] , ) ; foreach ( array ( 'connection' , 'database' , 'type' , 'time' , ) as $ key ) { unset ( $ query [ $ key ] ) ; } $ formattedQuery [ 'query' ] = Yaml :: dump ( $ query , 'batchInsert' == $ formattedQuery [ 'type' ] ? 6 : 2 ) ; $ formattedQueries [ ] = $ formattedQuery ; } return $ formattedQueries ; }
Returns the queries formatted .
27,463
protected function setKept ( $ key , $ value ) { if ( $ key == 'deleted_at' ) { $ this -> kept_at = $ value ; $ this -> kept_data [ $ key ] = $ value ; } $ this -> kept_data [ $ key ] = $ value ; }
Set kept data .
27,464
public function forceDelete ( ) { $ key = $ this -> getPKvalue ( ) ; $ sql = 'delete from ' . $ this -> DBtable . ' where ' . $ this -> keyName . " = '" . $ key . "' " ; return Database :: exec ( $ sql ) ; }
force delete if the resource is kept delete .
27,465
protected function lightDelete ( ) { $ now = Time :: current ( ) ; $ key = $ this -> getPKvalue ( ) ; $ sql = 'update ' . $ this -> DBtable . " set deleted_at='" . $ now . "' where " . $ this -> keyName . " = '" . $ key . "' " ; if ( Database :: exec ( $ sql ) ) { $ this -> clean ( ) ; $ this -> deleted_at = $ now ; } }
light delete if the resource is kept delete .
27,466
public function restore ( ) { if ( $ this -> isKept ) { $ key = $ this -> getPKvalue ( ) ; $ sql = 'update ' . $ this -> DBtable . ' set deleted_at=null where ' . $ this -> keyName . " = '" . $ key . "' " ; if ( Database :: exec ( $ sql ) ) { } } }
restore if kept deleted .
27,467
public function getCallable ( $ name ) { if ( method_exists ( $ this , $ name ) ) { return call_user_func ( [ $ this , $ name ] ) ; } else { throw new InvalidArgumentException ( 'Undefined property: ' . get_class ( $ this ) . "::$name" ) ; } }
Dynamic Property .
27,468
public static function all ( ) { $ self = self :: instance ( ) ; $ sql = 'select * from ' . $ self -> DBtable ; return Database :: read ( $ sql , 1 ) ; }
Get all rows of Data Table .
27,469
public static function count ( $ where ) { $ self = self :: instance ( ) ; $ rows = new ModelArray ( ) ; $ sql = 'select count(*) as cnt from ' . $ self -> DBtable . " where $where " ; $ data = Database :: read ( $ sql , 1 ) ; return $ data [ 0 ] [ 'cnt' ] ; }
To count rows by where clause .
27,470
public function hasOne ( $ model , $ local = null , $ remote = null ) { return ( new OneToOne ( ) ) -> ini ( $ model , $ this , $ local , $ remote ) ; }
The has one relation for one to one .
27,471
public function parseMany ( $ line ) { $ results = [ ] ; $ buffer = '' ; foreach ( \ str_split ( $ line ) as $ character ) { if ( '{' == $ character ) { $ buffer = $ character ; } elseif ( '}' == $ character ) { $ results [ ] = $ this -> parse ( $ buffer . $ character ) ; } else { $ buffer .= $ character ; } } return $ results ; }
Parse multiple elements .
27,472
public function parse ( $ line ) { $ elements = [ ] ; $ line = \ str_replace ( [ '{' , '}' ] , '' , $ line ) ; $ elements = $ this -> extractElements ( $ line ) ; $ iterator = function ( $ element ) { return \ str_replace ( [ '\'' , '"' ] , '' , $ element ) ; } ; return \ array_map ( $ iterator , $ elements ) ; }
Parse a single element .
27,473
protected function extractElements ( $ line ) { $ elements = [ ] ; $ buffer = '' ; $ quote = false ; foreach ( \ str_split ( $ line ) as $ character ) { if ( \ in_array ( $ character , [ '\'' , '"' ] ) ) { $ quote = ! $ quote ; continue ; } if ( ( ':' == $ character ) and ! $ quote ) { $ elements [ ] = $ buffer ; $ buffer = '' ; continue ; } $ buffer .= $ character ; } if ( $ buffer ) { $ elements [ ] = $ buffer ; } return $ elements ; }
Extract an array of elements from the string .
27,474
public function getResponse ( $ printResponse = true ) { $ this -> setStatusInfo ( ) ; if ( $ printResponse ) { header ( 'Content-Type: application/json' ) ; echo $ this -> ResponseData ; } else { return $ this -> ResponseData ; } return null ; }
Print or return ResponseData
27,475
private function setStatusInfo ( ) { $ statusInfo [ 'status' ] = [ 'data' => date ( 'Y-m-d H:i:s' ) ] ; $ origData = json_decode ( $ this -> ResponseData , true ) ; if ( ! is_null ( $ origData ) ) { $ this -> ResponseData = json_encode ( array_merge ( $ origData , $ statusInfo ) ) ; } else { $ this -> ResponseData = json_encode ( $ statusInfo ) ; } return $ this ; }
Append status info to a response data
27,476
public function run ( ) { $ this -> logger -> notice ( 'Starting to run an election' ) ; $ this -> logger -> notice ( sprintf ( 'There are %d candidates, %d ballots and to be %d winners' , $ this -> election -> getCandidateCount ( ) , $ this -> validBallots , $ this -> election -> getWinnersCount ( ) ) ) ; $ this -> rejectInvalidBallots ( ) ; $ this -> setQuota ( ) ; $ this -> firstStep ( ) ; $ candidates = $ this -> election -> getActiveCandidates ( ) ; $ this -> processReallocationRounds ( $ candidates ) ; $ this -> reallocateRemainingVotes ( $ candidates ) ; $ this -> logger -> notice ( 'Election complete' ) ; return $ this -> election -> getElectedCandidates ( ) ; }
Run the election .
27,477
protected function firstStep ( ) { $ this -> logger -> info ( 'Beginning the first step' ) ; foreach ( $ this -> ballots as $ i => $ ballot ) { $ this -> allocateVotes ( $ ballot ) ; } $ this -> logger -> notice ( 'Step 1 complete' , [ 'candidatesStatus' => $ this -> election -> getCandidatesStatus ( ) ] ) ; $ this -> steps [ 1 ] = $ this -> election -> getCandidatesStatus ( ) ; return ; }
Perform the initial vote allocation . p . 46 .
27,478
protected function checkCandidates ( array $ candidates ) : bool { $ elected = false ; $ candidatesToElect = [ ] ; $ this -> logger -> info ( 'Checking if candidates have passed quota' ) ; if ( empty ( $ candidates ) ) { throw new LogicException ( 'There are no more candidates left' ) ; } foreach ( $ candidates as $ i => $ candidate ) { if ( $ candidate -> getState ( ) !== Candidate :: RUNNING ) { throw new LogicException ( 'Candidate is not marked as not running but has not been excluded' ) ; } $ votes = $ candidate -> getVotes ( ) ; $ this -> logger -> debug ( "Checking candidate ($candidate) with $votes" , [ 'candidate' => $ candidate ] ) ; if ( $ votes >= $ this -> quota ) { $ candidatesToElect [ ] = $ candidate ; $ elected = true ; } } $ this -> electCandidates ( $ candidatesToElect ) ; $ this -> logger -> info ( ( 'Candidate checking complete. Elected: ' . count ( $ candidatesToElect ) ) ) ; return $ elected ; }
Check if any candidates have reached the quota and can be elected .
27,479
protected function electCandidates ( array $ candidates ) { if ( $ this -> candidatesToElect < count ( $ candidates ) ) { throw new RuntimeException ( 'Cannot elect candidate as not enough seats to fill' ) ; } foreach ( $ candidates as $ i => $ candidate ) { $ this -> electCandidate ( $ candidate ) ; } return ; }
Elect an array of candidates .
27,480
protected function allocateVotes ( Ballot $ ballot , float $ multiplier = 1.0 , float $ divisor = 1.0 ) : Ballot { $ currentWeight = $ ballot -> getWeight ( ) ; $ weight = $ ballot -> setWeight ( ( $ currentWeight * $ multiplier ) / $ divisor ) ; $ candidate = $ ballot -> getNextChoice ( ) ; $ this -> logger -> debug ( "Allocating vote of weight $weight to $candidate. Previous weight: $currentWeight" , array ( 'ballot' => $ ballot , ) ) ; if ( $ candidate !== null ) { $ this -> election -> getCandidate ( $ candidate ) -> addVotes ( $ weight ) ; $ ballot -> incrementLevelUsed ( ) ; $ this -> logger -> debug ( 'Vote added to candidate' ) ; if ( ! in_array ( $ candidate , $ this -> election -> getActiveCandidateIds ( ) ) ) { $ this -> allocateVotes ( $ ballot ) ; } } return $ ballot ; }
Allocate the next votes from a Ballot . p . 49 .
27,481
protected function transferSurplusVotes ( float $ surplus , Candidate $ candidate ) { $ totalVotes = $ candidate -> getVotes ( ) ; $ candidateId = $ candidate -> getId ( ) ; $ this -> logger -> info ( 'Transfering surplus votes' ) ; foreach ( $ this -> ballots as $ i => $ ballot ) { if ( $ ballot -> getLastChoice ( ) == $ candidateId ) { $ this -> allocateVotes ( $ ballot , $ surplus , $ totalVotes ) ; } } return ; }
Transfer the votes from one candidate to other candidates .
27,482
protected function electCandidate ( Candidate $ candidate ) { $ this -> logger -> notice ( "Electing a candidate: $candidate" ) ; $ candidate -> setState ( Candidate :: ELECTED ) ; ++ $ this -> electedCandidates ; -- $ this -> candidatesToElect ; if ( $ this -> electedCandidates < $ this -> election -> getWinnersCount ( ) ) { $ surplus = $ candidate -> getVotes ( ) - $ this -> quota ; if ( $ surplus > 0 ) { $ this -> transferSurplusVotes ( $ surplus , $ candidate ) ; } else { $ this -> logger -> notice ( "No surplus votes from $candidate to reallocate" ) ; } } return ; }
Elect a candidate after they ve passed the threshold .
27,483
protected function eliminateCandidates ( array $ candidates ) : int { $ minimumCandidates = $ this -> getLowestCandidates ( $ candidates ) ; $ count = count ( $ minimumCandidates ) ; $ minimumCandidate = $ minimumCandidates [ ( array_rand ( $ minimumCandidates ) ) ] ; $ this -> logger -> notice ( sprintf ( 'There were %d joint lowest candidates, %d was randomly selected to be eliminated' , $ count , $ minimumCandidate -> getId ( ) ) ) ; $ this -> transferEliminatedVotes ( $ minimumCandidate ) ; $ minimumCandidate -> setState ( Candidate :: DEFEATED ) ; return count ( $ minimumCandidates ) ; }
Eliminate the candidate with the lowest number of votes and reallocated their votes . p . 51 .
27,484
public function checkBallotValidity ( Ballot $ ballot ) : bool { $ ranking = $ ballot -> getRanking ( ) ; if ( ! $ this -> checkCandidateCountValidity ( $ ranking ) || ! $ this -> checkBallotVoteDuplicationValidity ( $ ranking ) || ! $ this -> checkAllBallotCandidatesValid ( $ ranking ) ) { return false ; } $ this -> logger -> debug ( 'Ballot is valid' ) ; return true ; }
Check if ballot is valid .
27,485
protected function reallocateRemainingVotes ( array & $ candidates ) { if ( ! empty ( $ candidates ) ) { $ this -> logger -> info ( 'All votes re-allocated. Electing all remaining candidates' ) ; if ( $ this -> candidatesToElect < count ( $ candidates ) ) { throw new LogicException ( 'Cannot elect candidate as no more seats to fill' ) ; } $ this -> electCandidates ( $ candidates ) ; } return ; }
Reallocate any remaining votes p . 53 .
27,486
public function setQuota ( ) : int { $ this -> quota = ( int ) floor ( ( $ this -> validBallots / ( $ this -> election -> getWinnersCount ( ) + 1 ) ) + 1 ) ; $ this -> logger -> info ( sprintf ( 'Quota set at %d based on %d winners and %d valid ballots' , $ this -> quota , $ this -> election -> getWinnersCount ( ) , $ this -> validBallots ) ) ; return $ this -> quota ; }
Get the quota to win . p . 47 .
27,487
protected function checkCandidateCountValidity ( array $ ranking ) : bool { if ( count ( $ ranking ) > $ this -> election -> getCandidateCount ( ) ) { $ this -> logger -> debug ( 'Invalid ballot - number of candidates' ) ; return false ; } return true ; }
Check that a ballot s ranking doesn t have more elements than we have candidates
27,488
protected function checkAllBallotCandidatesValid ( array $ ranking ) : bool { $ candidateIds = $ this -> election -> getCandidateIds ( ) ; foreach ( $ ranking as $ candidate ) { if ( ! in_array ( $ candidate , $ candidateIds ) ) { $ this -> logger -> debug ( 'Invalid ballot - invalid candidate' ) ; return false ; } } return true ; }
Check that a ballot only contains candidate id numbers that are integers and correspond to valid candidates .
27,489
public static function time ( ) { if ( ! is_null ( self :: $ _now ) ) { if ( is_int ( self :: $ _now ) ) { return self :: $ _now ; } return strtotime ( self :: $ _now ) ; } return time ( ) ; }
Get the current time .
27,490
public static function strtotime ( $ str , $ time = null ) { if ( is_null ( $ time ) ) { $ time = self :: time ( ) ; } return strtotime ( $ str , $ time ) ; }
Strtotime with fallback on overriden application time .
27,491
public static function inPast ( $ date , $ time = null ) { if ( is_null ( $ time ) ) { $ time = self :: time ( ) ; } if ( ! is_int ( $ date ) ) { $ date = self :: strtotime ( $ date ) ; } return $ time > $ date ; }
Is the date in the past?
27,492
public static function inFuture ( $ date , $ time = null ) { if ( is_null ( $ time ) ) { $ time = self :: time ( ) ; } if ( ! is_int ( $ date ) ) { $ date = self :: strtotime ( $ date ) ; } return $ time < $ date ; }
Is the date in the future?
27,493
public static function isPresent ( $ date , $ time = null ) { if ( is_null ( $ time ) ) { $ time = self :: time ( ) ; } if ( ! is_int ( $ date ) ) { $ date = self :: strtotime ( $ date ) ; } return $ time === $ date ; }
Is it now .
27,494
public static function niceTimeDiff ( $ d1 , $ d2 , $ limitPeriods = 2 ) { if ( ! is_int ( $ d1 ) ) { $ d1 = self :: strtotime ( $ d1 ) ; } if ( ! is_int ( $ d2 ) ) { $ d2 = self :: strtotime ( $ d2 ) ; } if ( empty ( $ d1 ) or empty ( $ d2 ) ) { return false ; } $ max = max ( $ d1 , $ d2 ) ; $ min = min ( $ d1 , $ d2 ) ; $ diff = $ max - $ min ; return self :: niceDuration ( $ diff , $ limitPeriods ) ; }
Nice time difference .
27,495
public static function niceDuration ( $ seconds , $ limitPeriods = 7 , $ zeros = false ) { $ periods = [ 'years' => 31556926 , 'months' => 2629743 , 'days' => 86400 , 'hours' => 3600 , 'minutes' => 60 , 'seconds' => 1 , ] ; $ seconds = ( float ) $ seconds ; $ segments = [ ] ; foreach ( $ periods as $ period => $ value ) { if ( $ limitPeriods >= 1 ) { $ count = floor ( $ seconds / $ value ) ; $ seconds = $ seconds % $ value ; } else { $ count = round ( $ seconds / $ value ) ; $ seconds = 0 ; } if ( ( $ count == 0 && ! $ zeros ) or $ limitPeriods < 1 ) { continue ; } $ segments [ strtolower ( $ period ) ] = $ count ; $ limitPeriods -- ; } $ string = [ ] ; foreach ( $ segments as $ key => $ value ) { $ segment_name = substr ( $ key , 0 , - 1 ) ; $ segment = $ value . ' ' . $ segment_name ; if ( $ value != 1 ) { $ segment .= 's' ; } $ string [ ] = $ segment ; } return implode ( ', ' , $ string ) ; }
Get the human string of a duration .
27,496
protected function loadConfig ( $ serviceName ) { if ( ! empty ( $ this -> config [ $ serviceName ] ) ) { return $ this -> config [ $ serviceName ] ; } else { throw new OAuthServiceException ( 'No configuration for ' . $ serviceName . ' service' ) ; } }
Returns config for specific service
27,497
public function trigger ( $ event , $ data = null ) { $ event = strtolower ( trim ( $ event ) ) ; if ( ! isset ( $ this -> _events [ $ event ] ) ) return $ data ; foreach ( $ this -> _events [ $ event ] as $ callback ) { $ result = call_user_func ( $ callback , $ event , $ data ) ; if ( $ result !== null ) $ data = $ result ; } return $ data ; }
Triggers an event .
27,498
public function startWeb ( ) { $ this -> startBase ( ) ; if ( Configuration :: get ( 'app.env' ) === 'development' && Configuration :: get ( 'app.profiler' , false ) ) { DebugBarHelper :: getInstance ( ) ; } $ this -> router -> run ( ) ; }
Start from web will make sure we start the logger some kernel parts and the router .
27,499
public function setService ( $ name , $ service ) { $ this -> validate ( $ service ) ; parent :: setService ( $ name , $ service ) ; }
Override setService for additional plugin validation .