idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
2,300
public function toJson ( ) { $ json = array ( ) ; $ json [ 'id' ] = $ this -> id ; $ json [ 'url' ] = $ this -> url ; $ json [ 'pattern' ] = $ this -> pattern ; $ json [ 'event' ] = $ this -> event ; $ json [ 'name' ] = $ this -> name ; $ json [ 'links' ] = $ this -> links ; return $ json ; }
Serializes Webhook object
2,301
public function formatName ( $ format = UserInterface :: NAME_FULL ) { $ first_name = $ this -> getFirstName ( ) ; $ last_name = $ this -> getLastName ( ) ; if ( empty ( $ first_name ) && empty ( $ last_name ) ) { list ( $ first_name , $ last_name ) = $ this -> getFirstAndLastNameFromEmail ( ) ; } if ( $ format == UserInterface :: NAME_FULL ) { return trim ( $ first_name . ' ' . $ last_name ) ; } else { if ( $ format == UserInterface :: NAME_SHORT_LAST_NAME ) { return $ this -> getLastName ( ) ? trim ( $ this -> getFirstName ( ) . ' ' . mb_substr ( $ this -> getLastName ( ) , 0 , 1 ) . '.' ) : $ this -> getFirstName ( ) ; } elseif ( $ format == UserInterface :: NAME_SHORT_FIRST_NAME ) { return $ this -> getFirstName ( ) ? trim ( mb_substr ( $ this -> getFirstName ( ) , 0 , 1 ) . '.' . ' ' . $ this -> getLastName ( ) ) : $ this -> getLastName ( ) ; } else { return mb_substr ( $ first_name , 0 , 1 ) . mb_substr ( $ last_name , 0 , 1 ) ; } } }
Return display name of this user .
2,302
public function getFirstAndLastNameFromEmail ( ) { $ exploded_full_name = explode ( ' ' , str_replace ( [ '.' , '-' , '_' ] , [ ' ' , ' ' , ' ' ] , substr ( $ this -> getEmail ( ) , 0 , strpos ( $ this -> getEmail ( ) , '@' ) ) ) ) ; if ( count ( $ exploded_full_name ) === 1 ) { $ first_name = mb_strtoupper ( mb_substr ( $ exploded_full_name [ 0 ] , 0 , 1 ) ) . mb_substr ( $ exploded_full_name [ 0 ] , 1 ) ; $ last_name = '' ; } else { $ full_name = [ ] ; foreach ( $ exploded_full_name as $ k ) { $ full_name [ ] = mb_strtoupper ( mb_substr ( $ k , 0 , 1 ) ) . mb_substr ( $ k , 1 ) ; } $ first_name = array_shift ( $ full_name ) ; $ last_name = implode ( ' ' , $ full_name ) ; } return [ $ first_name , $ last_name ] ; }
Try to get first and last name from email address .
2,303
private function describeManifest ( ManifestInterface $ manifest , OutputInterface $ output ) { $ builder = new ProcedureBuilder ( ) ; $ manifest -> configureProcedureBuilder ( $ builder ) ; $ output -> writeln ( sprintf ( "Manifest description for <info>%s</info>\n" , $ manifest -> getName ( ) ) ) ; $ output -> writeln ( "<fg=blue;options=bold>PROCEDURE CONFIGURATION</fg=blue;options=bold>\n" ) ; $ this -> describeProcedure ( $ builder -> getProcedure ( ) , $ output ) ; }
Describes a manifest .
2,304
private function describeProcedure ( Procedure $ procedure , OutputInterface $ output , $ depth = 0 ) { $ output -> writeln ( sprintf ( '%sProcedure <info>%s</info>' , str_repeat ( ' ' , $ depth ) , $ procedure -> getName ( ) ) ) ; $ this -> describeComponents ( $ procedure -> getSources ( ) , 'SOURCES' , $ output , $ depth ) ; $ this -> describeComponents ( $ procedure -> getWorkers ( ) , 'WORKERS' , $ output , $ depth ) ; $ this -> describeComponents ( $ procedure -> getTargets ( ) , 'TARGETS' , $ output , $ depth ) ; $ this -> describeChildProcedures ( $ procedure -> getChildren ( ) , $ output , $ depth ) ; $ output -> write ( "\n" ) ; }
Describes a procedure .
2,305
private function describeChildProcedures ( $ children , $ output , $ depth ) { if ( is_array ( $ children ) ) { $ output -> writeln ( sprintf ( '%s<comment>SUB-PROCEDURES</comment>' , str_repeat ( ' ' , $ depth ) ) ) ; foreach ( $ children as $ child ) { $ this -> describeProcedure ( $ child , $ output , $ depth + 2 ) ; $ output -> writeln ( '' ) ; } } }
Describes child procedures .
2,306
private function describeComponents ( $ components , $ name , OutputInterface $ output , $ depth = 0 ) { if ( is_array ( $ components ) ) { $ output -> writeln ( sprintf ( '%s<comment>%s</comment>' , str_repeat ( ' ' , $ depth ) , $ name ) ) ; foreach ( $ components as $ component ) { $ output -> writeln ( sprintf ( '%s%s' , str_repeat ( ' ' , $ depth + 4 ) , is_object ( $ component ) ? get_class ( $ component ) : get_class ( $ component [ 0 ] ) ) ) ; } } }
Describes components .
2,307
public function analyseSavedContent ( $ wikiPage ) { $ newPages = $ this -> parseNewPagesFrom ( $ wikiPage -> Content ) ; foreach ( $ newPages as $ pageTitle ) { $ trimmedTitle = trim ( $ pageTitle ) ; $ page = DataObject :: get_one ( 'WikiPage' , '"SiteTree"."Title" = \'' . Convert :: raw2sql ( $ trimmedTitle ) . '\'' ) ; if ( ! $ page ) { $ page = new WikiPage ( ) ; $ page -> Title = $ trimmedTitle ; $ page -> MenuTitle = $ trimmedTitle ; $ page -> ParentID = $ wikiPage -> ID ; $ page -> write ( ) ; if ( WikiPage :: $ auto_publish ) { $ page -> doPublish ( ) ; } } $ replacement = '<a href="[sitetree_link id=' . $ page -> ID . ']">' . $ pageTitle . '</a>' ; $ wikiPage -> Content = str_replace ( '[[' . $ pageTitle . ']]' , $ replacement , $ wikiPage -> Content ) ; } }
Analyse content just after it s saved . This is useful for creating new pages etc where referenced by particular formatting
2,308
public function parseNewPagesFrom ( $ content ) { $ pages = array ( ) ; if ( preg_match_all ( '/\[\[([\w\s_.-]+)\]\]/' , $ content , $ matches ) ) { foreach ( $ matches [ 1 ] as $ pageTitle ) { $ pages [ ] = $ pageTitle ; } } return $ pages ; }
Separated into a separate method for testing
2,309
protected function getSelect ( ) { $ html = '<select>' ; if ( is_array ( $ this -> window [ 'all' ] ) ) { $ html .= $ this -> getOptionLinks ( $ this -> window [ 'all' ] ) ; } $ html .= '</select>' ; return $ html ; }
Get the select tag with options for the URLs in the given array .
2,310
protected function getOptionLinks ( array $ urls ) { $ html = '' ; foreach ( $ urls as $ page => $ url ) { $ html .= $ this -> getOption ( $ url , $ page ) ; } return $ html ; }
Get option tags with links for the URLs in the given array .
2,311
protected function getOption ( $ url , $ page ) { if ( $ page == $ this -> paginator -> currentPage ( ) ) { return $ this -> getActiveOption ( $ page ) ; } return $ this -> getAvailableOption ( $ url , $ page ) ; }
Get html option tag .
2,312
private function parseBundle ( array $ tokenBundle , $ serverField , $ fromField ) { $ pref = null ; try { list ( $ variantTokenList , $ paramTokenList ) = $ this -> splitVariantAndParamTokens ( $ tokenBundle , $ fromField ) ; $ paramBundleList = $ this -> bundleTokens ( $ paramTokenList , Tokens :: PARAMS_SEPARATOR ) ; $ this -> validateParamBundleList ( $ paramBundleList , $ serverField ) ; $ pref = $ this -> createPreference ( $ variantTokenList , $ paramBundleList , $ serverField , $ fromField ) ; } catch ( InvalidVariantException $ e ) { if ( $ serverField ) { throw $ e ; } } return $ pref ; }
Accepts tokens for a single variant and returns the Preference value object encapsulating that data .
2,313
private function splitVariantAndParamTokens ( array $ tokenBundle , $ fromField ) { if ( PreferenceInterface :: MIME === $ fromField ) { $ this -> validateBundleMimeVariant ( $ tokenBundle ) ; $ variantTokenList = array_slice ( $ tokenBundle , 0 , 3 ) ; $ paramTokenList = array_slice ( $ tokenBundle , 3 ) ; } else { $ variantTokenList = array_slice ( $ tokenBundle , 0 , 1 ) ; $ paramTokenList = array_slice ( $ tokenBundle , 1 ) ; } return array ( $ variantTokenList , $ paramTokenList ) ; }
Splits the token list into variant & parameter arrays .
2,314
private function createPreference ( array $ variantTokenList , array $ paramBundleList , $ serverField , $ fromField ) { $ builder = $ this -> getBuilder ( $ fromField ) -> setFromField ( $ fromField ) -> setFromServer ( $ serverField ) -> setVariant ( implode ( '' , $ variantTokenList ) ) ; foreach ( $ paramBundleList as $ paramBundle ) { if ( $ this -> isQualityFactor ( $ paramBundle ) ) { $ builder = $ builder -> setQualityFactor ( $ paramBundle [ 2 ] ) ; break ; } } return $ builder -> get ( ) ; }
Accepts the bundled tokens for variant & parameter data and builds the Preference value object .
2,315
private function bundleTokens ( array $ tokenList , $ targetToken ) { $ bundleList = array ( ) ; $ bundle = array ( ) ; foreach ( $ tokenList as $ token ) { if ( $ targetToken === $ token ) { $ bundleList [ ] = $ bundle ; $ bundle = array ( ) ; } else { $ bundle [ ] = $ token ; } } $ bundleList [ ] = $ bundle ; $ bundleList = array_filter ( $ bundleList ) ; return $ bundleList ; }
Splits token list up into one bundle per variant for later processing .
2,316
private function validateBundleMimeVariant ( array $ bundle ) { if ( count ( $ bundle ) < 3 || Tokens :: MIME_SEPARATOR !== $ bundle [ 1 ] || Tokens :: isSeparator ( $ bundle [ 0 ] , true ) || Tokens :: isSeparator ( $ bundle [ 2 ] , true ) ) { throw new InvalidVariantException ( '"' . implode ( '' , $ bundle ) . '" is not a valid mime type' ) ; } }
Checks to see if the bundle is valid for a mime type if an anomaly is detected then an exception is thrown .
2,317
private function validateParamBundleList ( array $ paramBundleList , $ serverField ) { foreach ( $ paramBundleList as $ paramBundle ) { try { $ this -> validateParamBundle ( $ paramBundle ) ; } catch ( InvalidVariantException $ e ) { if ( $ serverField ) { throw $ e ; } } } }
Checks to see if the parameters are correctly formed if an anomaly is detected then an exception is thrown .
2,318
protected function request ( $ path , array $ data = null , $ method = null ) { $ authError = $ this -> authenticationError ( ) ; if ( null !== $ authError ) { return $ authError ; } $ url = 'https://api.cloudflare.com/client/v4/' . $ path ; $ args = $ this -> prepareRequestArguments ( $ data , $ method ) ; $ response = wp_remote_request ( $ url , $ args ) ; if ( is_wp_error ( $ response ) ) { return $ response ; } return $ this -> decode ( $ response ) ; }
API call method for sending requests via wp_remote_request .
2,319
private function authenticationError ( ) { if ( empty ( $ this -> email ) || empty ( $ this -> auth_key ) ) { return new WP_Error ( 'authentication-error' , 'Authentication information must be provided' ) ; } if ( ! is_email ( $ this -> email ) ) { return new WP_Error ( 'authentication-error' , 'Email is not valid' ) ; } return null ; }
Return WP Error if this object does not contain necessary info to perform API requests .
2,320
private function prepareRequestArguments ( array $ data = null , string $ method = null ) : array { $ data = $ data ?? [ ] ; $ method = $ method ?? 'GET' ; $ data = array_filter ( $ data , function ( $ val ) { return ( null !== $ val ) ; } ) ; $ headers = [ 'Content-Type' => 'application/json' , 'X-Auth-Email' => $ this -> email , 'X-Auth-Key' => $ this -> auth_key , ] ; $ args = [ 'body' => wp_json_encode ( $ data ) , 'headers' => $ headers , 'method' => strtoupper ( $ method ) , 'timeout' => 15 , ] ; return $ args ; }
Prepare arguments for wp_remote_request .
2,321
private function decode ( array $ response ) { $ decodedBody = json_decode ( $ response [ 'body' ] , true ) ; if ( null === $ decodedBody ) { return new WP_Error ( 'decode-error' , 'Unable to decode response body' , $ response ) ; } if ( true !== $ decodedBody [ 'success' ] ) { return $ this -> wpErrorFor ( $ decodedBody [ 'errors' ] , $ response ) ; } return $ response ; }
Decode Cloudflare response .
2,322
private function wpErrorFor ( array $ errors , array $ response ) : WP_Error { $ wpError = new WP_Error ; foreach ( $ errors as $ error ) { $ wpError -> add ( $ error [ 'code' ] , $ error [ 'message' ] , $ response ) ; } return $ wpError ; }
Decode Cloudflare error messages to WP Error .
2,323
static function GetEnvType ( ) { if ( ! is_array ( $ _SERVER ) || ! array_key_exists ( 'SERVER_NAME' , $ _SERVER ) || ! is_string ( $ _SERVER [ 'SERVER_NAME' ] ) || empty ( $ _SERVER [ 'SERVER_NAME' ] ) ) { return self :: ENV_UNKNOWN ; } $ nRet = self :: ENV_PRODUCTION ; $ sServerName = strtolower ( trim ( $ _SERVER [ 'SERVER_NAME' ] ) ) ; $ sRootDomain = strtolower ( trim ( self :: ROOT_DOMAIN ) ) ; if ( 0 == strcasecmp ( $ sServerName , $ sRootDomain ) ) { $ nRet = self :: ENV_PRODUCTION ; } else if ( strstr ( $ sServerName , sprintf ( "-pre.%s" , $ sRootDomain ) ) ) { $ nRet = self :: ENV_PRE_PRODUCTION ; } else if ( strstr ( $ sServerName , sprintf ( "-dev.%s" , $ sRootDomain ) ) ) { $ nRet = self :: ENV_DEVELOPMENT ; } else if ( strstr ( $ sServerName , sprintf ( "-loc.%s" , $ sRootDomain ) ) ) { $ nRet = self :: ENV_LOCAL ; } else if ( strstr ( $ sServerName , sprintf ( "-test.%s" , $ sRootDomain ) ) ) { $ nRet = self :: ENV_TEST ; } else { $ sNeedle = sprintf ( ".%s" , $ sRootDomain ) ; $ nRightPos = strlen ( $ sServerName ) - strlen ( $ sNeedle ) - 1 ; $ nSearchPos = strrpos ( $ sServerName , $ sNeedle ) ; if ( $ nRightPos > 0 && $ nRightPos === $ nSearchPos ) { $ nRet = self :: ENV_PRODUCTION ; } } return $ nRet ; }
get environment type
2,324
static function IsSecureHttp ( ) { return ( CLib :: IsArrayWithKeys ( $ _SERVER , 'HTTPS' ) && CLib :: IsExistingString ( $ _SERVER [ 'HTTPS' ] ) && ( 0 == strcasecmp ( 'ON' , $ _SERVER [ 'HTTPS' ] ) || 0 == strcasecmp ( '1' , $ _SERVER [ 'HTTPS' ] ) ) ) ; }
detect if the protocol of current request is secure
2,325
public function setRadioAttribute ( $ a , $ v ) { foreach ( $ this -> radios as $ radio ) { $ radio -> setAttribute ( $ a , $ v ) ; if ( $ a == 'tabindex' ) { $ v ++ ; } } return $ this ; }
Set an attribute for the input radio elements
2,326
public function setRadioAttributes ( array $ a ) { foreach ( $ this -> radios as $ radio ) { $ radio -> setAttributes ( $ a ) ; if ( isset ( $ a [ 'tabindex' ] ) ) { $ a [ 'tabindex' ] ++ ; } } return $ this ; }
Set an attribute or attributes for the input radio elements
2,327
public function setValue ( $ value ) { $ this -> checked = $ value ; if ( ( null !== $ this -> checked ) && ( $ this -> hasChildren ( ) ) ) { foreach ( $ this -> childNodes as $ child ) { if ( $ child instanceof Input \ Radio ) { if ( $ child -> getValue ( ) == $ this -> checked ) { $ child -> check ( ) ; } else { $ child -> uncheck ( ) ; } } } } return $ this ; }
Set the checked value of the radio form elements
2,328
public static function buildBasedIntRegex ( $ base ) { assert ( 2 <= $ base && $ base <= 16 ) ; $ regex = '/(?i:[0-' ; if ( $ base <= 10 ) { $ regex .= ( string ) $ base - 1 ; } else { $ regex .= '9a-' . strtolower ( dechex ( $ base - 1 ) ) ; } $ regex .= '])+/' ; return $ regex ; }
in the given base
2,329
public function logPreProcedureEvent ( Events \ PreProcedureEvent $ event ) { $ procedure = $ event -> getProcedure ( ) ; $ this -> logger -> info ( sprintf ( 'Starting procedure "%s"...' , $ procedure -> getName ( ) ) ) ; }
Logs pre procedure event .
2,330
public function logPostProcedureEvent ( Events \ PostProcedureEvent $ event ) { $ procedure = $ event -> getProcedure ( ) ; $ this -> logger -> info ( sprintf ( 'Finished procedure "%s"' , $ procedure -> getName ( ) ) ) ; }
Logs post procedure event .
2,331
public function logPostAdapterReceiveEvent ( Events \ PostAdapterReceiveEvent $ event ) { $ source = $ event -> getSourceAdapter ( ) ; $ this -> logger -> info ( sprintf ( 'Received data from adapter "%s"' , get_class ( $ source ) ) ) ; }
Logs post adapter receive .
2,332
public function logPostWorkerEvent ( Events \ PostWorkerEvent $ event ) { $ worker = $ event -> getWorker ( ) ; $ this -> logger -> info ( sprintf ( 'Worked an object with "%s"' , get_class ( $ worker ) ) ) ; }
Logs post worker event .
2,333
public function logPostAdapterSendEvent ( Events \ PostAdapterSendEvent $ event ) { $ target = $ event -> getTargetAdapter ( ) ; $ this -> logger -> info ( sprintf ( 'Objects sent to adapter "%s"' , get_class ( $ target ) ) ) ; }
Logs post adapter send event .
2,334
public static function byOverWriting ( Collection $ collection , int $ index ) : NotAllowed { return new static ( sprintf ( 'Cannot write to the immutable collection `%s`. ' . '(Tried writing to position %d).' , get_class ( $ collection ) , $ index ) ) ; }
Indicates that this write operation is not allowed .
2,335
public static function byRemoving ( Collection $ collection , int $ index ) : NotAllowed { return new static ( sprintf ( 'Cannot alter the immutable collection `%s`. ' . '(Tried to unset position %d).' , get_class ( $ collection ) , $ index ) ) ; }
Indicates that this unset operation is not allowed .
2,336
public static function byResizingTo ( Collection $ collection , int $ size ) : NotAllowed { return new static ( sprintf ( 'Cannot directly resize the immutable collection `%s`. ' . '(Tried to resize from %d to %d).' , get_class ( $ collection ) , count ( $ collection ) , $ size ) ) ; }
Indicates that this resize operation is not allowed .
2,337
public function get_sizes ( $ size = '' ) { global $ _wp_additional_image_sizes ; $ sizes = array ( ) ; $ get_intermediate_image_sizes = get_intermediate_image_sizes ( ) ; foreach ( $ get_intermediate_image_sizes as $ _size ) { if ( in_array ( $ _size , array ( 'thumbnail' , 'medium' , 'large' ) ) ) { $ sizes [ $ _size ] [ 'width' ] = get_option ( $ _size . '_size_w' ) ; $ sizes [ $ _size ] [ 'height' ] = get_option ( $ _size . '_size_h' ) ; $ sizes [ $ _size ] [ 'crop' ] = ( bool ) get_option ( $ _size . '_crop' ) ; } elseif ( isset ( $ _wp_additional_image_sizes [ $ _size ] ) ) { $ sizes [ $ _size ] = array ( 'width' => $ _wp_additional_image_sizes [ $ _size ] [ 'width' ] , 'height' => $ _wp_additional_image_sizes [ $ _size ] [ 'height' ] , 'crop' => $ _wp_additional_image_sizes [ $ _size ] [ 'crop' ] , ) ; } } if ( $ size ) { if ( isset ( $ sizes [ $ size ] ) ) { return $ sizes [ $ size ] ; } else { return false ; } } return $ sizes ; }
Get all the currently defined named image sizes
2,338
public function addForumAssets ( ConfigureClientView $ event ) { if ( $ event -> isForum ( ) ) { $ event -> addAssets ( [ __DIR__ . '/../../js/forum/dist/extension.js' , ] ) ; $ event -> view -> addHeadString ( '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.5.1/katex.min.css">' ) ; $ event -> view -> addHeadString ( '<script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.5.1/katex.min.js"></script>' ) ; $ event -> view -> addHeadString ( '<script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.5.1/contrib/auto-render.min.js"></script>' ) ; $ event -> addBootstrapper ( 'flagrow/latex/main' ) ; } }
Modifies the client view for the Forum .
2,339
private function getDeviceForRequest ( Request \ GenericRequest $ request ) { Handlers \ Utils :: reset ( ) ; $ deviceId = $ this -> deviceIdForRequest ( $ request ) ; return $ this -> getWrappedDevice ( $ deviceId , $ request ) ; }
Returns the Device for the given \ Wurfl \ Request_GenericRequest
2,340
public function getDevice ( $ deviceId , Request \ GenericRequest $ request = null ) { if ( $ request !== null ) { if ( ! ( $ request instanceof GenericRequest ) ) { throw new \ InvalidArgumentException ( 'Error: Request parameter must be null or instance of WURFL_Request_GenericRequest' ) ; } $ generic_normalizer = UserAgentHandlerChainFactory :: createGenericNormalizers ( ) ; $ request -> setUserAgentNormalized ( $ generic_normalizer -> normalize ( $ request -> getUserAgent ( ) ) ) ; } return $ this -> getWrappedDevice ( $ deviceId , $ request ) ; }
Return a device for the given device id
2,341
public function getFallBackDevices ( $ deviceId ) { $ fallBackDevices = $ this -> getDeviceRepository ( ) -> getDeviceHierarchy ( $ deviceId ) ; array_shift ( $ fallBackDevices ) ; return array_map ( array ( $ this , 'deviceId' ) , $ fallBackDevices ) ; }
Returns an array of all the fall back devices starting from the given device
2,342
private function getWrappedDevice ( $ deviceId , Request \ GenericRequest $ request = null ) { $ modelDevices = $ this -> getCacheStorage ( ) -> load ( 'DEVS_' . $ deviceId ) ; if ( empty ( $ modelDevices ) ) { $ modelDevices = $ this -> getDeviceRepository ( ) -> getDeviceHierarchy ( $ deviceId ) ; } $ this -> getCacheStorage ( ) -> save ( 'DEVS_' . $ deviceId , $ modelDevices ) ; if ( $ request === null ) { $ requestFactory = new GenericRequestFactory ( ) ; $ request = $ requestFactory -> createRequestForUserAgent ( $ modelDevices [ 0 ] -> userAgent ) ; $ genericNormalizer = UserAgentHandlerChainFactory :: createGenericNormalizers ( ) ; $ request -> setUserAgentNormalized ( $ genericNormalizer -> normalize ( $ request -> getUserAgent ( ) ) ) ; } return new CustomDevice ( $ modelDevices , $ request ) ; }
Wraps the model device with \ Wurfl \ Xml \ ModelDeviceInterface . This function takes the Device ID and returns the \ Wurfl \ CustomDevice with all capabilities .
2,343
public function info ( $ message , array $ placeholders = [ ] , $ dismissible = true ) { $ this -> message ( $ message , null , $ placeholders , 'info' , $ dismissible ) ; return $ this ; }
Flash an info message .
2,344
public function success ( $ message , array $ placeholders = [ ] , $ dismissible = true ) { $ this -> message ( $ message , null , $ placeholders , 'success' , $ dismissible ) ; return $ this ; }
Flash a success message .
2,345
public function warning ( $ message , array $ placeholders = [ ] , $ dismissible = true ) { $ this -> message ( $ message , null , $ placeholders , 'warning' , $ dismissible ) ; return $ this ; }
Flash a warning message .
2,346
public function error ( $ message , array $ placeholders = [ ] , $ dismissible = true ) { $ this -> message ( $ message , null , $ placeholders , 'error' , $ dismissible ) ; return $ this ; }
Flash an error message .
2,347
private function getExistingFlashMessages ( ) { return $ this -> session -> has ( $ this -> sessionKey ) ? $ this -> session -> get ( $ this -> sessionKey ) : [ ] ; }
Get messages that have already been flashed .
2,348
private function getTranslation ( $ message , array $ placeholders ) { if ( $ this -> translator -> has ( $ message ) ) { $ message = $ this -> translator -> get ( $ message , $ placeholders ) ; } return $ message ; }
Get a translation for the message key or return the original message .
2,349
public static function currentServerName ( ) { if ( ! empty ( env ( 'SERVER_NAME' ) ) ) { $ BASE_URL = env ( 'SERVER_NAME' ) ; } elseif ( ! empty ( $ _SERVER [ 'SERVER_NAME' ] ) ) { $ BASE_URL = $ _SERVER [ 'SERVER_NAME' ] ; } elseif ( ! empty ( $ _SERVER [ 'HTTP_HOST' ] ) ) { $ BASE_URL = $ _SERVER [ 'HTTP_HOST' ] ; } else { $ BASE_URL = 'empty' ; } return $ BASE_URL ; }
Determine the current website server name .
2,350
public static function currentWebsiteData ( ) { static $ current_data ; $ BASE_URL = static :: currentServerName ( ) ; $ cache_key = 'website-data.' . $ BASE_URL ; if ( empty ( $ current_data ) ) { if ( Cache :: has ( $ cache_key ) ) { return Cache :: get ( $ cache_key ) ; } } if ( empty ( $ current_data ) ) { try { $ result = static :: whereRaw ( "INSTR('" . $ BASE_URL . "', `http_host`) > 0" ) -> orderBy ( DB :: raw ( 'LENGTH(`http_host`)' ) , 'desc' ) -> first ( ) ; if ( empty ( $ result ) ) { $ current_data = null ; } else { $ current_data = $ result -> toArray ( ) ; } Cache :: put ( $ cache_key , $ current_data , 60 ) ; } catch ( \ Exception $ e ) { $ current_data = null ; } } return $ current_data ; }
Determine the current website data .
2,351
protected function __before ( ServerRequestInterface $ request , array $ arguments ) { $ type_id_variable = $ this -> getTypeIdVariable ( ) ; if ( array_key_exists ( $ type_id_variable , $ arguments ) ) { $ this -> active_object = empty ( $ arguments [ $ type_id_variable ] ) ? null : $ this -> pool -> getById ( $ this -> getTypeClassName ( ) , $ arguments [ $ type_id_variable ] ) ; if ( empty ( $ this -> active_object ) ) { return new NotFoundStatusResponse ( ) ; } } return null ; }
Run before every action .
2,352
public function index ( ServerRequestInterface $ request ) { if ( $ this -> shouldCheckPermissions ( ) ) { $ authenticated_user = $ this -> getAuthenticatedUser ( $ request ) ; if ( ! $ this -> canList ( $ authenticated_user ) ) { return new ForbiddenStatusResponse ( ) ; } } $ collection_class = $ this -> getCollectionClassName ( ) ; $ collection = $ this -> $ collection_class ; if ( $ collection instanceof CollectionInterface ) { if ( $ collection -> isPaginated ( ) ) { return $ collection -> currentPage ( $ this -> getPageFromQueryParams ( $ request -> getQueryParams ( ) ) ) ; } else { return $ collection ; } } else { throw new CollectionNotFoundException ( get_class ( $ this ) , __FUNCTION__ , $ collection_class ) ; } }
Return a collection of type instances .
2,353
public function edit ( ServerRequestInterface $ request ) { if ( $ this -> isReadOnly ( ) ) { return new NotFoundStatusResponse ( ) ; } if ( $ this -> active_object && $ this -> active_object -> isLoaded ( ) ) { $ authenticated_user = $ this -> getAuthenticatedUser ( $ request ) ; if ( $ this -> shouldCheckPermissions ( ) && ! $ this -> canEdit ( $ this -> active_object , $ authenticated_user ) ) { return new ForbiddenStatusResponse ( ) ; } $ request_body = $ request -> getParsedBody ( ) ; if ( empty ( $ request_body ) ) { $ request_body = [ ] ; } if ( $ this -> requestBodyContainsProtectedFields ( $ this -> active_object , $ request_body ) ) { return new BadRequestStatusResponse ( ) ; } $ this -> cleanUpRequestBodyForEdit ( $ request_body , $ authenticated_user ) ; try { return $ this -> pool -> modify ( $ this -> active_object , $ request_body ) ; } catch ( ValidationException $ e ) { return $ e ; } } else { return new NotFoundStatusResponse ( ) ; } }
Update an existing type instance .
2,354
public function delete ( ServerRequestInterface $ request ) { if ( $ this -> isReadOnly ( ) ) { return new NotFoundStatusResponse ( ) ; } if ( $ this -> active_object && $ this -> active_object -> isLoaded ( ) ) { $ authenticated_user = $ this -> getAuthenticatedUser ( $ request ) ; if ( $ this -> shouldCheckPermissions ( ) && ! $ this -> canDelete ( $ this -> active_object , $ authenticated_user ) ) { return new ForbiddenStatusResponse ( ) ; } $ this -> active_object = $ this -> pool -> scrap ( $ this -> active_object ) ; if ( $ this -> active_object -> isNew ( ) ) { return [ 'single' => [ 'id' => $ this -> active_object -> getId ( ) ] , ] ; } else { return $ this -> active_object ; } } else { return new NotFoundStatusResponse ( ) ; } }
Drop an existing type instance .
2,355
protected function getPageFromQueryParams ( array $ query_params ) { $ page = 1 ; if ( isset ( $ query_params [ 'page' ] ) ) { $ page = ( integer ) $ query_params [ 'page' ] ; } return $ page < 1 ? 1 : $ page ; }
Return page from request query params .
2,356
protected function getTypeFromRequestBody ( array & $ request_body ) { $ type_class = $ this -> getTypeClassName ( ) ; if ( isset ( $ request_body [ 'type' ] ) ) { $ type_class = $ request_body [ 'type' ] ; unset ( $ request_body [ 'type' ] ) ; } if ( class_exists ( $ type_class ) ) { $ type_class_reflection = new ReflectionClass ( $ type_class ) ; if ( $ type_class_reflection -> isSubclassOf ( $ this -> getTypeClassName ( ) ) && ! $ type_class_reflection -> isAbstract ( ) ) { return $ type_class ; } } throw new InvalidArgumentException ( 'Please specify a valid type' ) ; }
Get a valid type class from request body .
2,357
protected function cleanUpRequestBodyForEdit ( array & $ request_body , UserInterface $ user = null ) { $ this -> cleanUpRequestBody ( $ request_body , $ user ) ; if ( $ this -> pool -> isTypePolymorph ( $ this -> getTypeClassName ( ) ) && array_key_exists ( 'type' , $ request_body ) ) { unset ( $ request_body [ 'type' ] ) ; } }
Perform request data clean - up before reqeust data is being used for edit action .
2,358
public function ask ( ) { $ this -> drawer -> open ( ) ; $ phkey = new Detector ( ) ; $ listener = $ phkey -> getListenerInstance ( ) ; $ event = $ listener -> getEventDispatcher ( ) ; $ event -> addListener ( 'key:up' , function ( ) { $ this -> cursor -> moveUp ( count ( $ this -> choices ) ) ; $ this -> draw ( ) ; } ) ; $ event -> addListener ( 'key:down' , function ( ) { $ this -> cursor -> moveDown ( count ( $ this -> choices ) ) ; $ this -> draw ( ) ; } ) ; $ event -> addListener ( 'key:space' , function ( ) { $ this -> selectChoice ( ) ; $ this -> draw ( ) ; } ) ; $ event -> addListener ( 'key:enter' , function ( ) use ( $ event ) { $ event -> dispatch ( 'key:stop:listening' ) ; $ this -> drawer -> closeWindow ( ) ; } ) ; $ this -> draw ( ) ; $ listener -> start ( ) ; return $ this -> getAnswers ( ) ; }
Asks the question
2,359
protected function draw ( ) { $ this -> drawer -> drawWindow ( $ this -> title , $ this -> choices , $ this -> cursor -> getPosition ( ) , $ this -> answers ) ; }
Draws the window
2,360
public function validate ( & $ uri , $ config , $ context ) { if ( $ this -> default_port == $ uri -> port ) $ uri -> port = null ; return true ; }
Validates the components of a URI
2,361
public function exportImage ( $ keep_resorce = false ) { $ this -> getCaptchaImage ( ) ; header ( 'content-type: image/png' ) ; imagepng ( $ this -> _final_image ) ; imagedestroy ( $ this -> _final_image ) ; }
send image to browser
2,362
public static function init ( $ blocks = 2 , $ block_min_length = 4 , $ block_max_length = 7 ) { if ( ! is_numeric ( $ blocks ) || ! is_numeric ( $ block_min_length ) || ! is_numeric ( $ block_max_length ) ) throw new CaptchaException ( __METHOD__ . ' arguments must be numeric values' ) ; if ( $ blocks < 1 || $ blocks > 5 ) throw new CaptchaException ( '__construct($blocks, , ) $blocks must be +ve integer and less than or equal 5.' ) ; if ( $ block_min_length < 1 || $ block_min_length > 20 ) throw new CaptchaException ( '__construct( , $block_min_length, ) $block_min_length must be +ve integer' ) ; if ( $ block_max_length < $ block_min_length || $ block_max_length > 100 ) throw new CaptchaException ( '__construct( , , $block_max_length ) $block_max_length must be +ve integer and greater than or equal to min_length and less than 100' ) ; $ code = '' ; $ pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ; for ( $ i = 1 ; $ i <= $ blocks ; $ i ++ ) { $ block_length = rand ( $ block_min_length , $ block_max_length ) ; $ code .= substr ( str_shuffle ( str_repeat ( $ pool , 5 ) ) , 0 , $ block_length - 1 ) ; $ code .= ( $ i >= $ blocks ) ? : ' ' ; } Session :: put ( 'captcha' , $ code ) ; }
This Method Will Generate a Capatcha Code and Store it in Session
2,363
private function calculateDimensions ( ) { $ this -> _calculated_text_box [ 'dimensions' ] = $ this -> getTextBoxDimensions ( $ this -> _background_text [ 'size' ] , 0 , $ this -> _background_text [ 'font' ] , $ this -> _code ) ; $ this -> _calculated_text_box [ 'char_width' ] = $ this -> _calculated_text_box [ 'dimensions' ] [ 'width' ] / $ this -> _code_length ; $ this -> _calculated_text_box [ 'additional_width' ] = $ this -> _calculated_text_box [ 'char_width' ] * $ this -> _code_length + $ this -> _blocks_seperation ; $ this -> _calculated_text_box [ 'additional_height' ] = rand ( 5 , 15 ) ; $ this -> _image_info [ 'width' ] = $ this -> _calculated_text_box [ 'dimensions' ] [ 'width' ] + $ this -> _calculated_text_box [ 'additional_width' ] ; $ this -> _image_info [ 'height' ] = $ this -> _calculated_text_box [ 'dimensions' ] [ 'height' ] + $ this -> _calculated_text_box [ 'additional_height' ] ; }
calculate required size of capatcha image
2,364
private function createCaptchaImage ( ) { $ this -> _image_resource = imagecreatetruecolor ( $ this -> _image_info [ 'width' ] , $ this -> _image_info [ 'height' ] ) ; if ( function_exists ( 'imageantialias' ) ) imageantialias ( $ this -> _image_resource , true ) ; $ rgb = $ this -> getRGBFromRange ( $ this -> _image_info [ 'color' ] [ 0 ] , $ this -> _image_info [ 'color' ] [ 1 ] , $ this -> _image_info [ 'color' ] [ 2 ] , $ this -> _image_info [ 'color' ] [ 'range' ] ) ; $ background_color = imagecolorallocate ( $ this -> _image_resource , $ rgb [ 0 ] , $ rgb [ 1 ] , $ rgb [ 2 ] ) ; imagefill ( $ this -> _image_resource , 0 , 0 , $ background_color ) ; }
create capatcha image resource
2,365
private function fixCaptchaImage ( ) { $ final_width = $ this -> _front_text [ 'x' ] + $ this -> _front_text [ 'initial_x' ] ; if ( $ this -> _image_info [ 'width' ] > $ final_width ) $ this -> _image_info [ 'width' ] = $ final_width ; $ this -> _final_image = imagecreatetruecolor ( $ this -> _image_info [ 'width' ] , $ this -> _image_info [ 'height' ] ) ; if ( function_exists ( 'imageantialias' ) ) imageantialias ( $ this -> _final_image , true ) ; imagecopy ( $ this -> _final_image , $ this -> _image_resource , 0 , 0 , 0 , 0 , $ this -> _image_info [ 'width' ] , $ this -> _image_info [ 'height' ] ) ; imagedestroy ( $ this -> _image_resource ) ; }
Fix Final Capatcha image Size if needed
2,366
public function setTextSize ( $ front , $ background = null ) { if ( ! is_numeric ( $ front ) ) throw new CaptchaException ( __METHOD__ . '($arg) must be numeric' ) ; if ( ! $ background ) { $ this -> _front_text [ 'size' ] = $ front ; $ this -> _background_text [ 'size' ] = $ front + 10 ; } else { if ( ! is_numeric ( $ background ) ) throw new CaptchaException ( __METHOD__ . '($arg) must be numeric' ) ; if ( $ front > $ background ) throw new CaptchaException ( __METHOD__ . '($front, $background) $background must be greater than or equal front' ) ; $ this -> _front_text [ 'size' ] = $ front ; $ this -> _background_text [ 'size' ] = $ background ; } return $ this ; }
Set Text Size
2,367
public function setColor ( $ key , $ r , $ g , $ b , $ alpha = 0 , $ range = 0 ) { if ( ! in_array ( $ key , array ( 'background' , 'background_text' , 'front_text' ) ) ) throw new CaptchaException ( __METHOD__ . '($key, ) must be one of( background, background_text, front_text ).' ) ; if ( ! is_numeric ( $ r ) || ! is_numeric ( $ g ) || ! is_numeric ( $ b ) || ! is_numeric ( $ alpha ) || ! is_numeric ( $ range ) ) throw new CaptchaException ( __METHOD__ . '( , $args ) second argument and the followers must be numeric values.' ) ; $ property = ( $ key == 'background' ) ? '_image_info' : '_' . $ key ; $ this -> { $ property } [ 'color' ] = array ( $ r , $ g , $ b , $ alpha ) ; $ this -> { $ property } [ 'color' ] [ 'range' ] = $ range ; return $ this ; }
Set Text Color
2,368
public function setFont ( $ key , $ font ) { if ( $ key != 'background_text' && $ key != 'front_text' ) throw new CaptchaException ( __METHOD__ . '($key, ) $key must be background_text or front_text.' ) ; $ font_file = Config :: get ( 'images.captcha.font_dir' ) . DIRECTORY_SEPARATOR . $ font ; if ( ! file_exists ( $ font_file ) ) throw new CaptchaException ( __METHOD__ . "( , $font) provided font file '$font_file' doesn't exists." ) ; $ property = '_' . $ key ; $ this -> { $ property } [ 'font' ] = $ font_file ; return $ this ; }
Set Captcha Font
2,369
public function asComplex ( ) { return new ComplexType ( new RationalType ( clone $ this -> numerator ( ) , clone $ this -> denominator ( ) ) , new RationalType ( new IntType ( 0 ) , new IntType ( 1 ) ) ) ; }
Return the number as a Complex number i . e . n + 0i
2,370
public function getAsNativeType ( ) { if ( $ this -> isInteger ( ) ) { return intval ( $ this -> value [ 'num' ] -> get ( ) ) ; } return floatval ( $ this -> value [ 'num' ] -> get ( ) / $ this -> value [ 'den' ] -> get ( ) ) ; }
Get the basic PHP value of the object type properly In this case the type is an int or float
2,371
public function normalize ( $ userAgent ) { if ( substr_count ( $ userAgent , ' ' ) === 0 and substr_count ( $ userAgent , '+' ) > 2 ) { $ userAgent = str_replace ( '+' , ' ' , $ userAgent ) ; } return $ userAgent ; }
This method clean the IIS logging from user agent string .
2,372
public function macroThumb ( MacroNode $ node , PhpWriter $ writer ) { if ( $ node -> modifiers ) { if ( Helpers :: removeFilter ( $ node -> modifiers , 'dataStream' ) ) { return $ writer -> write ( '$_fi=Thumbnail\\Thumbnail::getSrcPath(%node.word, %node.args); echo Latte\\Runtime\\Filters::dataStream(file_get_contents(__DIR__."/../../../".$_fi));' ) ; } throw new CompileException ( 'Modifiers are not allowed in ' . $ node -> getNotation ( ) ) ; } return $ writer -> write ( 'echo Thumbnail\\Thumbnail::getSrcPath(%node.word, %node.args)' ) ; }
Macro thumb .
2,373
public function prepareResponse ( ) : void { $ this -> response -> setStatusCode ( 200 ) ; $ this -> response -> resetHeaders ( ) ; $ this -> response -> setCharset ( 'UTF-8' ) ; $ this -> response -> setContentType ( 'text/html' ) ; $ this -> response -> addHeader ( 'X-Some-Header-Example-Name: headerValueExample' ) ; $ body = 'This is an example generated in Route <i>' . get_class ( $ this ) . '</i> with a fictive Controller.' ; $ this -> response -> setBody ( $ body ) ; }
Setup response headers and body by your controller or other logic .
2,374
protected function calculateResize ( AbstractImage $ abstractImage , $ width , $ height ) { if ( ! is_numeric ( $ width ) || ! is_numeric ( $ height ) ) { throw new \ LogicException ( 'Non numeric value provide for calculating resize!' ) ; } $ imageWidth = $ abstractImage -> getSize ( ) -> getWidth ( ) ; $ imageHeight = $ abstractImage -> getSize ( ) -> getHeight ( ) ; $ widthRatio = $ imageWidth / ( int ) $ width ; $ heightRatio = $ imageHeight / ( int ) $ height ; $ ratio = min ( $ widthRatio , $ heightRatio ) ; if ( $ ratio < 1 ) { throw new ImageTooSmallException ( 'Provided image is too small to be resize! Provide larger image.' ) ; } $ calcWidth = $ imageWidth / $ ratio ; $ calcHeight = $ imageHeight / $ ratio ; $ box = clone $ this -> box ; $ box -> setWidth ( round ( $ calcWidth ) ) -> setHeight ( round ( $ calcHeight ) ) ; return $ box ; }
Calculates image resize
2,375
protected function createCropPoint ( AbstractImage $ abstractImage , $ width , $ height ) { if ( ! is_numeric ( $ width ) || ! is_numeric ( $ height ) ) { throw new \ LogicException ( 'Provided values for width and height are not numeric!' ) ; } $ width = ( int ) $ width ; $ height = ( int ) $ height ; $ imageWidth = $ abstractImage -> getSize ( ) -> getWidth ( ) ; $ imageHeight = $ abstractImage -> getSize ( ) -> getHeight ( ) ; if ( $ imageWidth < $ width || $ imageHeight < $ height ) { throw new ImageTooSmallException ( 'Provided image is too small to be resize! Provide larger image.' ) ; } $ cropWidth = ( $ imageWidth / 2 ) - ( $ width / 2 ) ; $ cropHeight = ( $ imageHeight / 2 ) - ( $ height / 2 ) ; $ box = clone $ this -> box ; $ box -> setWidth ( round ( $ cropWidth ) ) -> setHeight ( round ( $ cropHeight ) ) ; $ this -> point -> setBox ( $ box ) ; return $ this -> point ; }
Creates crop point
2,376
public function isApplicable ( $ role ) { if ( isset ( $ this -> options [ 'roles' ] [ $ role ] ) ) { return ( bool ) ( int ) $ this -> options [ 'roles' ] [ $ role ] ; } return true ; }
Checks whether the widget is applicable to the role . This behavior differs from the ACL . Returns FALSE if and only if the widget is explicitly disabled for a given role .
2,377
protected function gmpTypeCheck ( $ value ) { if ( version_compare ( PHP_VERSION , '5.6.0' ) < 0 ) { return is_resource ( $ value ) && get_resource_type ( $ value ) == 'GMP integer' ; } return ( $ value instanceof \ GMP ) ; }
Check gmp type depending on PHP version
2,378
public function registerClientScript ( $ gCaptchaParams = [ ] ) { $ id = $ this -> id ; $ view = $ this -> view ; ReCaptchaAsset :: register ( $ view ) ; $ options = Json :: encode ( $ gCaptchaParams ) ; $ view -> registerJs ( <<<JSif (typeof (renderReCaptchaCallback) === "undefined") { var reCaptchaWidgets = {}; var renderReCaptchaCallback = function() { for (var widgetId in reCaptchaWidgets) { if (reCaptchaWidgets.hasOwnProperty(widgetId)) { grecaptcha.render(document.getElementById(widgetId), reCaptchaWidgets[widgetId]); } } };}JS , View :: POS_HEAD , 'renderReCaptchaCallbackFunction' ) ; $ view -> registerJs ( <<<JSreCaptchaWidgets.$id = $options;JS , View :: POS_HEAD ) ; }
Register google reCAPTCHA js api and custom render scripts
2,379
protected function instantiateService ( string $ id , array $ arguments ) { if ( isset ( $ this -> instances [ $ id ] ) ) { return $ this -> instances [ $ id ] ; } if ( isset ( $ this -> factories [ $ id ] ) ) { return ( $ this -> factories [ $ id ] ) ( $ arguments ) ; } if ( isset ( $ this -> callableDefinitions [ $ id ] ) ) { $ this -> factories [ $ id ] = $ this -> createServiceFactoryFromCallable ( $ this -> callableDefinitions [ $ id ] ) ; return $ this -> invokeFactory ( $ id , $ arguments ) ; } $ class = $ this -> classDefinitions [ $ id ] ?? $ id ; if ( $ class !== $ id ) { return $ this -> saveShared ( $ id , $ this -> instantiateService ( $ class , $ arguments ) ) ; } if ( ! class_exists ( $ class ) ) { throw new NotFoundException ( $ id , $ this -> resolving ) ; } $ this -> factories [ $ id ] = $ this -> createServiceFactoryFromClass ( $ class ) ; return $ this -> invokeFactory ( $ id , $ arguments ) ; }
Create callable factory for the subject service .
2,380
protected function isResolvableService ( string $ id ) : bool { return isset ( $ this -> keys [ $ id ] ) || class_exists ( $ id ) ; }
Check if container can resolve the service with subject identifier .
2,381
protected function resolving ( string $ id ) { if ( isset ( $ this -> resolving [ $ id ] ) ) { throw new CircularReferenceException ( $ id , $ this -> resolving ) ; } $ this -> resolving [ $ id ] = $ id ; }
Detects circular references .
2,382
private function createServiceFactoryFromCallable ( Invokable $ invokable ) : Closure { return function ( array $ arguments = [ ] ) use ( $ invokable ) { return $ this -> invoker -> invoke ( $ invokable , $ arguments ) ; } ; }
Create callable factory with resolved arguments from callable .
2,383
private function createServiceFactoryFromClass ( string $ class ) : Closure { $ reflection = new ReflectionClass ( $ class ) ; if ( ! $ reflection -> isInstantiable ( ) ) { throw new UninstantiableServiceException ( $ class , $ this -> resolving ) ; } $ constructor = $ reflection -> getConstructor ( ) ; if ( $ constructor && $ constructor -> getNumberOfParameters ( ) > 0 ) { if ( $ constructor -> getDeclaringClass ( ) !== $ class ) { $ invokable = new Invokable ( [ $ class , '__construct' ] ) ; } else { $ invokable = new Invokable ( $ constructor ) ; } return function ( array $ arguments = [ ] ) use ( $ invokable ) { return $ this -> invoker -> invoke ( $ invokable , $ arguments ) ; } ; } return function ( ) use ( $ class ) { return new $ class ( ) ; } ; }
Create callable factory with resolved arguments from class name .
2,384
public function actionIndex ( ) { $ searchModel = new CustomerSearch ( ) ; $ dataProvider = $ searchModel -> search ( Yii :: $ app -> request -> queryParams ) ; return $ this -> render ( 'index' , [ 'searchModel' => $ searchModel , 'dataProvider' => $ dataProvider , ] ) ; }
Lists all Customer models .
2,385
protected function normalizePath ( $ value ) { if ( is_array ( $ value ) ) { foreach ( $ value as $ i => $ val ) { $ value [ $ i ] = $ this -> normalizePath ( $ val ) ; } return $ value ; } $ converter = new PathConverter ( dirname ( $ this -> config [ 'config_path' ] ) , $ this -> config [ 'path' ] ) ; return $ converter -> convert ( $ value ) ; }
Normalize all relative paths by prefixing them with the project path .
2,386
protected function copyCollectionWith ( Collection $ collection , array $ values ) { $ collection = clone $ collection ; $ collection -> exchangeArray ( $ values ) ; return $ collection ; }
Get a copy of a collection with new values .
2,387
public function update ( Request $ request ) { $ user = $ request -> user ( ) ; $ this -> validate ( $ request , [ 'name' => 'required' , 'email' => 'required|email|unique:users,email,' . $ user -> id , ] ) ; return tap ( $ user ) -> update ( $ request -> only ( 'name' , 'email' ) ) ; }
Update the user s profile information .
2,388
public static function storageById ( $ id ) { $ handlers = self :: storageHandlers ( ) ; if ( isset ( $ handlers [ $ id ] ) ) { return $ handlers [ $ id ] ; } else { throw new ServerErrorHttpException ( "Storage handler with id $id not found." ) ; } }
Returns AbstractPropertyStorage instance by PropertyStorage . id
2,389
public static function storageIdByClass ( $ className ) { foreach ( self :: storageHandlers ( ) as $ id => $ handler ) { if ( $ handler instanceof $ className ) { return $ id ; } } return null ; }
Return a property storage id by storage class name .
2,390
public function collectAction ( ) { $ service = $ this -> getGarbageCollector ( ) ; if ( $ service -> collect ( ) ) { return $ this -> redirect ( ) -> toRoute ( 'sc-admin/content-manager' ) ; } return $ this -> redirect ( ) -> toRoute ( 'sc-admin/file/delete' , [ 'random' => Stdlib :: randomKey ( 6 ) ] ) -> setStatusCode ( 303 ) ; }
Collects garbage - removes files from the file system .
2,391
public function auth ( $ provider_name , & $ profile = null ) { $ identifier = null ; try { $ provider = $ this -> hybrid_auth -> authenticate ( $ provider_name ) ; $ userProfile = $ provider -> getUserProfile ( ) ; $ identifier = $ userProfile -> identifier ; $ profile = $ userProfile ; } catch ( \ Exception $ e ) { dd ( $ e -> getMessage ( ) ) ; } return $ identifier ; }
Prompt the User to authenticate with a social - auth provider
2,392
public function attach ( $ provider_name ) { $ response = null ; $ profile = null ; $ identifier = $ this -> auth ( $ provider_name , $ profile ) ; if ( ! $ this -> checkRegistered ( $ provider_name , $ identifier ) ) { $ id = Auth :: user ( ) -> getAuthIdentifier ( ) ; $ login = $ this -> login_repository -> create ( ) ; $ login -> setProvider ( $ provider_name ) ; $ login -> setIdentifier ( $ identifier ) ; $ login -> setUser ( $ id ) ; if ( $ this -> login_repository -> save ( $ login ) ) { $ providers = SocialAuth :: getConnectedProviders ( ) ; $ socialProfile = $ providers [ $ provider_name ] -> getProfile ( ) ; Event :: fire ( 'social-auth.attach' , [ 'user' => Auth :: user ( ) , 'provider' => $ provider_name , 'profile' => $ socialProfile ] ) ; $ response = Redirect :: back ( ) -> with ( [ 'message' => trans ( 'social-auth::user.account attach success' , [ 'provider' => $ provider_name , 'accountname' => $ socialProfile -> getDisplayName ( ) ] ) ] ) ; } else { $ response = Redirect :: back ( ) -> withErrors ( [ 'message' => trans ( 'social-auth::user.account attach fail' , [ 'accoutnname' => $ profile -> displayName ] ) ] ) ; } } else { $ response = Redirect :: back ( ) -> withErrors ( [ 'message' => trans ( 'social-auth::user.account already registered' , [ 'accountname' => $ profile -> displayName ] ) ] ) ; } return $ response ; }
Attempt to login to a social - auth provider If successful attach the social - auth user to the currently logged in user on this system
2,393
public function register ( $ provider_name ) { $ response = null ; $ profile = null ; $ route = Config :: get ( 'social-auth::register_route' ) ; $ identifier = $ this -> auth ( $ provider_name , $ profile ) ; if ( ! $ this -> checkRegistered ( $ provider_name , $ identifier ) ) { $ register_info = App :: make ( 'Ipunkt\SocialAuth\RegisterInfo' ) ; $ register_info -> setProvider ( $ provider_name ) ; SocialAuth :: setRegistration ( $ register_info ) ; $ response = Redirect :: route ( $ route ) ; } else { $ response = Redirect :: route ( $ route ) -> withErrors ( [ 'message' => trans ( 'social-auth::user.account already registered' , [ 'accountname' => $ profile -> displayName ] ) , [ 'accountname' => $ profile -> displayName ] ] ) ; } return $ response ; }
Login into a social - auth account intending to register a new user with it It is considered successful if the user logs into the social - auth account and the account is not yet attached to a different Account on this system .
2,394
public static function isURL ( string $ url ) : bool { return ( boolean ) ! ( filter_var ( $ url , FILTER_SANITIZE_URL | FILTER_VALIDATE_URL ) === false ) ; }
Valid if current provided string is an URL
2,395
public function filter ( $ filters ) { $ filtered = [ ] ; foreach ( $ this -> objectArr as $ obj ) { $ success = true ; foreach ( $ filters as $ prop => $ value ) { if ( $ obj -> $ prop !== $ value ) { $ success = false ; break ; } } if ( $ success ) { $ filtered [ ] = $ obj ; } } return $ filtered ; }
Gets an array of matching items according to the array of filters provided . Filters are key - value pairs that are ANDed together i . e . returned items match all the criteria
2,396
public function get ( $ filters ) { $ matches = $ this -> filter ( $ filters ) ; $ n = count ( $ matches ) ; if ( $ n == 0 ) { $ msg = "No " . $ this -> objectClass . " found matching " . json_encode ( $ filters ) ; throw new Exceptions \ ObjectDoesNotExistException ( $ msg ) ; } elseif ( $ n > 1 ) { $ msg = "Multiple " . $ this -> objectClass . " objects ($n) found matching " . json_encode ( $ filters ) ; throw new Exceptions \ MultipleObjectsReturnedException ( $ msg ) ; } return $ matches [ 0 ] ; }
Gets a single matching item according to the array of filters provided . Filters are key - value pairs that are ANDed together i . e . returned items match all the criteria . If more or less than one item matches an exception is thrown
2,397
protected function setResource ( $ i , $ data ) { $ this -> resources [ $ i ] = new static :: $ resourceClass ( $ this -> client , $ this -> parent , $ data ) ; }
Initialize and add a resource to the collection
2,398
public function getNormalizer ( $ data_type ) { if ( ! isset ( $ this -> _normalizers [ $ data_type ] ) ) { $ message = 'Normalizer not attached for data type: ' . $ data_type ; throw new \ InvalidArgumentException ( $ message ) ; } return $ this -> _normalizers [ $ data_type ] ; }
Returns a mormalizer that is applied to fields of the given data type .
2,399
public function get ( $ resource , $ query = array ( ) ) { $ url = $ this -> baseUrl . $ resource ; if ( count ( $ query ) > 0 ) { $ url .= "?" ; } foreach ( $ query as $ key => $ value ) { $ url .= "$key=$value&" ; } $ headers = array ( "Authorization" => $ this -> auth -> getCredential ( ) ) ; try { $ response = $ this -> browser -> get ( $ url , $ headers ) ; } catch ( \ Buzz \ Exception \ ClientException $ e ) { throw new RequestException ( $ e -> getMessage ( ) ) ; } if ( $ this -> browser -> getLastResponse ( ) -> getStatusCode ( ) > 299 ) { throw new RequestException ( json_decode ( $ this -> browser -> getLastResponse ( ) -> getContent ( ) , true ) ) ; } return json_decode ( $ response -> getContent ( ) , true ) ; }
Common get request for all API calls