idx
int64
0
60.3k
question
stringlengths
92
4.62k
target
stringlengths
7
635
1,000
public function fetchUrl ( $ url , $ httpClient = null ) { if ( $ httpClient == null ) { $ httpClient = new Maestrano_Net_HttpClient ( ) ; } return $ httpClient -> get ( $ url ) ; }
Fetch url and return content . Wrapper function .
1,001
public function performRemoteCheck ( $ httpClient = null ) { if ( empty ( $ this -> sessionToken ) ) { return false ; } $ json = $ this -> fetchUrl ( $ this -> getSessionCheckUrl ( ) , $ httpClient ) ; if ( $ json ) { $ response = json_decode ( $ json , true ) ; if ( $ response [ 'valid' ] == "true" && $ response [ 'recheck' ] != null ) { $ this -> recheck = new DateTime ( $ response [ 'recheck' ] ) ; return true ; } } return false ; }
Perform remote session check on Maestrano
1,002
public function isValid ( $ ifSession = false , $ httpClient = null ) { if ( $ ifSession ) { return true ; } if ( ! $ this -> ssoTokenExists ( ) || $ this -> isRemoteCheckRequired ( ) ) { if ( $ this -> performRemoteCheck ( $ httpClient ) ) { $ this -> save ( ) ; return true ; } else { return false ; } } else { return true ; } }
Perform check to see if session is valid Check is only performed if current time is after the recheck timestamp If a remote check is performed then the mno_session_recheck timestamp is updated in session .
1,003
private function getId ( Url $ url ) { if ( $ url -> hasQueryParameter ( 'story_fbid' ) ) { $ this -> isEmbeddable = true ; return $ url -> getQueryParameter ( 'story_fbid' ) ; } if ( $ url -> hasQueryParameter ( 'fbid' ) ) { return $ url -> getQueryParameter ( 'fbid' ) ; } if ( $ url -> hasQueryParameter ( 'id' ) ) { return $ url -> getQueryParameter ( 'id' ) ; } if ( $ url -> getDirectoryPosition ( 0 ) === 'events' ) { $ this -> isEmbeddable = true ; return $ url -> getDirectoryPosition ( 1 ) ; } if ( $ url -> getDirectoryPosition ( 0 ) === 'pages' ) { return $ url -> getDirectoryPosition ( 2 ) ; } if ( $ url -> getDirectoryPosition ( 1 ) === 'posts' ) { $ this -> isEmbeddable = true ; return $ url -> getDirectoryPosition ( 2 ) ; } if ( $ url -> getDirectoryPosition ( 2 ) === 'posts' ) { $ this -> isEmbeddable = true ; return $ url -> getDirectoryPosition ( 3 ) ; } return $ url -> getDirectoryPosition ( 0 ) ; }
Returns the id found in a facebook url
1,004
public static function createFromFormat ( $ format , $ time , $ tz = null ) { if ( $ tz !== null ) { $ dt = parent :: createFromFormat ( $ format , $ time , static :: safeCreateDateTimeZone ( $ tz ) ) ; } else { $ dt = parent :: createFromFormat ( $ format , $ time ) ; } if ( $ dt instanceof DateTimeInterface ) { return static :: instance ( $ dt ) ; } $ errors = static :: getLastErrors ( ) ; throw new InvalidArgumentException ( implode ( PHP_EOL , $ errors [ 'errors' ] ) ) ; }
Create a Date instance from a specific format .
1,005
public function setDateTime ( $ year , $ month , $ day , $ hour , $ minute = 0 , $ second = 0 ) { return $ this -> setDate ( $ year , $ month , $ day ) -> setTime ( $ hour , $ minute , $ second ) ; }
Set the date and time all together .
1,006
public function setTimeFromTimeString ( $ time ) { $ time = explode ( ':' , $ time ) ; $ hour = ( int ) $ time [ 0 ] ; $ minute = isset ( $ time [ 1 ] ) ? ( int ) $ time [ 1 ] : 0 ; $ second = isset ( $ time [ 2 ] ) ? ( int ) $ time [ 2 ] : 0 ; return $ this -> setTime ( $ hour , $ minute , $ second ) ; }
Set the time by time string .
1,007
public function isBetween ( Date $ dt1 , Date $ dt2 , $ equal = true ) { if ( $ dt1 -> isAfter ( $ dt2 ) ) { $ temp = $ dt1 ; $ dt1 = $ dt2 ; $ dt2 = $ temp ; } if ( $ equal ) { return $ this -> isAfterOrEquals ( $ dt1 ) && $ this -> isBeforeOrEquals ( $ dt2 ) ; } return $ this -> isAfter ( $ dt1 ) && $ this -> isBefore ( $ dt2 ) ; }
Determines if the instance is between two others .
1,008
public function diffInWeeks ( Date $ dt = null , $ abs = true ) { return ( int ) ( $ this -> diffInDays ( $ dt , $ abs ) / static :: DAYS_PER_WEEK ) ; }
Get the difference in weeks .
1,009
public function diffInDaysFiltered ( Closure $ callback , Date $ dt = null , $ abs = true ) { return $ this -> diffFiltered ( Interval :: day ( ) , $ callback , $ dt , $ abs ) ; }
Get the difference in days using a filter closure .
1,010
public function diffInHoursFiltered ( Closure $ callback , Date $ dt = null , $ abs = true ) { return $ this -> diffFiltered ( Interval :: hour ( ) , $ callback , $ dt , $ abs ) ; }
Get the difference in hours using a filter closure .
1,011
public function diffFiltered ( Interval $ ci , Closure $ callback , Date $ dt = null , $ abs = true ) { $ start = $ this ; $ end = $ dt ? : static :: now ( $ this -> getTimezone ( ) ) ; $ inverse = false ; if ( $ end < $ start ) { $ start = $ end ; $ end = $ this ; $ inverse = true ; } $ period = new DatePeriod ( $ start , $ ci , $ end ) ; $ vals = array_filter ( iterator_to_array ( $ period ) , function ( DateTimeInterface $ date ) use ( $ callback ) { return call_user_func ( $ callback , Date :: instance ( $ date ) ) ; } ) ; $ diff = count ( $ vals ) ; return $ inverse && ! $ abs ? - $ diff : $ diff ; }
Get the difference by the given interval using a filter closure .
1,012
public function diffInWeekendDays ( Date $ dt = null , $ abs = true ) { return $ this -> diffInDaysFiltered ( function ( Date $ date ) { return $ date -> isWeekend ( ) ; } , $ dt , $ abs ) ; }
Get the difference in weekend days using a filter .
1,013
public function createRta ( RtaServices $ rtaSer , $ keyElement = null , array $ fields = null ) { if ( $ rtaSer -> auth === false ) { $ this -> code = 401 ; } else if ( ! $ rtaSer -> isOk ( ) ) { $ this -> code = 400 ; } $ this -> body = $ rtaSer -> toArray ( ) ; if ( $ keyElement ) { if ( $ rtaSer -> getParam ( $ keyElement ) != NULL ) { $ jsonHelper = new JsonHelper ( ) ; $ this -> body [ $ keyElement ] = $ jsonHelper -> object_to_array ( $ rtaSer -> getParam ( $ keyElement ) , $ fields ) ; } } }
Crea una respuesta API en base a un elemento y sus campos
1,014
public function findAllByUser ( $ userId ) { $ select = $ this -> select ( ) -> join ( 'user_right_x_user' , new Sql \ Expression ( '?.? = ?.? AND ?.? = ?' , array ( self :: $ tableName , 'id' , 'user_right_x_user' , 'rightId' , 'user_right_x_user' , 'userId' , $ userId , ) , array ( Sql \ Expression :: TYPE_IDENTIFIER , Sql \ Expression :: TYPE_IDENTIFIER , Sql \ Expression :: TYPE_IDENTIFIER , Sql \ Expression :: TYPE_IDENTIFIER , Sql \ Expression :: TYPE_IDENTIFIER , Sql \ Expression :: TYPE_IDENTIFIER , Sql \ Expression :: TYPE_VALUE , ) ) , array ( 'granted' => 'userId' ) , Sql \ Select :: JOIN_LEFT ) -> order ( array ( 'group' => 'ASC' , 'resource' => 'ASC' , 'privilege' => 'ASC' , ) ) ; $ return = array ( ) ; $ result = $ this -> sql ( ) -> prepareStatementForSqlObject ( $ select ) -> execute ( ) ; foreach ( $ result as $ row ) { $ return [ ] = $ this -> selected ( $ row ) ; } return $ return ; }
Get all rights and granted flags to a user
1,015
protected function getURI ( ) : string { if ( empty ( $ this -> baseUrl ) || empty ( $ this -> uri ) ) { throw new Exception ( 'Url or end point can not be null' ) ; } return $ this -> baseUrl . $ this -> uri ; }
Get URI concatenating base url api with resource end point
1,016
protected function setParameters ( array $ parameters ) { if ( empty ( $ parameters ) ) { throw new InvalidArgumentException ( 'Parameters can not be null' ) ; } $ this -> uri = null ; foreach ( $ parameters as $ key => $ param ) { if ( preg_match ( "/{$key}/i" , $ this -> endPoint ) ) { if ( is_null ( $ this -> uri ) ) { $ this -> uri = $ this -> endPoint ; } $ this -> uri = str_replace ( $ key , $ param , $ this -> uri ) ; } } if ( empty ( $ this -> uri ) ) { throw new Exception ( 'Parameters definition not matches with request end point' ) ; } }
Set url parameters
1,017
public function content ( ) : Context { if ( ! $ this -> content ) { $ this -> setContent ( new Context ( new Helper ( ) , new Extensions ( ) ) ) ; } return $ this -> content ; }
Content for Sandbox
1,018
public function authenticate ( ) { $ hmac = $ this -> getRest ( ) -> getServer ( ) -> getHmac ( ) ; $ data = array_merge ( $ this -> getRequestHeaders ( true ) , $ this -> getBodyData ( ) ) ; $ auth = $ hmac -> setData ( $ data ) -> setRoute ( $ this -> getPlatform ( ) -> getPost ( 'api_method' ) ) -> setMethod ( $ _SERVER [ 'REQUEST_METHOD' ] ) -> auth ( $ this -> settings [ 'api_key' ] , $ this -> settings [ 'api_secret' ] ) ; if ( ! $ auth ) { return false ; } return true ; }
Authenticates the request
1,019
public function getBodyData ( ) { if ( is_null ( $ this -> body_data ) ) { $ data = json_decode ( file_get_contents ( "php://input" ) , true ) ; if ( ! $ data ) { $ data = array ( ) ; } $ this -> body_data = $ data ; } return $ this -> body_data ; }
Returns the input data as an array
1,020
public function getRequestHeaders ( $ auth = true ) { $ headers = \ getallheaders ( ) ; if ( $ auth ) { $ hmac = $ this -> getRest ( ) -> getServer ( ) -> getHmac ( ) ; $ return = array ( $ hmac -> getPrefix ( ) . 'timestamp' => ( isset ( $ headers [ $ hmac -> getPrefix ( ) . 'timestamp' ] ) ? $ headers [ $ hmac -> getPrefix ( ) . 'timestamp' ] : '' ) , $ hmac -> getPrefix ( ) . 'signature' => ( isset ( $ headers [ $ hmac -> getPrefix ( ) . 'signature' ] ) ? $ headers [ $ hmac -> getPrefix ( ) . 'signature' ] : '' ) , $ hmac -> getPrefix ( ) . 'key' => ( isset ( $ headers [ $ hmac -> getPrefix ( ) . 'key' ] ) ? $ headers [ $ hmac -> getPrefix ( ) . 'key' ] : '' ) , $ hmac -> getPrefix ( ) . 'version' => ( isset ( $ headers [ $ hmac -> getPrefix ( ) . 'version' ] ) ? $ headers [ $ hmac -> getPrefix ( ) . 'version' ] : '' ) , ) ; $ headers = $ return ; } return $ headers ; }
Returns an associative array of the request headers
1,021
public function setAssets ( $ assets ) : self { if ( is_array ( $ assets ) ) { $ assets = new \ ArrayIterator ( $ assets ) ; } if ( ! $ assets instanceof \ Traversable ) { throw new \ InvalidArgumentException ( 'Assets must be an iterable array or object.' ) ; } $ this -> assets = $ assets ; return $ this ; }
Define the assets that need to be copied when snapshotting components .
1,022
protected function filterable ( $ value ) { if ( count ( $ value ) !== $ this -> expectedInputs ) { throw new Exception \ RuntimeException ( sprintf ( 'There are not enough values in the array to filter this date (Required: %d, Received: %d)' , $ this -> expectedInputs , count ( $ value ) ) ) ; } }
Ensures there are enough inputs in the array to properly format the date .
1,023
protected function getUncompressed ( $ compressed ) { $ decompressed = $ this -> _gzdecode ( $ compressed ) ; if ( $ decompressed === false ) { throw new ehough_shortstop_api_exception_RuntimeException ( 'Could not decompress data with simulated gzdecode()' ) ; } return $ decompressed ; }
Get the uncompressed version of the given data .
1,024
public function init ( ) { if ( $ errors = Session :: has ( self :: SESSION_ERROR_NAME ) ) { $ this -> errors = $ errors ; } $ this -> clean ( ) ; return ; }
start the error bag
1,025
protected function validatePayloadType ( $ payloadTypeKey , $ endpointTypeKey ) { $ metadata = $ this -> getStore ( ) -> getMetadataForType ( $ endpointTypeKey ) ; if ( false === $ metadata -> isPolymorphic ( ) && $ payloadTypeKey === $ endpointTypeKey ) { return ; } if ( true === $ metadata -> isPolymorphic ( ) && in_array ( $ payloadTypeKey , $ metadata -> ownedTypes ) ) { return ; } $ expected = ( true === $ metadata -> isPolymorphic ( ) ) ? implode ( ', ' , $ metadata -> ownedTypes ) : $ endpointTypeKey ; throw AdapterException :: badRequest ( sprintf ( 'The payload "type" member does not match the API endpoint. Expected one of "%s" but received "%s"' , $ expected , $ payloadTypeKey ) ) ; }
Validates that the payload type key matches the endpoint type key . Also handles proper type keys for polymorphic endpoints .
1,026
private function handleGetRequest ( Rest \ RestRequest $ request ) { if ( true === $ request -> hasIdentifier ( ) ) { if ( false === $ request -> isRelationship ( ) && false === $ request -> hasFilters ( ) ) { return $ this -> findRecord ( $ request -> getEntityType ( ) , $ request -> getIdentifier ( ) ) ; } if ( true === $ request -> isRelationshipRetrieve ( ) ) { return $ this -> findRelationship ( $ request -> getEntityType ( ) , $ request -> getIdentifier ( ) , $ request -> getRelationshipFieldKey ( ) ) ; } throw AdapterException :: badRequest ( 'No GET handler found.' ) ; } else { if ( true === $ request -> isAutocomplete ( ) ) { return $ this -> autocomplete ( $ request -> getEntityType ( ) , $ request -> getAutocompleteKey ( ) , $ request -> getAutocompleteValue ( ) ) ; } if ( true === $ request -> isQuery ( ) ) { return $ this -> findQuery ( $ request -> getEntityType ( ) , $ request -> getQueryCriteria ( ) , $ request -> getFieldset ( ) , $ request -> getSorting ( ) , $ request -> getPagination ( ) , $ request -> getInclusions ( ) ) ; } return $ this -> findAll ( $ request -> getEntityType ( ) , [ ] , $ request -> getFieldset ( ) , $ request -> getSorting ( ) , $ request -> getPagination ( ) , $ request -> getInclusions ( ) ) ; } throw AdapterException :: badRequest ( 'No GET handler found.' ) ; }
Handles a GET request .
1,027
public function render ( Configuration $ configuration ) { $ output = '' ; foreach ( $ configuration -> getSections ( ) as $ name => $ section ) { $ output .= $ this -> renderSection ( $ section ) ; } return $ output ; }
Renders a configuration
1,028
public function renderSection ( Section $ section ) { $ output = sprintf ( "[%s]\n" , $ section -> getName ( ) ) ; foreach ( $ section -> getProperties ( ) as $ key => $ value ) { $ value = $ this -> normalizeValue ( $ value ) ; $ output .= sprintf ( "%s = %s\n" , $ key , $ value ) ; } $ output .= "\n" ; return $ output ; }
Renders a section
1,029
protected function normalizeValue ( $ value ) { if ( is_array ( $ value ) ) { return implode ( ',' , $ value ) ; } elseif ( is_bool ( $ value ) ) { return $ value ? 'true' : 'false' ; } return $ value ; }
Normalize value to valid INI format
1,030
public function removeResource ( AbstractResourceFile $ resource ) { if ( parent :: offsetExists ( $ resource -> getMemberId ( ) ) ) { parent :: offsetUnset ( $ resource -> getMemberId ( ) ) ; } }
Remove the target resource object from the current collection .
1,031
public static function toJalali ( $ g_y , $ g_m , $ g_d ) { $ g_days_in_month = array ( 31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 ) ; $ j_days_in_month = array ( 31 , 31 , 31 , 31 , 31 , 31 , 30 , 30 , 30 , 30 , 30 , 29 ) ; $ gy = $ g_y - 1600 ; $ gm = $ g_m - 1 ; $ gd = $ g_d - 1 ; $ g_day_no = 365 * $ gy + self :: div ( $ gy + 3 , 4 ) - self :: div ( $ gy + 99 , 100 ) + self :: div ( $ gy + 399 , 400 ) ; for ( $ i = 0 ; $ i < $ gm ; ++ $ i ) $ g_day_no += $ g_days_in_month [ $ i ] ; if ( $ gm > 1 && ( ( $ gy % 4 == 0 && $ gy % 100 != 0 ) || ( $ gy % 400 == 0 ) ) ) $ g_day_no ++ ; $ g_day_no += $ gd ; $ j_day_no = $ g_day_no - 79 ; $ j_np = self :: div ( $ j_day_no , 12053 ) ; $ j_day_no %= 12053 ; $ jy = 979 + 33 * $ j_np + 4 * self :: div ( $ j_day_no , 1461 ) ; $ j_day_no %= 1461 ; if ( $ j_day_no >= 366 ) { $ jy += self :: div ( $ j_day_no - 1 , 365 ) ; $ j_day_no = ( $ j_day_no - 1 ) % 365 ; } for ( $ i = 0 ; $ i < 11 && $ j_day_no >= $ j_days_in_month [ $ i ] ; ++ $ i ) $ j_day_no -= $ j_days_in_month [ $ i ] ; $ jm = $ i + 1 ; $ jd = $ j_day_no + 1 ; return array ( $ jy , $ jm , $ jd ) ; }
Gregorian to Jalali Conversion
1,032
protected function initializeApplicableChecker ( ChainApplicableChecker $ applicableChecker ) { if ( ! empty ( $ this -> additionalApplicableCheckers ) ) { $ checkers = $ this -> additionalApplicableCheckers ; \ krsort ( $ checkers ) ; $ checkers = \ array_merge ( ... $ checkers ) ; foreach ( $ checkers as $ checker ) { $ applicableChecker -> addChecker ( $ checker ) ; } } foreach ( $ applicableChecker as $ checker ) { if ( $ this -> debug && $ checker instanceof MatchApplicableChecker ) { $ checker -> addIgnoredAttribute ( 'priority' ) ; } if ( $ checker instanceof ProcessorBagAwareApplicableCheckerInterface ) { $ checker -> setProcessorBag ( $ this ) ; } } }
Initializes the given applicable checker
1,033
public static function factory ( $ config = array ( ) ) { $ default = array ( 'token_format' => 'Bearer' , 'Accept' => 'application/json' , 'environment' => 'prod' , 'service-description-name' => Client :: NAME_SERVICE_API , 'ssl' => false ) ; $ required = array ( 'base_url' , 'token_format' , 'access_token' , 'Accept' , 'environment' , 'ssl' ) ; $ config = Collection :: fromConfig ( $ config , $ default , $ required ) ; if ( $ config [ 'environment' ] == 'dev' && $ config [ 'ssl' ] == false ) { $ config [ 'ssl.certificate_authority' ] = 'system' ; $ config [ 'curl.options' ] = array ( CURLOPT_SSL_VERIFYHOST => false , CURLOPT_SSL_VERIFYPEER => false ) ; } $ client = new self ( $ config -> get ( 'base_url' ) , $ config ) ; $ client -> addSubscriber ( new OAuth2Plugin ( $ config -> toArray ( ) ) ) ; $ client -> addSubscriber ( new AcceptHeaderPluging ( $ config -> toArray ( ) ) ) ; return $ client ; }
Build new class ChateaGratisClient this provides commands to run at ApiChateaServer
1,034
public function updateAccessToken ( $ access_token ) { $ this -> getEventDispatcher ( ) -> addListener ( 'request.before_send' , function ( Event $ event ) use ( $ access_token ) { $ request = $ event [ 'request' ] ; $ request -> setHeader ( 'Authorization ' , 'Bearer ' . $ access_token ) ; } ) ; }
Update the access token on header .
1,035
public static function loadExtensionsFiles ( $ files , array $ config = [ ] ) : array { $ callbacks = [ ] ; $ files = ! is_array ( $ files ) ? static :: findExtensionsFiles ( $ files ) : $ files ; foreach ( $ files as $ file ) { $ item = require $ file ; if ( $ item instanceof \ Closure ) { $ callbacks [ ] = $ item ; } if ( is_array ( $ item ) ) { $ config = array_replace_recursive ( $ config , $ item ) ; } } foreach ( $ callbacks as $ callback ) { $ config = $ callback ( $ config ) ; } return $ config ; }
Load configurations files .
1,036
public function get ( $ key ) { $ cache_file = new File ( $ key . self :: CACHE_FILE_EXT , $ this -> config -> getCacheRoot ( ) ) ; if ( ! $ cache_file -> exists ( ) ) { return false ; } if ( ! $ cache_file -> canRead ( ) ) { throw ( new CacheFileNotReadableException ( $ cache_file ) ) ; } $ lines = $ cache_file -> getContentsAsArray ( ) ; static $ keywords = [ 'expires' , 'type' , 'class' , 'data' ] ; $ cache_info = [ ] ; foreach ( $ keywords as $ keyword ) { $ line = array_shift ( $ lines ) ; $ kwlen = strlen ( $ keyword ) ; if ( ! $ line ) { throw ( new CacheFileFormatException ( $ cache_file ) ) ; } if ( strlen ( $ line ) < $ kwlen + 1 || strpos ( $ line , $ keyword . ':' ) !== 0 ) { throw ( new CacheFileFormatException ( $ cache_file ) ) ; } $ cache_info [ $ keyword ] = substr ( $ line , $ kwlen + 1 ) ; } $ expires = $ cache_info [ 'expires' ] ? intval ( $ cache_info [ 'expires' ] ) : null ; if ( $ expires === null ) { throw ( new CacheMetaDataException ( 'expires' , $ expires ) ) ; } $ now = time ( ) ; if ( $ expires > 0 && $ expires < $ now ) { return null ; } $ data = $ cache_info [ 'data' ] ?? null ; if ( $ data === null ) { throw ( new CacheMetaDataException ( 'data' , $ data ) ) ; } $ data = unserialize ( base64_decode ( $ data ) ) ; $ type = $ cache_info [ 'type' ] ?? null ; if ( $ type === null ) { throw ( new CacheMetaDataException ( 'type' , $ type ) ) ; } if ( $ type !== gettype ( $ data ) ) { return null ; } if ( $ type === 'object' ) { $ class = $ cache_info [ 'class' ] ?? null ; if ( $ class === null ) { throw ( new CacheMetaDataException ( 'class' , $ class ) ) ; } if ( ! ( $ data instanceof $ class ) ) { return null ; } } return $ data ; }
Get non - typed data which is associated with a string key
1,037
public function set ( $ key , $ value ) { $ cache_file = new File ( $ key . self :: CACHE_FILE_EXT , $ this -> config -> getCacheRoot ( ) ) ; $ expire = $ this -> config -> getExpire ( ) ; $ expires = $ expire > 0 ? time ( ) + $ this -> config -> getExpire ( ) : 0 ; $ data = base64_encode ( serialize ( $ value ) ) ; $ content [ ] = 'expires:' . $ expires ; $ content [ ] = 'type:' . gettype ( $ value ) ; $ content [ ] = 'class:' . ( is_object ( $ value ) ? get_class ( $ value ) : '' ) ; $ content [ ] = 'data:' . $ data ; $ cache_file -> putContents ( implode ( "\n" , $ content ) ) ; }
Save a value to cache
1,038
public function delete ( $ key ) { $ cache_file = new File ( $ key . self :: CACHE_FILE_EXT , $ this -> config -> getCacheRoot ( ) ) ; if ( ! $ cache_file -> exists ( ) ) { throw ( new CacheFileNotFoundException ( $ cache_file ) ) ; } $ cache_file -> delete ( ) ; }
Remove a cache data
1,039
public function touch ( $ key , $ duration = NULL ) { $ cache_file = new File ( $ key . self :: CACHE_FILE_EXT , $ this -> config -> getCacheRoot ( ) ) ; if ( ! $ cache_file -> exists ( ) ) { throw ( new CacheFileNotFoundException ( $ cache_file ) ) ; } $ cache_file -> touch ( ) ; }
Rewrite cache expiration time
1,040
protected function find ( $ array , $ key ) { if ( empty ( $ key ) && ! is_numeric ( $ key ) || empty ( $ array ) || ! is_array ( $ array ) ) { return [ false , null ] ; } $ partsOfKey = explode ( '.' , $ key ) ; $ variants = [ ] ; $ parts = [ ] ; do { $ partial = implode ( '.' , $ partsOfKey ) ; if ( array_key_exists ( $ partial , $ array ) ) { if ( ! count ( $ parts ) ) { return [ true , $ array [ $ partial ] ] ; } $ variants [ implode ( '.' , $ parts ) ] = $ array [ $ partial ] ; } array_unshift ( $ parts , array_pop ( $ partsOfKey ) ) ; } while ( count ( $ partsOfKey ) ) ; foreach ( $ variants as $ path => $ branch ) { list ( $ has , $ value ) = $ this -> find ( $ branch , $ path ) ; if ( $ has ) { return [ true , $ value ] ; } } return [ false , null ] ; }
Checks existence and returns the value of the key
1,041
protected function filterMedias ( $ medias , $ currentPage , $ itemCount ) { if ( 0 == $ itemCount ) { return $ medias ; } $ filteredMedias = array ( ) ; $ offset = ( $ currentPage - 1 ) * $ itemCount ; for ( $ i = $ offset ; $ i < $ offset + $ itemCount && isset ( $ medias [ $ i ] ) ; $ i ++ ) { $ filteredMedias [ ] = $ medias [ $ i ] ; } return $ filteredMedias ; }
Filter medias to display
1,042
public function generateTokenHTML ( $ force = false ) { if ( $ force ) { $ token = $ this -> generateToken ( ) ; } else { if ( ! isset ( $ this -> lastToken ) ) { $ this -> lastToken = $ this -> generateToken ( ) ; } $ token = $ this -> lastToken ; } return '<input type="hidden" name="' . self :: HTML_PREFIX . $ this -> name . '" value="' . $ token . '" />' ; }
Generate a new token and return HTML input tag
1,043
public function validate ( $ token ) { if ( ! isset ( $ _SESSION [ self :: SESSION_KEY ] [ $ this -> name ] ) ) { return false ; } $ TOKEN_SESSION = & $ _SESSION [ self :: SESSION_KEY ] [ $ this -> name ] ; if ( empty ( $ token ) || empty ( $ TOKEN_SESSION ) || ! isset ( $ TOKEN_SESSION [ $ token ] ) ) { return false ; } $ TOKEN_SESSION [ $ token ] ++ ; if ( $ TOKEN_SESSION [ $ token ] >= $ this -> maxUsage ) { unset ( $ TOKEN_SESSION [ $ token ] ) ; } return true ; }
Validate the given token
1,044
public function validateForm ( InputRequest $ request , $ domain = null ) { if ( ! $ this -> validateCurrent ( $ request ) ) { throw new UserException ( self :: ERROR_INVALIDTOKEN , $ domain ) ; } }
Validate the given token from form or throw an UserException
1,045
public function validateCurrent ( InputRequest $ request ) { return $ this -> validate ( $ request -> getInputValue ( self :: HTML_PREFIX . $ this -> name ) ) ; }
Validate token in request
1,046
public static function create ( IOInterface $ io , Composer $ composer , InputInterface $ input ) : BaseInstaller { $ config = $ composer -> getConfig ( ) ; $ installer = new BaseInstaller ( $ io , $ config , $ composer -> getPackage ( ) , $ composer -> getDownloadManager ( ) , $ composer -> getRepositoryManager ( ) , $ composer -> getLocker ( ) , $ composer -> getInstallationManager ( ) , $ composer -> getEventDispatcher ( ) , $ composer -> getAutoloadGenerator ( ) ) ; [ $ preferSource , $ preferDist ] = self :: getPreferredInstallOptions ( $ config , $ input ) ; $ optimize = self :: getOption ( $ input , 'optimize-autoloader' ) || ( bool ) $ config -> get ( 'optimize-autoloader' ) ; $ authoritative = self :: getOption ( $ input , 'classmap-authoritative' ) || ( bool ) $ config -> get ( 'classmap-authoritative' ) ; $ apcu = self :: getOption ( $ input , 'apcu-autoloader' ) || ( bool ) $ config -> get ( 'apcu-autoloader' ) ; $ installer -> disablePlugins ( ) -> setPreferSource ( $ preferSource ) -> setPreferDist ( $ preferDist ) -> setDryRun ( self :: getOption ( $ input , 'dry-run' ) ) -> setVerbose ( self :: getOption ( $ input , 'verbose' ) ) -> setDevMode ( ! self :: getOption ( $ input , 'no-dev' ) ) -> setSuggestedPackagesReporter ( new SuggestedPackagesReporter ( new NullIO ( ) ) ) -> setDumpAutoloader ( ! self :: getOption ( $ input , 'no-autoloader' ) ) -> setRunScripts ( ! self :: getOption ( $ input , 'no-scripts' ) ) -> setOptimizeAutoloader ( $ optimize ) -> setClassMapAuthoritative ( $ authoritative ) -> setApcuAutoloader ( $ apcu ) -> setIgnorePlatformRequirements ( self :: getOption ( $ input , 'ignore-platform-reqs' ) ) -> setUpdate ( true ) ; return $ installer ; }
Create a configured Composer Installer .
1,047
private static function getPreferredInstallOptions ( Config $ config , InputInterface $ input ) : array { $ preferSource = false ; $ preferDist = false ; switch ( $ config -> get ( 'preferred-install' ) ) { case 'source' : $ preferSource = true ; break ; case 'dist' : $ preferDist = true ; break ; case 'auto' : default : break ; } $ preferSource = self :: getOption ( $ input , 'prefer-source' , $ preferSource ) ; $ preferDist = self :: getOption ( $ input , 'prefer-dist' , $ preferDist ) ; return [ $ preferSource , $ preferDist ] ; }
Returns preferSource and preferDist values based on the configuration .
1,048
private static function getOption ( InputInterface $ input , string $ name , bool $ default = false ) : bool { return $ input -> hasOption ( $ name ) ? ( bool ) $ input -> getOption ( $ name ) : $ default ; }
Returns default if options is not found .
1,049
public function getMeetingsAction ( ) { $ em = $ this -> getDoctrine ( ) -> getManager ( ) ; $ meetings = $ em -> getRepository ( 'InterneSeanceBundle:Meeting' ) -> findAll ( ) ; $ view = $ this -> view ( $ meetings , Response :: HTTP_OK ) ; return $ this -> handleView ( $ view ) ; }
Gets the list of all Meetings .
1,050
public function getMeetingAction ( Meeting $ meeting ) { $ view = $ this -> view ( $ meeting , Response :: HTTP_OK ) ; return $ this -> handleView ( $ view ) ; }
Gets a specific Meeting .
1,051
public function createNew ( string $ providerName , string $ credentialPubKey , string $ accessToken , string $ tokenSecret = '' , string $ signupHash = '' ) : array { $ array = [ 'provider' => $ providerName , 'access_token' => $ accessToken , 'credential' => $ credentialPubKey ] ; if ( ! empty ( $ tokenSecret ) ) { $ array [ 'token_secret' ] = $ tokenSecret ; } if ( ! empty ( $ signupHash ) ) { $ array [ 'signup_hash' ] = $ signupHash ; } return $ this -> sendPost ( '/sso' , [ ] , $ array ) ; }
Creates a new SSO .
1,052
final public function format ( $ format ) { if ( is_null ( $ this -> value ) ) { return null ; } else { return $ this -> value -> format ( $ format ) ; } }
Formats the current value given a formatting string
1,053
final public function hasPassed ( DateTime $ dateTime = null ) { $ dateTime = $ dateTime ? : DateTime :: createFromFormat ( "U.u" , $ this -> unixTimestampAsUuFormat ( microtime ( true ) ) ) ; return $ this -> value < $ dateTime ; }
Whether the date time has elapsed
1,054
public static function setConnection ( ) { $ dhost = getenv ( 'DB_HOST' ) ; $ dbase = getenv ( 'DB_BASE' ) ; $ duser = getenv ( 'DB_USER' ) ; $ dpass = getenv ( 'DB_PASS' ) ; $ opt = [ PDO :: ATTR_ERRMODE => PDO :: ERRMODE_EXCEPTION , PDO :: ATTR_DEFAULT_FETCH_MODE => PDO :: FETCH_OBJ , PDO :: ATTR_EMULATE_PREPARES => false , ] ; try { self :: $ pdo = new PDO ( "mysql:host=$dhost;dbname=$dbase" , $ duser , $ dpass , $ opt ) ; } catch ( \ Exception $ exception ) { var_dump ( $ exception -> getMessage ( ) ) ; exit ( ) ; } }
Connection to DB
1,055
public function getSignin ( ) { if ( Sentinel :: check ( ) ) { if ( Sentinel :: inRole ( 'admin' ) ) return Redirect :: route ( 'home' ) ; else return Redirect :: route ( 'user.home' ) ; } return View ( 'auth.login' ) ; }
Account sign in .
1,056
public function getForgotPasswordConfirm ( $ userId , $ passwordResetCode ) { if ( ! $ user = Sentinel :: findById ( $ userId ) ) { return Redirect :: route ( 'forgot-password' ) -> with ( 'error' , Lang :: get ( 'base.auth.forgot_password_confirm.error' ) ) ; } return View ( 'auth.forgot-password-confirm' , compact ( 'userId' , 'passwordResetCode' ) ) ; }
Forgot Password Confirmation page .
1,057
public function getActivate ( $ userId , $ activationCode ) { if ( Sentinel :: check ( ) ) { if ( Sentinel :: inRole ( 'admin' ) ) return Redirect :: route ( 'home' ) ; else return Redirect :: route ( 'user.home' ) ; } if ( ! $ user = Sentinel :: findById ( $ userId ) ) { return Redirect :: route ( 'login' ) -> with ( 'error' , Lang :: get ( 'base.auth.activate.error' ) ) ; } if ( Activation :: complete ( $ user , $ activationCode ) ) { $ user -> status = 1 ; $ user -> save ( ) ; return Redirect :: route ( 'login' ) -> with ( 'success' , Lang :: get ( 'base.auth.activate.success' ) ) ; } else { $ error = Lang :: get ( 'base.auth.activate.error' ) ; return Redirect :: route ( 'login' ) -> with ( 'error' , $ error ) ; } }
User account activation page .
1,058
public function postSignin ( ) { $ isEmail = preg_match ( '/@/' , Input :: get ( 'email' ) ) ; $ rules = array ( 'email' => 'required|email' , 'password' => 'required|between:3,32' , ) ; if ( ! $ isEmail ) $ rules [ 'email' ] = 'required' ; $ validator = Validator :: make ( Input :: all ( ) , $ rules ) ; if ( $ validator -> fails ( ) ) { return back ( ) -> withInput ( ) -> withErrors ( $ validator ) ; } try { foreach ( Sentinel :: createModel ( ) -> getLoginNames ( ) as $ loginName ) { $ data = array ( $ loginName => Input :: only ( 'email' ) [ "email" ] , "password" => Input :: only ( 'password' ) [ "password" ] ) ; if ( Sentinel :: authenticate ( $ data , Input :: get ( 'remember-me' , false ) ) ) { $ user = Sentinel :: check ( ) ; $ user -> update ( [ 'ip' => Request :: ip ( ) ] ) ; Base :: Log ( $ user -> username . ' (' . $ user -> first_name . ' ' . $ user -> last_name . ') logged in with IP ' . Request :: ip ( ) ) ; return Redirect :: route ( "home" ) -> with ( 'success' , Lang :: get ( 'base.auth.signin.success' ) ) ; } } $ this -> messageBag -> add ( 'email' , Lang :: get ( 'base.auth.account.not_found' ) ) ; } catch ( NotActivatedException $ e ) { $ this -> messageBag -> add ( 'email' , Lang :: get ( 'base.auth.account.not_activated' ) ) ; } catch ( ThrottlingException $ e ) { $ delay = $ e -> getDelay ( ) ; $ this -> messageBag -> add ( 'email' , Lang :: get ( 'base.auth.account.suspended' , compact ( 'delay' ) ) ) ; } Base :: Log ( 'Login attempt registred for ' . Input :: only ( 'email' ) [ "email" ] . ' from IP ' . Request :: ip ( ) ) ; return back ( ) -> withInput ( ) -> withErrors ( $ this -> messageBag ) ; }
Account sign in form processing .
1,059
public function postForgotPassword ( ) { $ rules = array ( 'email' => 'required|email' , ) ; $ validator = Validator :: make ( Input :: all ( ) , $ rules ) ; if ( $ validator -> fails ( ) ) { return Redirect :: to ( URL :: previous ( ) ) -> withInput ( ) -> withErrors ( $ validator ) ; } $ user = Sentinel :: findByCredentials ( [ 'email' => Input :: get ( 'email' ) ] ) ; if ( $ user ) { $ reminder = Reminder :: exists ( $ user ) ? : Reminder :: create ( $ user ) ; $ data = array ( 'user' => $ user , 'forgotPasswordUrl' => URL :: route ( 'forgot-password-confirm' , [ $ user -> id , $ reminder -> code ] ) , ) ; Base :: Log ( 'Forgot password request for ' . $ user -> username . ' (' . $ user -> first_name . ' ' . $ user -> last_name . ') from IP ' . Request :: ip ( ) ) ; Mail :: queue ( 'emails.auth.forgot-password' , $ data , function ( $ m ) use ( $ user ) { $ m -> to ( $ user -> email , $ user -> first_name . ' ' . $ user -> last_name ) ; $ m -> subject ( Lang :: get ( 'base.mails.recovery' ) ) ; } ) ; } return Redirect :: to ( URL :: previous ( ) ) -> with ( 'success' , Lang :: get ( 'base.auth.forgot_password.success' ) ) ; }
Forgot password form processing page .
1,060
public function postForgotPasswordConfirm ( $ userId , $ passwordResetCode ) { $ rules = array ( 'password' => 'required|between:3,32' , 'password_confirm' => 'required|same:password' ) ; $ validator = Validator :: make ( Input :: all ( ) , $ rules ) ; if ( $ validator -> fails ( ) ) { return Redirect :: route ( 'forgot-password-confirm' , compact ( [ 'userId' , 'passwordResetCode' ] ) ) -> withInput ( ) -> withErrors ( $ validator ) ; } $ user = Sentinel :: findById ( $ userId ) ; if ( ! $ reminder = Reminder :: complete ( $ user , $ passwordResetCode , Input :: get ( 'password' ) ) ) { Base :: Log ( 'Forgot password confirm failed for ' . $ user -> username . ' (' . $ user -> first_name . ' ' . $ user -> last_name . ') from IP ' . Request :: ip ( ) ) ; return Redirect :: route ( 'login' ) -> with ( 'error' , Lang :: get ( 'base.auth.forgot_password_confirm.error' ) ) ; } else { Mail :: queue ( 'emails.auth.password-changed' , [ 'user' => $ user ] , function ( $ m ) use ( $ user ) { $ m -> to ( $ user -> email , $ user -> first_name . ' ' . $ user -> last_name ) ; $ m -> subject ( Lang :: get ( 'base.mails.password_changed' ) ) ; } ) ; } Base :: Log ( 'Forgot password confirmed for ' . $ user -> username . ' (' . $ user -> first_name . ' ' . $ user -> last_name . ') from IP ' . Request :: ip ( ) ) ; return Redirect :: route ( 'login' ) -> with ( 'success' , Lang :: get ( 'base.auth.forgot_password_confirm.success' ) ) ; }
Forgot Password Confirmation form processing page .
1,061
public static function factory ( $ config = array ( ) ) { $ defaults = array ( 'scheme' => 'http' , 'om_classes' => array ( 'order' => 'Dzangocart\OM\Order' , 'sale' => 'Dzangocart\OM\Sale' , 'customer' => 'Dzangocart\OM\Customer' , 'address' => 'Dzangocart\OM\Address' , 'category' => 'Dzangocart\OM\Category' ) ) ; $ required = array ( 'api_url' , 'token' ) ; $ config = Collection :: fromConfig ( $ config , $ defaults , $ required ) ; $ client = new self ( $ config -> get ( 'api_url' ) , $ config ) ; $ description = ServiceDescription :: factory ( __DIR__ . '/dzangocart.json' ) ; $ client -> setDescription ( $ description ) ; return $ client ; }
Factory method to create a new DzangocartClient
1,062
public function remember ( string $ section ) : bool { $ arr = $ this -> cacheStore -> get ( $ section ) ; if ( $ arr !== null ) { $ this -> memory [ $ section ] = & $ arr ; return true ; } return false ; }
Load section into memory to make subsequent getter calls read from memory instead of physical store .
1,063
public function enableCurlOptionProxy ( $ guzzleRequest ) { $ guzzleRequest -> getCurlOptions ( ) -> add ( CURLOPT_PROXY , "127.0.0.1" ) ; $ guzzleRequest -> getCurlOptions ( ) -> add ( CURLOPT_PROXYPORT , 8890 ) ; return $ guzzleRequest ; }
enable those two lines in order to debug api calls with aproxy like charles
1,064
public function getMethodTemplate ( ) { if ( ! isset ( $ this -> methodTemplate ) ) { $ this -> methodTemplate = $ this -> _getMethodTemplate ( ) ; } return $ this -> methodTemplate ; }
Get method template
1,065
protected function getChild ( string $ name ) : Path { $ full_path = "{$this->path}/$name" ; if ( $ this -> driver -> isDir ( $ full_path ) ) { return $ this -> driver -> getDirectory ( $ full_path ) ; } return $ this -> driver -> getFile ( $ full_path ) ; }
Gets a child of this directory
1,066
public static function registerMock ( $ object , string $ className , array $ args = [ ] , string $ namespace = 'default' , string $ mockNamespace = self :: MOCK_ENABLED ) : void { static :: $ instances [ $ mockNamespace ] [ $ className ] [ $ namespace ] = $ object ; }
Register a mock object
1,067
public static function cleanMocks ( string $ mockNamespace = self :: MOCK_ENABLED ) : void { if ( isset ( static :: $ instances [ $ mockNamespace ] ) ) { unset ( static :: $ instances [ $ mockNamespace ] ) ; } }
Clean mock context
1,068
public static function buildObject ( $ className , array $ args = [ ] , $ instanceName = 'default' , $ beforeBuildBootstrapMethod = null , $ afterBuildBootstrapMethod = null ) { if ( ! isset ( static :: $ instances [ static :: $ mockNamespace ] [ $ className ] [ $ instanceName ] ) ) { if ( $ beforeBuildBootstrapMethod !== null ) { $ bootstrap = Container :: getBootstrap ( ) ; if ( ! is_callable ( [ $ bootstrap , $ beforeBuildBootstrapMethod ] ) ) { throw new ArchException ( "Bootstrap method $beforeBuildBootstrapMethod() must be declared in your bootstrap file" ) ; } $ bootstrap -> $ beforeBuildBootstrapMethod ( ) ; } $ class = new \ ReflectionClass ( $ className ) ; if ( ! $ class -> isInstantiable ( ) ) { throw new ArchException ( 'Class ' . $ className . ' must be instanciable' ) ; } static :: $ instances [ static :: $ mockNamespace ] [ $ className ] [ $ instanceName ] = count ( $ args ) ? $ class -> newInstanceArgs ( $ args ) : $ class -> newInstance ( ) ; if ( $ afterBuildBootstrapMethod !== null ) { $ bootstrap = Container :: getBootstrap ( ) ; if ( ! method_exists ( $ bootstrap , $ afterBuildBootstrapMethod ) ) { throw new ArchException ( "Bootstrap method $afterBuildBootstrapMethod() must be declared in your bootstrap file" ) ; } $ bootstrap -> $ afterBuildBootstrapMethod ( ) ; } } return static :: $ instances [ static :: $ mockNamespace ] [ $ className ] [ $ instanceName ] ; }
Build an object or get existing object from class name and serveral parameters
1,069
protected static function ucFirst ( $ txt ) : string { if ( class_exists ( '\Osf\Stream\Text' ) ) { return \ Osf \ Stream \ Text :: ucFirst ( $ txt ) ; } return ucfirst ( ( string ) $ txt ) ; }
Bind to stream - > ucfirst if installed
1,070
public function showArticles ( string $ lang , string $ year = null , string $ month = null , string $ day = null , string $ slug = null ) { if ( $ slug ) return $ this -> showArticle ( $ lang , $ year , $ month , $ day , $ slug ) ; if ( $ day ) return $ this -> showByDate ( ( new Carbon ( $ year . '-' . $ month . '-' . $ day ) ) -> startOfDay ( ) , ( new Carbon ( $ year . '-' . $ month . '-' . $ day ) ) -> endOfDay ( ) ) ; if ( $ month ) return $ this -> showByDate ( ( new Carbon ( $ year . '-' . $ month ) ) -> startOfMonth ( ) , ( new Carbon ( $ year . '-' . $ month ) ) -> endOfMonth ( ) ) ; if ( $ year ) return $ this -> showByDate ( ( new Carbon ( $ year ) ) -> startOfYear ( ) , ( new Carbon ( $ year ) ) -> endOfYear ( ) ) ; abort ( 404 , 'Page not found' ) ; }
Based on provided data showing content
1,071
protected function showByDate ( Carbon $ startAt , Carbon $ endAt ) { $ data = HCPages :: with ( 'translation' ) -> where ( 'type' , 'ARTICLE' ) -> where ( 'publish_at' , '>=' , $ startAt ) -> where ( 'publish_at' , '<=' , $ endAt ) -> where ( 'publish_at' , '<' , Carbon :: now ( ) ) -> paginate ( 20 ) -> toArray ( ) ; $ data [ 'data' ] = removeRecordsWithNoTranslation ( $ data [ 'data' ] ) ; return hcview ( 'HCPages::article.list' , [ 'data' => [ 'list' => $ data ] ] ) ; }
Showing list of pages by date
1,072
protected function showArticle ( string $ lang , string $ year , string $ month , string $ day , string $ slug ) { $ r = HCPages :: getTableName ( ) ; $ t = HCPagesTranslations :: getTableName ( ) ; $ query = HCPages :: with ( [ 'translation' , 'categories' , 'author' ] ) -> select ( HCPages :: getFillableFields ( true ) ) ; $ query -> join ( $ t , "$r.id" , "=" , "$t.record_id" ) -> where ( "$t.slug" , $ slug ) -> where ( "$t.language_code" , $ lang ) -> where ( "$r.type" , 'ARTICLE' ) -> where ( 'publish_at' , '>=' , ( new Carbon ( $ year . '-' . $ month . '-' . $ day ) ) -> startOfDay ( ) ) -> where ( 'publish_at' , '<=' , ( new Carbon ( $ year . '-' . $ month . '-' . $ day ) ) -> endOfDay ( ) ) -> where ( 'publish_at' , '<' , Carbon :: now ( ) ) ; $ data = $ query -> first ( ) ; if ( ! $ data ) abort ( 404 , 'Page not found' ) ; return hcview ( 'HCPages::article.single' , [ 'data' => [ 'article' => $ data -> toArray ( ) ] ] ) ; }
Returning single article view
1,073
public function createFromArray ( array $ data ) { $ headers = json_encode ( Arr :: path ( $ this -> emailConfig , 'defaults.headers' , [ ] ) ) ; if ( isset ( $ data [ 'sender_localpart' ] ) ) { if ( ! Arr :: path ( $ this -> emailConfig , 'defaults.sender.domain' ) ) { throw new \ Exception ( 'defaults.sender.domain not set in email config' ) ; } $ data [ 'sender_email' ] = ( Arr :: remove ( $ data , 'sender_localpart' ) . '@' . Arr :: path ( $ this -> emailConfig , 'defaults.sender.domain' ) ) ; } $ defaults = [ 'headers' => $ headers , 'sender_email' => Arr :: path ( $ this -> emailConfig , 'defaults.sender.email' ) , 'sender_name' => Arr :: path ( $ this -> emailConfig , 'defaults.sender.name' ) , ] ; $ email = $ this -> emailMapper -> getPrototype ( ) ; $ email = $ email -> exchangeArray ( array_merge ( $ defaults , $ data ) ) ; $ email = $ this -> emailMapper -> persist ( $ email ) ; return $ email ; }
Create an email entity from an array and populate with default data
1,074
public function filter ( EventInterface $ event ) { if ( ! $ event instanceof UserEventInterface ) { return null ; } $ channels = $ this -> getChannels ( $ event ) ; $ nick = $ event -> getNick ( ) ; if ( empty ( $ channels ) || $ nick === null ) { return null ; } $ connection = $ event -> getConnection ( ) ; foreach ( $ channels as $ channel ) { $ userModes = $ this -> userMode -> getUserModes ( $ connection , $ channel , $ nick ) ; $ commonModes = array_intersect ( $ userModes , $ this -> modes ) ; if ( $ commonModes ) { return true ; } } return false ; }
Filters events that are not user - specific or are from users with specified modes .
1,075
protected function configure ( ) { if ( $ this -> docs -> getIs ( "description" ) ) { $ this -> setDescription ( $ this -> docs [ "description" ] ) ; } if ( $ this -> docs -> getIs ( "help" ) ) { $ this -> setHelp ( $ this -> docs [ "help" ] ) ; } }
input and output
1,076
public function listenApplicationEvents ( Listener \ Application $ listener ) { $ this -> di -> get ( 'eventsManager' ) -> attach ( 'application' , $ listener , PHP_INT_MAX ) ; return $ this ; }
Listen application s events
1,077
public function listenDispatchEvents ( Listener \ Dispatch $ listener ) { $ this -> di -> get ( 'eventsManager' ) -> attach ( 'dispatch' , $ listener , PHP_INT_MAX ) ; return $ this ; }
Listen dispatch s events
1,078
public function getVar ( $ varName ) { if ( ! isset ( $ this -> variableList [ $ varName ] ) ) { trigger_error ( 'Variable "' . $ varName . '" isn\'t defined in View.' , E_USER_WARNING ) ; return false ; } return $ this -> variableList [ $ varName ] ; }
Get var send to View from Controller or Layout
1,079
public function render ( ) { $ viewPath = $ this -> getDirectory ( ) . '/' . $ this -> getName ( ) . '.' . $ this -> getExtension ( ) ; if ( ! file_exists ( $ viewPath ) ) { trigger_error ( 'View file "' . $ viewPath . '" doesn\'t exist.' , E_USER_ERROR ) ; return false ; } if ( Configuration :: read ( 'mvc.autoload_shared_var' ) && ! empty ( $ this -> variableList ) ) { foreach ( $ this -> variableList as $ varName => $ varValue ) { $ { $ varName } = $ varValue ; } } ob_start ( ) ; require ( $ viewPath ) ; echo PHP_EOL ; return ob_get_clean ( ) ; }
Render layout from view
1,080
public function shouldCreateSnapshot ( AggregateRoot $ root ) { if ( $ root -> hasChanges ( ) ) { $ lastSnapshot = $ this -> store -> get ( $ root -> getIdentity ( ) ) ; $ threshold = new \ DateTime ( date ( 'c' , strtotime ( '-' . $ this -> threshold ) ) ) ; if ( $ lastSnapshot -> getCreationDate ( ) > $ threshold ) { return true ; } } return false ; }
Should a snapshot be created?
1,081
public static function sort ( $ array , $ key , $ order = 'asc' , $ sort_flags = SORT_REGULAR ) { if ( ! is_array ( $ array ) ) { throw new \ InvalidArgumentException ( 'Arr::sort() - $array must be an array.' ) ; } if ( empty ( $ array ) ) { return $ array ; } foreach ( $ array as $ k => $ v ) { $ b [ $ k ] = static :: get ( $ v , $ key ) ; } switch ( $ order ) { case 'asc' : asort ( $ b , $ sort_flags ) ; break ; case 'desc' : arsort ( $ b , $ sort_flags ) ; break ; default : throw new \ InvalidArgumentException ( 'Arr::sort() - $order must be asc or desc.' ) ; break ; } foreach ( $ b as $ key => $ val ) { $ c [ ] = $ array [ $ key ] ; } return $ c ; }
Sorts a multi - dimensional array by it s values .
1,082
public function guessType ( $ class , $ property ) { if ( ! $ ret = $ this -> getMetadata ( $ class ) ) { return new TypeGuess ( 'text' , array ( ) , Guess :: LOW_CONFIDENCE ) ; } list ( $ metadata , $ name ) = $ ret ; $ idFieldNames = $ metadata -> getIdentifierFieldNames ( ) ; if ( count ( $ idFieldNames ) == 1 && $ property == $ idFieldNames [ 0 ] ) { return new TypeGuess ( 'id' , array ( 'class' => $ class ) , Guess :: HIGH_CONFIDENCE ) ; } $ guess = parent :: guessType ( $ class , $ property ) ; $ options = $ guess -> getOptions ( ) ; switch ( $ guess -> getType ( ) ) { case 'number' : return new TypeGuess ( 'float' , $ guess -> getOptions ( ) , $ guess -> getConfidence ( ) ) ; case 'entity' : if ( $ options [ 'multiple' ] ) { return new TypeGuess ( 'collection' , array ( 'type' => 'entity' , 'options' => array ( 'data_class' => $ options [ 'class' ] ) ) , $ guess -> getConfidence ( ) ) ; } return new TypeGuess ( 'entity' , array ( 'data_class' => $ options [ 'class' ] ) , $ guess -> getConfidence ( ) ) ; case 'textarea' : return new TypeGuess ( 'text' , $ guess -> getOptions ( ) , $ guess -> getConfidence ( ) ) ; case 'checkbox' : return new TypeGuess ( 'boolean' , $ guess -> getOptions ( ) , $ guess -> getConfidence ( ) ) ; default : return new TypeGuess ( $ guess -> getType ( ) , $ guess -> getOptions ( ) , $ guess -> getConfidence ( ) ) ; } }
Returns a field guess for a property name of a class . It is based in great part upon the guesser with the same name in symfony core but some guesses are updated to match DataView types before returned to the factory .
1,083
public function getFullQualifiedNamespace ( ) { if ( empty ( $ this -> fullQualifiedNamespace ) && ! empty ( $ this -> class ) ) { $ this -> fullQualifiedNamespace = $ this -> getFullQualifiedNamespaceTrait ( $ this -> namespace , $ this -> class ) ; } return $ this -> fullQualifiedNamespace ; }
When the full qualified namespace is empty but the class and namespace are set we concat these two values to the full qualified namespace
1,084
public function setFullQualifiedNamespace ( $ fullQualifiedNamespace ) { if ( empty ( $ this -> class ) && empty ( $ this -> namespace ) ) { $ extracted = $ this -> extractNamespace ( $ fullQualifiedNamespace ) ; $ this -> class = $ extracted [ 'class' ] ; $ this -> namespace = $ extracted [ 'namespace' ] ; } $ this -> fullQualifiedNamespace = $ fullQualifiedNamespace ; }
When we set the full qualified namespace we automatically set the class and the namespace
1,085
public function clear ( ) { foreach ( get_object_vars ( $ this ) as $ property => $ value ) { if ( is_array ( $ value ) ) { $ tempValue = [ ] ; } else { $ tempValue = null ; } $ this -> { $ property } = $ tempValue ; } }
Clears the current object so when we do an incremental cache build we can reuse the object when the timestamps are not the same
1,086
public function matches ( string $ value ) : bool { $ check = @ preg_match ( $ this -> pattern , $ value ) ; if ( false === $ check ) { throw new \ RuntimeException ( sprintf ( 'Failure while matching "%s", reason: %s.' , $ this -> pattern , $ this -> messageFor ( preg_last_error ( ) ) ) ) ; } return ( ( 1 != $ check ) ? ( false ) : ( true ) ) ; }
test that the given value complies with the regular expression
1,087
public function execute ( Framework $ framework , CliRequest $ request , Response $ response ) { $ this -> assetCacheManager -> clearAssetCache ( ) ; $ response -> setOutputPart ( 'cacheCleared' , 'The asset cache was successfully cleared!' ) ; }
This event handler clears the assets cache .
1,088
public function getAnnotations ( ) { if ( $ this -> reader === null ) { return null ; } if ( $ this -> annotations === null ) { $ this -> annotations = [ ] ; foreach ( $ this -> reader -> getAnnotations ( ) as $ annotation ) { $ key = "" ; $ value = "" ; if ( ( $ pos = mb_strpos ( $ annotation , " " ) ) === false ) { $ key = mb_substr ( $ annotation , 1 ) ; } else { $ key = mb_substr ( $ annotation , 1 , $ pos - 1 ) ; $ value = ltrim ( mb_substr ( $ annotation , $ pos ) ) ; } if ( ! array_key_exists ( $ key , $ this -> annotations ) ) { $ this -> annotations [ $ key ] = [ ] ; } $ this -> annotations [ $ key ] [ ] = $ value ; } } return $ this -> annotations ; }
Returns the annotations from the doc comment .
1,089
public function encrypt ( ) { Service :: $ log -> msg ( 'Encryption started' ) ; if ( $ this -> encryptConfig -> get ( 'Type' , 'openssl' ) == 'openssl' ) { $ cmd = 'openssl bf < ' . $ this -> source . ' > ' . $ this -> source . '.bf -k \'' . $ this -> encryptConfig -> Passphrase . '\'' ; $ archive = $ this -> source . '.bf' ; } else if ( $ this -> encryptConfig -> get ( 'Type' ) == 'gpg' ) { $ cmd = 'echo \'' . $ this -> encryptConfig -> Passphrase . '\' | gpg --batch --passphrase-fd 0 -c ' . $ this -> source ; $ archive = $ this -> source . '.gpg' ; } else { throw new \ Exception ( sprintf ( 'Unknown encryption type "%s"' , $ this -> encryptConfig -> get ( 'Type' ) ) ) ; } Service :: $ log -> msg ( 'Encryption command: ' . $ this -> encryptConfig -> get ( 'Type' ) ) ; system ( $ cmd ) ; Service :: $ log -> msg ( 'Encryption ended' ) ; Cleanup :: addToQueue ( $ archive , Cleanup :: TYPE_FILE ) ; return $ archive ; }
Does the archive encryption .
1,090
private function runParentClass ( $ version ) { $ this -> setAutoExit ( false ) ; $ this -> setCatchExceptions ( true ) ; parent :: __construct ( 'Anonym' , $ version ) ; }
execute parent class
1,091
protected function resolveCommands ( ) { $ this -> commands = $ commands = array_merge ( $ this -> kernel , $ this -> commands ) ; foreach ( $ commands as $ command ) { $ command = $ this -> getContainer ( ) -> make ( $ command ) -> setContainer ( $ this -> getContainer ( ) ) ; $ this -> addToParent ( $ command ) ; } }
resolve the commands
1,092
protected function execute ( InputInterface $ input , OutputInterface $ output ) { $ templateName = $ input -> getArgument ( 'template' ) ; $ templates = $ this -> configurationManager -> get ( 'store.templates' ) ; $ templateFound = array_reduce ( $ templates , function ( $ alreadyFound , $ template ) use ( $ templateName ) { return $ alreadyFound || ( $ template [ 'bundle' ] == $ templateName ) ; } , false ) ; if ( ! $ templateFound ) { throw new Exception ( sprintf ( 'Template %s not found' , $ templateName ) ) ; } $ this -> configurationManager -> set ( 'store.template' , $ templateName ) ; $ formatter = $ this -> getHelper ( 'formatter' ) ; $ formattedLine = $ formatter -> formatSection ( 'OK' , 'Template "' . $ templateName . '" enabled' ) ; $ output -> writeln ( $ formattedLine ) ; }
This command enables a template
1,093
public function create ( ) { $ this -> keys [ 'session_id' ] = $ this -> _new_session_id ( ) ; $ this -> keys [ 'previous_id' ] = $ this -> keys [ 'session_id' ] ; $ this -> keys [ 'ip_hash' ] = md5 ( \ Input :: ip ( ) . \ Input :: real_ip ( ) ) ; $ this -> keys [ 'user_agent' ] = \ Input :: user_agent ( ) ; $ this -> keys [ 'created' ] = $ this -> time -> get_timestamp ( ) ; $ this -> keys [ 'updated' ] = $ this -> keys [ 'created' ] ; return $ this ; }
create a new session
1,094
public function write ( ) { if ( ! empty ( $ this -> keys ) or ! empty ( $ this -> data ) or ! empty ( $ this -> flash ) ) { parent :: write ( ) ; $ this -> rotate ( false ) ; $ this -> keys [ 'updated' ] = $ this -> time -> get_timestamp ( ) ; $ payload = $ this -> _serialize ( array ( $ this -> keys , $ this -> data , $ this -> flash ) ) ; $ this -> _write_memcached ( $ this -> keys [ 'session_id' ] , $ payload ) ; if ( isset ( $ this -> keys [ 'previous_id' ] ) and $ this -> keys [ 'previous_id' ] != $ this -> keys [ 'session_id' ] ) { $ payload = $ this -> _serialize ( array ( 'rotated_session_id' => $ this -> keys [ 'session_id' ] ) ) ; $ this -> _write_memcached ( $ this -> keys [ 'previous_id' ] , $ payload ) ; } $ this -> _set_cookie ( array ( $ this -> keys [ 'session_id' ] ) ) ; } return $ this ; }
write the session
1,095
protected function _write_memcached ( $ session_id , $ payload ) { if ( $ this -> memcached -> set ( $ this -> config [ 'cookie_name' ] . '_' . $ session_id , $ payload , $ this -> config [ 'expiration_time' ] ) === false ) { throw new \ FuelException ( 'Memcached returned error code "' . $ this -> memcached -> getResultCode ( ) . '" on write. Check your configuration.' ) ; } }
Writes the memcached entry
1,096
public static function mergeProps ( $ mergeStack , $ options = array ( ) ) { $ merged = array ( ) ; while ( $ mergeStack ) { $ props = \ array_shift ( $ mergeStack ) ; $ props = self :: moveShortcuts ( $ props ) ; $ props = self :: mergeClassesPrep ( $ merged , $ props ) ; $ props = self :: classnamesToArray ( $ props ) ; $ merged = ArrayUtil :: mergeDeep ( $ merged , $ props , $ options ) ; } return $ merged ; }
Merge field properties
1,097
public static function moveShortcuts ( $ props , $ addKeys = array ( ) ) { $ attribShortcuts = \ array_merge ( array ( 'checked' , 'disabled' , 'name' , 'required' , 'selected' , 'type' , 'value' , ) , $ addKeys ) ; if ( isset ( $ props [ 'attributes' ] ) ) { $ props [ 'attribs' ] = $ props [ 'attributes' ] ; unset ( $ props [ 'attributes' ] ) ; } if ( ! isset ( $ props [ 'attribs' ] ) ) { $ props [ 'attribs' ] = array ( ) ; } foreach ( $ attribShortcuts as $ k ) { if ( \ array_key_exists ( $ k , $ props ) && ! isset ( $ props [ 'attribs' ] [ $ k ] ) ) { $ props [ 'attribs' ] [ $ k ] = $ props [ $ k ] ; } unset ( $ props [ $ k ] ) ; } return $ props ; }
Move common attributes to attribs array
1,098
protected static function classnamesToArray ( $ props ) { foreach ( $ props as $ k => $ v ) { if ( \ strpos ( $ k , 'attribs' ) === 0 && isset ( $ v [ 'class' ] ) ) { if ( ! \ is_array ( $ v [ 'class' ] ) ) { $ props [ $ k ] [ 'class' ] = \ explode ( ' ' , $ v [ 'class' ] ) ; } } } return $ props ; }
Convert classname string to array
1,099
public static function resultFix ( & $ array ) { foreach ( $ array as & $ element ) { if ( $ element instanceof \ stdClass ) { self :: resultFix ( $ element ) ; } else { if ( \ is_object ( $ element ) && $ element instanceof ObjectID ) { $ element = ( string ) $ element ; } if ( \ is_object ( $ element ) && $ element instanceof UTCDateTime ) { $ element = ( new UTCDateTime ( ( string ) $ element ) ) -> toDateTime ( ) -> format ( 'Y-m-d H:i:s' ) ; } } } }
Cleanup result of query