idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
100
public function get ( ) { $ modelResult = $ this -> getRequest ( ) -> request ( 'GET' , $ this -> getRequestUrl ( 'models' ) ) ; return $ this -> getModelsFromResult ( $ modelResult ) ; }
Gets All Models
101
public function getById ( $ id ) { $ modelResult = $ this -> getRequest ( ) -> request ( 'GET' , $ this -> getRequestUrl ( sprintf ( 'models/%s' , $ id ) ) ) ; return $ this -> getModelFromResult ( $ modelResult ) ; }
Gets Model By Id
102
public function getModelVersions ( $ id ) { $ modelResult = $ this -> getRequest ( ) -> request ( 'GET' , $ this -> getRequestUrl ( sprintf ( 'models/%s/versions' , $ id ) ) ) ; if ( ! isset ( $ modelResult [ 'model_versions' ] ) ) { throw new \ Exception ( 'Model Versions Not Found' ) ; } $ modelVersions = [ ] ; foreach ( $ modelResult [ 'model_versions' ] as $ version ) { $ modelVersion = new ModelVersion ( $ version ) ; $ modelVersions [ ] = $ modelVersion ; } return $ modelVersions ; }
Gets Model Versions
103
public function getModelVersionById ( $ modelId , $ versionId ) { $ modelResult = $ this -> getRequest ( ) -> request ( 'GET' , $ this -> getRequestUrl ( sprintf ( 'models/%s/versions/%s' , $ modelId , $ versionId ) ) ) ; if ( isset ( $ modelResult [ 'model_version' ] ) ) { $ modelVersion = new ModelVersion ( $ modelResult [ 'model_version' ] ) ; } else { throw new \ Exception ( 'Model Versions Not Found' ) ; } return $ modelVersion ; }
Gets Model Version By Id
104
public function updateModelConcepts ( array $ modelsArray , $ action ) { $ data [ 'models' ] = [ ] ; foreach ( $ modelsArray as $ modelId => $ modelConcepts ) { $ model = [ ] ; $ model [ 'id' ] = ( string ) $ modelId ; $ model [ 'output_info' ] = [ ] ; $ model [ 'output_info' ] [ 'data' ] = [ ] ; $ model [ 'output_info' ] [ 'data' ] = $ this -> addModelConcepts ( $ model [ 'output_info' ] [ 'data' ] , $ modelConcepts ) ; $ data [ 'models' ] [ ] = $ model ; } $ data [ 'action' ] = $ action ; $ updateResult = $ this -> getRequest ( ) -> request ( 'PATCH' , $ this -> getRequestUrl ( 'models' ) , $ data ) ; return $ this -> getModelsFromResult ( $ updateResult ) ; }
Common Model s Concepts Update Method
105
public function getModelsFromResult ( $ modelResult ) { $ modelsArray = [ ] ; if ( isset ( $ modelResult [ 'models' ] ) ) { foreach ( $ modelResult [ 'models' ] as $ model ) { $ model = new Model ( $ model ) ; $ modelsArray [ ] = $ model ; } } else { throw new \ Exception ( 'Models Not Found' ) ; } return $ modelsArray ; }
Parses Request Result and gets Models
106
public function addModelConcepts ( array $ data , array $ concepts ) { $ data [ 'concepts' ] = [ ] ; foreach ( $ concepts as $ concept ) { $ data [ 'concepts' ] [ ] = [ 'id' => $ concept -> getId ( ) , ] ; } return $ data ; }
Adds Model s Concepts to Model s Data
107
public function deleteById ( string $ modelId ) { $ deleteResult = $ this -> getRequest ( ) -> request ( 'DELETE' , $ this -> getRequestUrl ( sprintf ( 'models/%s' , $ modelId ) ) ) ; return $ deleteResult [ 'status' ] ; }
Delete Model By Id
108
public function deleteVersionById ( string $ modelId , string $ versionId ) { $ deleteResult = $ this -> getRequest ( ) -> request ( 'DELETE' , $ this -> getRequestUrl ( sprintf ( 'models/%s/versions/%s' , $ modelId , $ versionId ) ) ) ; return $ deleteResult [ 'status' ] ; }
Delete Model Version By Id
109
public function searchByNameAndType ( $ name = null , $ type = null ) { $ searchResult = $ this -> getRequest ( ) -> request ( 'POST' , $ this -> getRequestUrl ( 'models/searches' ) , [ 'model_query' => [ 'name' => $ name , 'type' => $ type , ] , ] ) ; return $ this -> getModelsFromResult ( $ searchResult ) ; }
Searches Models by It s name and type
110
public function setString ( $ context , $ text , $ plural = '' ) { $ this -> context = ( string ) $ context ; $ this -> text = ( string ) $ text ; $ this -> plural = ( string ) $ plural ; $ this -> hash = md5 ( $ this -> plural ? $ this -> context . "\004" . $ this -> text . "\005" . $ this -> plural : $ this -> context . "\004" . $ this -> text ) ; }
Set the translatable text .
111
protected function innerSet ( $ key , $ val ) { $ setMethod = 'set' . ucfirst ( $ key ) ; if ( ! in_array ( $ key , $ this -> notsetters ( ) ) && method_exists ( $ this , $ setMethod ) ) { $ this -> $ setMethod ( $ val ) ; } else { $ validateMethod = 'validate' . ucfirst ( $ key ) ; if ( method_exists ( $ this , $ validateMethod ) ) { $ errors = new Exceptions ( ) ; try { $ validateResult = $ this -> $ validateMethod ( $ val ) ; if ( false === $ validateResult ) { return ; } if ( $ validateResult instanceof \ Generator ) { foreach ( $ validateResult as $ error ) { if ( $ error instanceof \ Throwable ) { $ errors -> add ( $ error ) ; } } } } catch ( \ Throwable $ e ) { $ errors -> add ( $ e ) ; } if ( ! $ errors -> empty ( ) ) { throw $ errors ; } } $ sanitizeMethod = 'sanitize' . ucfirst ( $ key ) ; if ( method_exists ( $ this , $ sanitizeMethod ) ) { $ val = $ this -> $ sanitizeMethod ( $ val ) ; } if ( null === $ key ) { $ this -> __data [ ] = $ val ; } else { $ this -> __data [ $ key ] = $ val ; } } }
This method is reloaded for on - set validation and sanitizing
112
protected function buildRedirectRequest ( RequestInterface $ request , UriInterface $ uri , $ statusCode ) { $ request = $ request -> withUri ( $ uri ) ; if ( false !== $ this -> redirectCodes [ $ statusCode ] [ 'switch' ] && ! in_array ( $ request -> getMethod ( ) , $ this -> redirectCodes [ $ statusCode ] [ 'switch' ] [ 'unless' ] ) ) { $ request = $ request -> withMethod ( $ this -> redirectCodes [ $ statusCode ] [ 'switch' ] [ 'to' ] ) ; } if ( is_array ( $ this -> preserveHeader ) ) { $ headers = array_keys ( $ request -> getHeaders ( ) ) ; foreach ( $ headers as $ name ) { if ( ! in_array ( $ name , $ this -> preserveHeader ) ) { $ request = $ request -> withoutHeader ( $ name ) ; } } } return $ request ; }
Builds the redirect request .
113
private function createUri ( ResponseInterface $ response , RequestInterface $ request ) { if ( $ this -> redirectCodes [ $ response -> getStatusCode ( ) ] [ 'multiple' ] && ( ! $ this -> useDefaultForMultiple || ! $ response -> hasHeader ( 'Location' ) ) ) { throw new MultipleRedirectionException ( 'Cannot choose a redirection' , $ request , $ response ) ; } if ( ! $ response -> hasHeader ( 'Location' ) ) { throw new HttpException ( 'Redirect status code, but no location header present in the response' , $ request , $ response ) ; } $ location = $ response -> getHeaderLine ( 'Location' ) ; $ parsedLocation = parse_url ( $ location ) ; if ( false === $ parsedLocation ) { throw new HttpException ( sprintf ( 'Location %s could not be parsed' , $ location ) , $ request , $ response ) ; } $ uri = $ request -> getUri ( ) ; if ( array_key_exists ( 'scheme' , $ parsedLocation ) ) { $ uri = $ uri -> withScheme ( $ parsedLocation [ 'scheme' ] ) ; } if ( array_key_exists ( 'host' , $ parsedLocation ) ) { $ uri = $ uri -> withHost ( $ parsedLocation [ 'host' ] ) ; } if ( array_key_exists ( 'port' , $ parsedLocation ) ) { $ uri = $ uri -> withPort ( $ parsedLocation [ 'port' ] ) ; } if ( array_key_exists ( 'path' , $ parsedLocation ) ) { $ uri = $ uri -> withPath ( $ parsedLocation [ 'path' ] ) ; } if ( array_key_exists ( 'query' , $ parsedLocation ) ) { $ uri = $ uri -> withQuery ( $ parsedLocation [ 'query' ] ) ; } else { $ uri = $ uri -> withQuery ( '' ) ; } if ( array_key_exists ( 'fragment' , $ parsedLocation ) ) { $ uri = $ uri -> withFragment ( $ parsedLocation [ 'fragment' ] ) ; } else { $ uri = $ uri -> withFragment ( '' ) ; } return $ uri ; }
Creates a new Uri from the old request and the location header .
114
public function invalidateResourceIndex ( FilterInterface $ filter = null ) { $ this -> cache -> deleteItem ( $ this -> getResourceIndexKey ( $ filter ) ) ; }
Invalidates the cached resource index
115
public function invalidateResource ( $ sourcePath , $ version = null ) { $ this -> cache -> deleteItem ( $ this -> getResourceKey ( $ sourcePath , $ version ) ) ; }
Invalidates a cached resource
116
public function invalidateResourceCollection ( $ version = null , FilterInterface $ filter = null ) { $ this -> cache -> deleteItem ( $ this -> getResourceCollectionKey ( $ version , $ filter ) ) ; }
Invalidates the cached resource collection
117
protected function materializeResource ( Resource $ resource ) { foreach ( $ resource as $ method ) { $ request = $ method -> getRequest ( ) ; if ( $ request ) { $ method -> setRequest ( new Schema ( $ request -> getDefinition ( ) ) ) ; } $ responses = $ method -> getResponses ( ) ; foreach ( $ responses as $ statusCode => $ response ) { $ method -> addResponse ( $ statusCode , new Schema ( $ response -> getDefinition ( ) ) ) ; } } }
A resource can contain schema definitions which are only resolved if we actual call the getDefinition method i . e . the schema is stored in a database . So before we cache the documentation we must get the actual definition object which we can serialize
118
protected function transformResponseToException ( RequestInterface $ request , ResponseInterface $ response ) { if ( $ response -> getStatusCode ( ) >= 400 && $ response -> getStatusCode ( ) < 500 ) { throw new ClientErrorException ( $ response -> getReasonPhrase ( ) , $ request , $ response ) ; } if ( $ response -> getStatusCode ( ) >= 500 && $ response -> getStatusCode ( ) < 600 ) { throw new ServerErrorException ( $ response -> getReasonPhrase ( ) , $ request , $ response ) ; } return $ response ; }
Transform response to an error if possible .
119
public function setRawConcepts ( array $ rawConcepts ) { $ concepts = [ ] ; foreach ( $ rawConcepts as $ rawConcept ) { $ concept = new Concept ( $ rawConcept ) ; $ concepts [ ] = $ concept ; } $ this -> concepts = $ concepts ; return $ this ; }
Sets concepts from Raw Data
120
public function generateRawData ( ) { $ rawData = [ 'id' => $ this -> getId ( ) ] ; $ rawData [ 'output_info' ] = [ ] ; $ rawData [ 'output_info' ] [ 'data' ] = [ ] ; if ( $ this -> getName ( ) ) { $ rawData [ 'name' ] = $ this -> getName ( ) ; } if ( $ this -> getAppId ( ) ) { $ rawData [ 'app_id' ] = $ this -> getAppId ( ) ; } if ( $ this -> getCreatedAt ( ) ) { $ rawData [ 'created_at' ] = $ this -> getCreatedAt ( ) ; } if ( $ this -> getConcepts ( ) ) { $ rawData [ 'output_info' ] [ 'data' ] [ 'concepts' ] = [ ] ; foreach ( $ this -> getConcepts ( ) as $ concept ) { $ rawData [ 'output_info' ] [ 'data' ] [ 'concepts' ] [ ] = $ concept -> generateRawData ( ) ; } } if ( $ this -> isConceptsMutuallyExclusive ( ) || $ this -> isClosedEnvironment ( ) ) { $ rawData [ 'output_info' ] [ 'output_config' ] = $ this -> getOutputConfig ( ) ; } if ( $ this -> getModelVersion ( ) ) { $ rawData [ 'model_version' ] = $ this -> getModelVersion ( ) -> generateRawData ( ) ; } return $ rawData ; }
Generates rawData from Model
121
public function getPercentage ( $ round = true ) { if ( $ this -> translated === 0 || $ this -> total === 0 ) { $ result = $ round ? 0 : 0.0 ; } elseif ( $ this -> translated === $ this -> total ) { $ result = $ round ? 100 : 100.0 ; } else { $ result = $ this -> translated * 100.0 / $ this -> total ; if ( $ round ) { $ result = max ( 1 , min ( 99 , ( int ) round ( $ result ) ) ) ; } } return $ result ; }
Get the translation percentage .
122
public static function getTypesInfo ( ) { $ locale = Localization :: activeLocale ( ) ; if ( ! isset ( self :: $ typesInfo [ $ locale ] ) ) { $ list = [ self :: ADJECTIVE => [ 'name' => tc ( 'TermType' , 'Adjective' ) , 'short' => tc ( 'TermType_short' , 'adj.' ) , 'description' => t ( 'A word that describes a noun or pronoun (examples: big, happy, obvious).' ) , ] , self :: ADVERB => [ 'name' => tc ( 'TermType' , 'Adverb' ) , 'short' => tc ( 'TermType_short' , 'adv.' ) , 'description' => t ( 'A word that describes or gives more information about a verb, adjective or other adverb (examples: carefully, quickly, very).' ) , ] , self :: CONJUNCTION => [ 'name' => tc ( 'TermType' , 'Conjunction' ) , 'short' => tc ( 'TermType_short' , 'conj.' ) , 'description' => t ( 'A word that connects words, phrases, and clauses in a sentence (examples: and, but, while, although).' ) , ] , self :: INTERJECTION => [ 'name' => tc ( 'TermType' , 'Interjection' ) , 'short' => tc ( 'TermType_short' , 'interj.' ) , 'description' => t ( 'A word that is used to show a short sudden expression of emotion (examples: Bye!, Cheers!, Goodbye!, Hi!, Hooray!).' ) , ] , self :: NOUN => [ 'name' => tc ( 'TermType' , 'Noun' ) , 'short' => tc ( 'TermType_short' , 'n.' ) , 'description' => t ( 'A word that refers to a person, place, thing, event, substance, or quality (examples: Andrew, house, pencil, table).' ) , ] , self :: PREPOSITION => [ 'name' => tc ( 'TermType' , 'Preposition' ) , 'short' => tc ( 'TermType_short' , 'prep.' ) , 'description' => t ( 'A word that is used before a noun, a noun phrase, or a pronoun, connecting it to another word (examples: at, for, in, on, under).' ) , ] , self :: PRONOUN => [ 'name' => tc ( 'TermType' , 'Pronoun' ) , 'short' => tc ( 'TermType_short' , 'pron.' ) , 'description' => t ( 'A word that is used instead of a noun or a noun phrase (examples: I, me, mine, myself).' ) , ] , self :: VERB => [ 'name' => tc ( 'TermType' , 'Verb' ) , 'short' => tc ( 'TermType_short' , 'v.' ) , 'description' => t ( 'A word or phrase that describes an action, condition, or experience (examples: listen, read, write).' ) , ] , ] ; $ comparer = new Comparer ( $ locale ) ; uasort ( $ list , function ( array $ a , array $ b ) use ( $ comparer ) { return $ comparer -> compare ( $ a [ 'name' ] , $ b [ 'name' ] ) ; } ) ; self :: $ typesInfo [ $ locale ] = $ list ; } return self :: $ typesInfo [ $ locale ] ; }
Get all the allowed type names short names and descriptions .
123
public static function isValidType ( $ type ) { if ( $ type === '' ) { $ result = true ; } else { $ valid = self :: getTypesInfo ( ) ; $ result = isset ( $ valid [ $ type ] ) ; } return $ result ; }
Check if a term type is valid .
124
private function lintDir ( $ dir ) { $ finder = Finder :: create ( ) ; $ finder -> files ( ) -> in ( $ dir ) ; $ patterns = $ this -> input -> getOption ( self :: OPTION_PATTERN ) ; if ( ! empty ( $ patterns ) ) { $ patterns = explode ( ',' , $ patterns ) ; foreach ( $ patterns as $ pattern ) { $ finder -> name ( trim ( $ pattern ) ) ; } } else { $ finder -> name ( '*.xml.dist' ) -> name ( '*.xml' ) ; } if ( ! $ this -> input -> getOption ( self :: OPTION_RECURSIVE ) ) { $ finder -> depth ( 0 ) ; } if ( $ this -> input -> hasOption ( self :: OPTION_EXCLUDE ) ) { $ exclude = explode ( ',' , $ this -> input -> getOption ( self :: OPTION_EXCLUDE ) ) ; $ finder -> exclude ( $ exclude ) ; } $ totalFiles = $ finder -> count ( ) ; $ counter = 0 ; $ ret = true ; foreach ( $ finder as $ file ) { $ ret = $ this -> lintFile ( $ file ) && $ ret ; if ( 0 == ++ $ counter % 30 ) { $ this -> output -> writeln ( sprintf ( ' %8d/%d %6.2f%%' , $ counter , $ totalFiles , $ counter / $ totalFiles * 100 ) ) ; } } return $ ret ; }
lint the content of a directory recursive if defined .
125
private function printReportsOfFilesWithProblems ( ) { $ this -> output -> writeln ( PHP_EOL . '<error>errors:</error>' ) ; foreach ( $ this -> reports as $ report ) { if ( false === $ report -> hasProblems ( ) ) { continue ; } $ file = $ report -> getFile ( ) ; $ this -> output -> writeln ( 'file: ' . $ file -> getPath ( ) . DIRECTORY_SEPARATOR . $ file -> getFilename ( ) ) ; foreach ( $ report -> getProblems ( ) as $ problem ) { $ this -> output -> write ( ' > ' . $ problem -> getMessage ( ) . PHP_EOL ) ; } $ this -> output -> write ( ' - - ' . PHP_EOL ) ; } }
format and print the errors from the queue to the output .
126
private function lintFile ( \ SplFileInfo $ file ) { if ( $ this -> output -> getVerbosity ( ) >= OutputInterface :: VERBOSITY_VERBOSE ) { $ this -> output -> write ( 'lint file ' . $ file . ' ... ' ) ; } $ report = FileReport :: create ( $ file ) ; $ this -> reports [ ] = $ report ; $ status = $ this -> validator -> validateFile ( $ report ) ; if ( $ this -> output -> getVerbosity ( ) >= OutputInterface :: VERBOSITY_VERBOSE ) { if ( false === $ status ) { $ this -> output -> writeln ( '<error>errors</error>' ) ; } else { $ this -> output -> writeln ( '<info>passed.</info>' ) ; } } else { if ( false === $ status ) { $ this -> output -> write ( '<error>F</error>' ) ; } else { $ this -> output -> write ( '.' ) ; } } return $ status ; }
lint a file pass errors to the queue .
127
public function getIdentify ( $ email , $ name = '' , $ properties = [ ] ) { if ( ! $ email ) { throw new InvalidArgumentException ( 'E-mail cannot be empty or null' ) ; } $ props = [ PayloadProperties :: EMAIL => Encryption :: decode ( $ email ) ] ; if ( $ name ) { $ props [ PayloadProperties :: NAME ] = $ name ; } if ( $ properties ) { $ props [ PayloadProperties :: PROPERTIES ] = $ properties ; } return $ this -> getTrackPayload ( ActionTypes :: IDENTIFY , $ props ) ; }
Generates payload for identify events
128
public function getPageView ( $ url , $ properties = [ ] ) { if ( empty ( $ url ) ) { throw new Exception ( 'url cannot be empty' ) ; } $ props = [ PayloadProperties :: URL => $ url ] ; if ( $ properties ) { $ props [ PayloadProperties :: PROPERTIES ] = $ properties ; } return $ this -> getTrackPayload ( ActionTypes :: PAGE_VIEWED , $ props ) ; }
Generates payload for page view events
129
public function getAddToOrder ( Models \ Product $ product ) { return $ this -> getTrackPayload ( ActionTypes :: ADDED_TO_ORDER , [ PayloadProperties :: PROPERTIES => [ [ PayloadProperties :: PRODUCT => $ product -> toArray ( ) ] ] ] ) ; }
Generates payload for add to order events
130
public function getOrderCompleted ( Models \ Order $ order ) { if ( ! $ order -> hasProducts ( ) ) { throw new \ Exception ( '$order should have at least one product' ) ; } return $ this -> getTrackPayload ( ActionTypes :: ORDER_COMPLETED , [ PayloadProperties :: PROPERTIES => [ [ PayloadProperties :: ORDER_TOTAL_PRICE => $ order -> getOrderTotal ( ) , PayloadProperties :: PRODUCTS => $ order -> toArray ( ) ] ] ] ) ; }
Generates payload for order completed events
131
public function getCustom ( $ event , $ properties = [ ] ) { $ properties = empty ( $ properties ) ? [ ] : [ PayloadProperties :: PROPERTIES => $ properties ] ; return $ this -> getTrackPayload ( $ event , $ properties ) ; }
Generates payload for custom events
132
public function generateRawData ( ) { $ rawData = [ 'id' => $ this -> getId ( ) ] ; if ( $ this -> getValue ( ) ) { $ rawData [ 'value' ] = $ this -> getValue ( ) ; } if ( $ this -> getName ( ) ) { $ rawData [ 'name' ] = $ this -> getName ( ) ; } if ( $ this -> getAppId ( ) ) { $ rawData [ 'app_id' ] = $ this -> getAppId ( ) ; } if ( $ this -> getLanguage ( ) ) { $ rawData [ 'language' ] = $ this -> getLanguage ( ) ; } if ( $ this -> getCreatedAt ( ) ) { $ rawData [ 'created_at' ] = $ this -> getCreatedAt ( ) ; } if ( $ this -> getUpdatedAt ( ) ) { $ rawData [ 'updated_at' ] = $ this -> getUpdatedAt ( ) ; } return $ rawData ; }
Generates rawData from Concept
133
protected function registerRegistry ( ) { $ this -> app [ 'registry' ] = $ this -> app -> share ( function ( $ app ) { $ config = $ app -> config -> get ( 'registry' , array ( ) ) ; return new Registry ( $ app [ 'db' ] , $ app [ 'registry.cache' ] , $ config ) ; } ) ; }
Register the collection repository .
134
private function rowSameAsTranslation ( array $ row , GettextTranslation $ translation , $ isPlural , $ pluralCount ) { if ( $ row [ 'text0' ] !== $ translation -> getTranslation ( ) ) { return false ; } if ( $ isPlural === false ) { return true ; } $ same = true ; switch ( $ pluralCount ) { case 6 : if ( $ same && $ row [ 'text5' ] !== $ translation -> getPluralTranslation ( 4 ) ) { $ same = false ; } case 5 : if ( $ same && $ row [ 'text4' ] !== $ translation -> getPluralTranslation ( 3 ) ) { $ same = false ; } case 4 : if ( $ same && $ row [ 'text3' ] !== $ translation -> getPluralTranslation ( 2 ) ) { $ same = false ; } case 3 : if ( $ same && $ row [ 'text2' ] !== $ translation -> getPluralTranslation ( 1 ) ) { $ same = false ; } case 2 : if ( $ same && $ row [ 'text1' ] !== $ translation -> getPluralTranslation ( 0 ) ) { $ same = false ; } break ; } return $ same ; }
Is a database row the same as the translation?
135
protected function buildErrorResponse ( $ error , $ code = null ) { if ( $ code !== null && ( ! is_int ( $ code ) || $ code < 400 ) ) { $ code = null ; } if ( is_object ( $ error ) ) { if ( $ error instanceof AccessDeniedException ) { $ error = $ error -> getMessage ( ) ; if ( $ code === null ) { $ code = Response :: HTTP_UNAUTHORIZED ; } } elseif ( $ error instanceof UserMessageException ) { if ( $ error -> getCode ( ) >= 400 ) { $ code = $ error -> getCode ( ) ; } $ error = $ error -> getMessage ( ) ; } elseif ( $ error instanceof Exception || $ error instanceof Throwable ) { $ error = t ( 'An unexpected error occurred' ) ; } elseif ( is_callable ( [ $ error , '__toString' ] ) ) { $ error = ( string ) $ error ; } else { $ error = get_class ( $ error ) ; } } if ( $ code === null ) { $ code = Response :: HTTP_INTERNAL_SERVER_ERROR ; } return $ this -> getResponseFactory ( ) -> create ( $ error , $ code , [ 'Content-Type' => 'text/plain; charset=UTF-8' , ] ) ; }
Build an error response .
136
protected function getRequestJson ( ) { if ( $ this -> request -> getContentType ( ) !== 'json' ) { throw new UserMessageException ( t ( 'Invalid request Content-Type: %s' , $ this -> request -> headers -> get ( 'Content-Type' , '' ) ) , Response :: HTTP_NOT_ACCEPTABLE ) ; } $ contentBody = $ this -> request -> getContent ( ) ; $ contentJson = @ json_decode ( $ contentBody , true ) ; if ( ! is_array ( $ contentJson ) ) { throw new UserMessageException ( t ( 'Failed to parse the request body as JSON' ) , Response :: HTTP_NOT_ACCEPTABLE ) ; } return $ contentJson ; }
Check if the request is a JSON request and returns the posted parameters .
137
public function getRateLimit ( ) { $ this -> start ( ) ; try { $ this -> getUserControl ( ) -> checkRateLimit ( ) ; $ this -> getUserControl ( ) -> checkGenericAccess ( __FUNCTION__ ) ; $ rateLimit = $ this -> getUserControl ( ) -> getRateLimit ( ) ; if ( $ rateLimit === null ) { $ result = $ this -> buildJsonResponse ( null ) ; } else { list ( $ maxRequests , $ timeWindow ) = $ rateLimit ; $ visits = $ this -> getUserControl ( ) -> getVisitsCountFromCurrentIP ( $ timeWindow ) ; $ result = $ this -> buildJsonResponse ( [ 'maxRequests' => $ maxRequests , 'timeWindow' => $ timeWindow , 'currentCounter' => $ visits , ] ) ; } } catch ( Exception $ x ) { $ result = $ this -> buildErrorResponse ( $ x ) ; } catch ( Throwable $ x ) { $ result = $ this -> buildErrorResponse ( $ x ) ; } return $ this -> finish ( $ result ) ; }
Get the current rate limit status .
138
public function getLocales ( ) { $ this -> start ( ) ; try { $ this -> getUserControl ( ) -> checkRateLimit ( ) ; $ this -> getUserControl ( ) -> checkGenericAccess ( __FUNCTION__ ) ; $ locales = $ this -> app -> make ( LocaleRepository :: class ) -> getApprovedLocales ( ) ; $ result = $ this -> buildJsonResponse ( $ this -> localesToArray ( $ locales ) ) ; } catch ( Exception $ x ) { $ result = $ this -> buildErrorResponse ( $ x ) ; } catch ( Throwable $ x ) { $ result = $ this -> buildErrorResponse ( $ x ) ; } return $ this -> finish ( $ result ) ; }
Get the list of approved locales .
139
public function getPackages ( ) { $ this -> start ( ) ; try { $ this -> getUserControl ( ) -> checkRateLimit ( ) ; $ this -> getUserControl ( ) -> checkGenericAccess ( __FUNCTION__ ) ; $ repo = $ this -> app -> make ( PackageRepository :: class ) ; $ packages = $ repo -> createQueryBuilder ( 'p' ) -> select ( 'p.handle, p.name' ) -> getQuery ( ) -> getArrayResult ( ) ; $ result = $ this -> buildJsonResponse ( $ packages ) ; } catch ( Exception $ x ) { $ result = $ this -> buildErrorResponse ( $ x ) ; } catch ( Throwable $ x ) { $ result = $ this -> buildErrorResponse ( $ x ) ; } return $ this -> finish ( $ result ) ; }
Get the list of packages .
140
public function getPackageVersions ( $ packageHandle ) { $ this -> start ( ) ; try { $ this -> getUserControl ( ) -> checkRateLimit ( ) ; $ this -> getUserControl ( ) -> checkGenericAccess ( __FUNCTION__ ) ; $ package = $ this -> app -> make ( PackageRepository :: class ) -> findOneBy ( [ 'handle' => $ packageHandle ] ) ; if ( $ package === null ) { throw new UserMessageException ( t ( 'Unable to find the specified package' ) , Response :: HTTP_NOT_FOUND ) ; } $ versions = [ ] ; foreach ( $ package -> getSortedVersions ( true , null ) as $ packageVersion ) { $ versions [ ] = $ packageVersion -> getVersion ( ) ; } $ result = $ this -> buildJsonResponse ( $ versions ) ; } catch ( Exception $ x ) { $ result = $ this -> buildErrorResponse ( $ x ) ; } catch ( Throwable $ x ) { $ result = $ this -> buildErrorResponse ( $ x ) ; } return $ this -> finish ( $ result ) ; }
Get the list of versions of a package .
141
public function getPackageVersionLocales ( $ packageHandle , $ packageVersion , $ minimumLevel = null ) { $ this -> start ( ) ; try { $ this -> getUserControl ( ) -> checkRateLimit ( ) ; $ accessibleLocales = $ this -> getUserControl ( ) -> checkLocaleAccess ( __FUNCTION__ ) ; $ package = $ this -> app -> make ( PackageRepository :: class ) -> findOneBy ( [ 'handle' => $ packageHandle ] ) ; if ( $ package === null ) { throw new UserMessageException ( t ( 'Unable to find the specified package' ) , Response :: HTTP_NOT_FOUND ) ; } $ isBestMatch = null ; $ version = $ this -> getPackageVersion ( $ package , $ packageVersion , $ isBestMatch ) ; if ( $ version === null ) { throw new UserMessageException ( t ( 'Unable to find the specified package version' ) , Response :: HTTP_NOT_FOUND ) ; } $ minimumLevel = ( int ) $ minimumLevel ; $ stats = $ this -> app -> make ( StatsRepository :: class ) -> get ( $ version , $ accessibleLocales ) ; $ utc = new DateTimeZone ( 'UTC' ) ; $ resultData = $ this -> localesToArray ( $ accessibleLocales , function ( LocaleEntity $ locale , array $ item ) use ( $ stats , $ minimumLevel , $ utc ) { $ result = null ; foreach ( $ stats as $ stat ) { if ( $ stat -> getLocale ( ) === $ locale ) { if ( $ stat -> getPercentage ( ) >= $ minimumLevel ) { $ item [ 'total' ] = $ stat -> getTotal ( ) ; $ item [ 'translated' ] = $ stat -> getTranslated ( ) ; $ item [ 'progress' ] = $ stat -> getPercentage ( true ) ; $ dt = $ stat -> getLastUpdated ( ) ; if ( $ dt === null ) { $ item [ 'updated' ] = null ; } else { $ dt = clone $ dt ; $ dt -> setTimezone ( $ utc ) ; $ item [ 'updated' ] = $ dt -> format ( 'c' ) ; } $ result = $ item ; } break ; } } return $ result ; } ) ; if ( $ isBestMatch ) { $ resultData = [ 'versionHandle' => $ version -> getVersion ( ) , 'versionName' => $ version -> getDisplayVersion ( ) , 'locales' => $ resultData , ] ; } $ result = $ this -> buildJsonResponse ( $ resultData ) ; } catch ( Exception $ x ) { $ result = $ this -> buildErrorResponse ( $ x ) ; } catch ( Throwable $ x ) { $ result = $ this -> buildErrorResponse ( $ x ) ; } return $ this -> finish ( $ result ) ; }
Get some stats about the translations of a package version .
142
public function getPackageVersionTranslations ( $ packageHandle , $ packageVersion , $ localeID , $ formatHandle ) { $ this -> start ( ) ; try { $ this -> getUserControl ( ) -> checkRateLimit ( ) ; $ accessibleLocales = $ this -> getUserControl ( ) -> checkLocaleAccess ( __FUNCTION__ ) ; $ locale = $ this -> app -> make ( LocaleRepository :: class ) -> findApproved ( $ localeID ) ; if ( $ locale === null ) { throw new UserMessageException ( t ( 'Unable to find the specified locale' ) , Response :: HTTP_NOT_FOUND ) ; } if ( ! in_array ( $ locale , $ accessibleLocales , true ) ) { throw AccessDeniedException :: create ( t ( 'Access denied to the specified locale' ) ) ; } $ package = $ this -> app -> make ( PackageRepository :: class ) -> findOneBy ( [ 'handle' => $ packageHandle ] ) ; if ( $ package === null ) { throw new UserMessageException ( t ( 'Unable to find the specified package' ) , Response :: HTTP_NOT_FOUND ) ; } $ version = $ this -> getPackageVersion ( $ package , $ packageVersion ) ; if ( $ version === null ) { throw new UserMessageException ( t ( 'Unable to find the specified package version' ) , Response :: HTTP_NOT_FOUND ) ; } $ format = $ this -> app -> make ( TranslationsConverterProvider :: class ) -> getByHandle ( $ formatHandle ) ; if ( $ format === null ) { throw new UserMessageException ( t ( 'Unable to find the specified translations format' ) , Response :: HTTP_NOT_FOUND ) ; } $ translationsFile = $ this -> app -> make ( TranslationsFileExporter :: class ) -> getSerializedTranslationsFile ( $ version , $ locale , $ format ) ; $ this -> app -> make ( DownloadStatsRepository :: class ) -> logDownload ( $ locale , $ version ) ; $ result = BinaryFileResponse :: create ( $ translationsFile , Response :: HTTP_OK , [ 'Content-Type' => 'application/octet-stream' , 'Content-Transfer-Encoding' => 'binary' , ] ) -> setContentDisposition ( 'attachment' , 'translations-' . $ locale -> getID ( ) . '.' . $ format -> getFileExtension ( ) ) ; } catch ( Exception $ x ) { $ result = $ this -> buildErrorResponse ( $ x ) ; } catch ( Throwable $ x ) { $ result = $ this -> buildErrorResponse ( $ x ) ; } return $ this -> finish ( $ result ) ; }
Get the translations of a package version .
143
public function unrecognizedCall ( $ unrecognizedPath = '' ) { $ this -> start ( ) ; if ( $ unrecognizedPath === '' ) { $ message = t ( 'Resource not specified' ) ; } else { $ message = t ( 'Unknown resource %1$s for %2$s method' , $ unrecognizedPath , $ this -> request -> getMethod ( ) ) ; } $ result = $ this -> buildErrorResponse ( $ message , Response :: HTTP_NOT_FOUND ) ; return $ this -> finish ( $ result ) ; }
What to do if the entry point is not recognized .
144
private function getDefaultProviders ( ) { $ defaultProviders = array ( ) ; foreach ( $ this -> defaultProviders as $ provider ) { $ defaultProviders [ $ provider ] = $ this -> getProvider ( $ provider ) ; } return $ defaultProviders ; }
Retrieves array of default providers objects .
145
public function getProvider ( $ label ) { if ( ! isset ( $ this -> providers [ $ label ] ) ) { throw new InvalidArgumentException ( sprintf ( 'Unknown share button provider `%s`' , $ label ) ) ; } return $ this -> providers [ $ label ] ; }
Retrieves a share button provider from collection by its label .
146
public function render ( array $ options = array ( ) ) { if ( ! empty ( $ options [ 'providers' ] ) ) { $ outputProviders = array ( ) ; foreach ( $ options [ 'providers' ] as $ provider ) { $ outputProviders [ ] = $ this -> getProvider ( $ provider ) ; } } else { $ outputProviders = $ this -> getDefaultProviders ( ) ; } unset ( $ options [ 'providers' ] ) ; $ renderedProviders = array ( ) ; foreach ( $ outputProviders as $ label => $ provider ) { $ provider -> setTemplateEngine ( $ this -> templateEngine ) ; $ provider -> setTemplateName ( $ options [ 'template' ] ) ; $ provider -> setLabel ( $ label ) ; $ renderedProviders [ $ label ] = $ provider -> render ( $ options ) ; } return $ renderedProviders ; }
Renders the share buttons list .
147
public function getUnreviewedInitialTranslations ( LocaleEntity $ locale ) { $ rs = $ this -> app -> make ( TranslationExporter :: class ) -> getUnreviewedSelectQuery ( $ locale ) ; return $ this -> buildInitialTranslations ( $ locale , $ rs ) ; }
Returns the initial translations to be reviewed for the online editor for a specific locale .
148
public function getInitialTranslations ( PackageVersionEntity $ packageVersion , LocaleEntity $ locale ) { $ rs = $ this -> app -> make ( TranslationExporter :: class ) -> getPackageSelectQuery ( $ packageVersion , $ locale , false ) ; return $ this -> buildInitialTranslations ( $ locale , $ rs ) ; }
Returns the initial translations for the online editor for a specific package version .
149
protected function buildInitialTranslations ( LocaleEntity $ locale , \ Concrete \ Core \ Database \ Driver \ PDOStatement $ rs ) { $ approvedSupport = $ this -> app -> make ( Access :: class ) -> getLocaleAccess ( $ locale ) >= Access :: ADMIN ; $ result = [ ] ; $ numPlurals = $ locale -> getPluralCount ( ) ; while ( ( $ row = $ rs -> fetch ( ) ) !== false ) { $ item = [ 'id' => ( int ) $ row [ 'id' ] , 'original' => $ row [ 'text' ] , ] ; if ( $ approvedSupport && $ row [ 'approved' ] ) { $ item [ 'isApproved' ] = true ; } if ( $ row [ 'context' ] !== '' ) { $ item [ 'context' ] = $ row [ 'context' ] ; } $ isPlural = $ row [ 'plural' ] !== '' ; if ( $ isPlural ) { $ item [ 'originalPlural' ] = $ row [ 'plural' ] ; } if ( $ row [ 'text0' ] !== null ) { $ translations = [ ] ; switch ( $ isPlural ? $ numPlurals : 1 ) { case 6 : $ translations [ ] = $ row [ 'text5' ] ; case 5 : $ translations [ ] = $ row [ 'text4' ] ; case 4 : $ translations [ ] = $ row [ 'text3' ] ; case 3 : $ translations [ ] = $ row [ 'text2' ] ; case 2 : $ translations [ ] = $ row [ 'text1' ] ; case 1 : $ translations [ ] = $ row [ 'text0' ] ; break ; } $ item [ 'translations' ] = array_reverse ( $ translations ) ; } $ result [ ] = $ item ; } $ rs -> closeCursor ( ) ; return $ result ; }
Builds the initial translations array .
150
public function getTranslatableData ( LocaleEntity $ locale , TranslatableEntity $ translatable , PackageVersionEntity $ packageVersion = null , $ initial = false ) { $ result = [ 'id' => $ translatable -> getID ( ) , 'translations' => $ this -> getTranslations ( $ locale , $ translatable ) , ] ; if ( $ initial ) { $ place = ( $ packageVersion === null ) ? null : $ this -> app -> make ( TranslatablePlaceRepository :: class ) -> findOneBy ( [ 'packageVersion' => $ packageVersion , 'translatable' => $ translatable ] ) ; if ( $ place !== null ) { $ extractedComments = $ place -> getComments ( ) ; $ references = $ this -> expandReferences ( $ place -> getLocations ( ) , $ packageVersion ) ; } else { $ extractedComments = [ ] ; $ references = [ ] ; } $ result [ 'extractedComments' ] = $ extractedComments ; $ result [ 'references' ] = $ references ; $ result [ 'extractedComments' ] = ( $ place === null ) ? [ ] : $ place -> getComments ( ) ; $ result [ 'comments' ] = $ this -> getComments ( $ locale , $ translatable ) ; $ result [ 'suggestions' ] = $ this -> getSuggestions ( $ locale , $ translatable ) ; $ result [ 'glossary' ] = $ this -> getGlossaryTerms ( $ locale , $ translatable ) ; } return $ result ; }
Returns the data to be used in the editor when editing a string .
151
public function getTranslations ( LocaleEntity $ locale , TranslatableEntity $ translatable ) { $ numPlurals = $ locale -> getPluralCount ( ) ; $ result = [ 'current' => null , 'others' => [ ] , ] ; $ translations = $ this -> app -> make ( TranslationRepository :: class ) -> findBy ( [ 'translatable' => $ translatable , 'locale' => $ locale ] , [ 'createdOn' => 'DESC' ] ) ; $ dh = $ this -> app -> make ( 'helper/date' ) ; $ uh = $ this -> app -> make ( UserService :: class ) ; foreach ( $ translations as $ translation ) { $ texts = [ ] ; switch ( ( $ translatable -> getPlural ( ) === '' ) ? 1 : $ numPlurals ) { case 6 : $ texts [ ] = $ translation -> getText5 ( ) ; case 5 : $ texts [ ] = $ translation -> getText4 ( ) ; case 4 : $ texts [ ] = $ translation -> getText3 ( ) ; case 3 : $ texts [ ] = $ translation -> getText2 ( ) ; case 2 : $ texts [ ] = $ translation -> getText1 ( ) ; case 1 : default : $ texts [ ] = $ translation -> getText0 ( ) ; break ; } $ item = [ 'id' => $ translation -> getID ( ) , 'createdOn' => $ dh -> formatPrettyDateTime ( $ translation -> getCreatedOn ( ) , false , true ) , 'createdBy' => $ uh -> format ( $ translation -> getCreatedBy ( ) ) , 'approved' => $ translation -> isApproved ( ) , 'translations' => array_reverse ( $ texts ) , ] ; if ( $ translation -> isCurrent ( ) ) { $ item [ 'currentSince' ] = $ dh -> formatPrettyDateTime ( $ translation -> getCurrentSince ( ) , false , true ) ; $ result [ 'current' ] = $ item ; } else { $ result [ 'others' ] [ ] = $ item ; } } return $ result ; }
Search all the translations associated to a translatable string .
152
public function getComments ( LocaleEntity $ locale , TranslatableEntity $ translatable , TranslatableCommentEntity $ parentComment = null ) { $ repo = $ this -> app -> make ( TranslatableCommentRepository :: class ) ; if ( $ parentComment === null ) { $ qb = $ repo -> createQueryBuilder ( 'c' ) ; $ qb -> where ( 'c.translatable = :translatable' ) -> andWhere ( 'c.parentComment is null' ) -> andWhere ( $ qb -> expr ( ) -> orX ( 'c.locale = :locale' , 'c.locale is null' ) ) -> orderBy ( 'c.postedOn' , 'ASC' ) -> setParameter ( 'translatable' , $ translatable ) -> setParameter ( 'locale' , $ locale ) ; $ comments = $ qb -> getQuery ( ) -> getResult ( ) ; } else { $ comments = $ repo -> findBy ( [ 'parentComment' => $ parentComment ] , [ 'postedOn' => 'ASC' ] ) ; } $ result = [ ] ; $ uh = $ this -> app -> make ( UserService :: class ) ; $ dh = $ this -> app -> make ( 'helper/date' ) ; $ me = new \ User ( ) ; $ myID = $ me -> isRegistered ( ) ? ( int ) $ me -> getUserID ( ) : null ; foreach ( $ comments as $ comment ) { $ result [ ] = [ 'id' => $ comment -> getID ( ) , 'date' => $ dh -> formatPrettyDateTime ( $ comment -> getPostedOn ( ) , true , true ) , 'mine' => $ myID && $ myID === $ comment -> getPostedBy ( ) , 'by' => $ uh -> format ( $ comment -> getPostedBy ( ) ) , 'text' => $ comment -> getText ( ) , 'comments' => $ this -> getComments ( $ locale , $ translatable , $ comment ) , 'isGlobal' => $ comment -> getLocale ( ) === null , ] ; } return $ result ; }
Get the comments associated to a translatable strings .
153
public function getSuggestions ( LocaleEntity $ locale , TranslatableEntity $ translatable ) { $ result = [ ] ; $ connection = $ this -> app -> make ( EntityManager :: class ) -> getConnection ( ) ; $ rs = $ connection -> executeQuery ( ' select distinct CommunityTranslationTranslatables.text, CommunityTranslationTranslations.text0, match(CommunityTranslationTranslatables.text) against (:search in natural language mode) as relevance from CommunityTranslationTranslations inner join CommunityTranslationTranslatables on CommunityTranslationTranslations.translatable = CommunityTranslationTranslatables.id and 1 = CommunityTranslationTranslations.current and :locale = CommunityTranslationTranslations.locale where CommunityTranslationTranslatables.id <> :currentTranslatableID and length(CommunityTranslationTranslatables.text) between :minLength and :maxLength having relevance > 0 order by relevance desc, text asc limit 0, ' . ( ( int ) self :: MAX_SUGGESTIONS ) . ' ' , [ 'search' => $ translatable -> getText ( ) , 'locale' => $ locale -> getID ( ) , 'currentTranslatableID' => $ translatable -> getID ( ) , 'minLength' => ( int ) floor ( strlen ( $ translatable -> getText ( ) ) * 0.75 ) , 'maxLength' => ( int ) ceil ( strlen ( $ translatable -> getText ( ) ) * 1.33 ) , ] ) ; while ( $ row = $ rs -> fetch ( ) ) { $ result [ ] = [ 'source' => $ row [ 'text' ] , 'translation' => $ row [ 'text0' ] , ] ; } $ rs -> closeCursor ( ) ; return $ result ; }
Search for similar translations .
154
public function getGlossaryTerms ( LocaleEntity $ locale , TranslatableEntity $ translatable ) { $ result = [ ] ; $ connection = $ this -> app -> make ( EntityManager :: class ) -> getConnection ( ) ; $ rs = $ connection -> executeQuery ( ' select CommunityTranslationGlossaryEntries.id, CommunityTranslationGlossaryEntries.term, CommunityTranslationGlossaryEntries.type, CommunityTranslationGlossaryEntries.comments as commentsE, CommunityTranslationGlossaryEntriesLocalized.translation, CommunityTranslationGlossaryEntriesLocalized.comments as commentsEL, match(CommunityTranslationGlossaryEntries.term) against (:search in natural language mode) as relevance from CommunityTranslationGlossaryEntries left join CommunityTranslationGlossaryEntriesLocalized on CommunityTranslationGlossaryEntries.id = CommunityTranslationGlossaryEntriesLocalized.entry and :locale = CommunityTranslationGlossaryEntriesLocalized.locale having relevance > 0 order by relevance desc, CommunityTranslationGlossaryEntries.term asc limit 0, ' . ( ( int ) self :: MAX_GLOSSARY_ENTRIES ) . ' ' , [ 'search' => $ translatable -> getText ( ) , 'locale' => $ locale -> getID ( ) , ] ) ; while ( $ row = $ rs -> fetch ( ) ) { $ result [ ] = [ 'id' => ( int ) $ row [ 'id' ] , 'term' => $ row [ 'term' ] , 'type' => $ row [ 'type' ] , 'termComments' => $ row [ 'commentsE' ] , 'translation' => ( $ row [ 'translation' ] === null ) ? '' : $ row [ 'translation' ] , 'translationComments' => ( $ row [ 'commentsEL' ] === null ) ? '' : $ row [ 'commentsEL' ] , ] ; } $ rs -> closeCursor ( ) ; return $ result ; }
Search the glossary entries to show when translating a string in a specific locale .
155
public function expandReferences ( array $ references , PackageVersionEntity $ packageVersion ) { if ( empty ( $ references ) ) { return $ references ; } $ gitRepositories = $ this -> app -> make ( GitRepositoryRepository :: class ) -> findBy ( [ 'packageHandle' => $ packageVersion -> getPackage ( ) -> getHandle ( ) ] ) ; $ applicableRepository = null ; $ foundVersionData = null ; foreach ( $ gitRepositories as $ gitRepository ) { $ d = $ gitRepository -> getDetectedVersion ( $ packageVersion -> getVersion ( ) ) ; if ( $ d !== null ) { $ applicableRepository = $ gitRepository ; $ foundVersionData = $ d ; break ; } } $ pattern = null ; $ lineFormat = null ; if ( $ applicableRepository !== null ) { $ matches = null ; switch ( true ) { case 1 == preg_match ( '/^(?:\w+:\/\/|\w+@)github.com[:\/]([a-z0-9_.\-]+\/[a-z0-9_.\-]+)\.git$/i' , $ applicableRepository -> getURL ( ) , $ matches ) : switch ( $ foundVersionData [ 'kind' ] ) { case 'tag' : $ pattern = 'https://github.com/' . $ matches [ 1 ] . '/blob/' . $ foundVersionData [ 'repoName' ] . '/<<FILE>><<LINE>>' ; $ lineFormat = '#L%s' ; break ; case 'branch' : $ pattern = 'https://github.com/' . $ matches [ 1 ] . '/blob/' . $ foundVersionData [ 'repoName' ] . '/<<FILE>><<LINE>>' ; $ lineFormat = '#L%s' ; break ; } break ; } } $ result = $ references ; if ( $ pattern !== null ) { $ prefix = $ applicableRepository -> getDirectoryToParse ( ) ; if ( $ prefix !== '' ) { $ prefix .= '/' ; } $ stripSuffix = $ applicableRepository -> getDirectoryForPlaces ( ) ; if ( $ stripSuffix !== '' ) { $ stripSuffix .= '/' ; } $ m = null ; foreach ( $ result as $ index => $ reference ) { if ( ! preg_match ( '/^\w*:\/\//' , $ reference ) ) { if ( preg_match ( '/^(.+):(\d+)$/' , $ reference , $ m ) ) { $ file = $ m [ 1 ] ; $ line = $ m [ 2 ] ; } else { $ file = $ reference ; $ line = null ; } $ file = ltrim ( $ file , '/' ) ; $ line = ( $ line === null || $ lineFormat === null ) ? '' : sprintf ( $ lineFormat , $ line ) ; if ( $ stripSuffix !== '' && strpos ( $ file , $ stripSuffix ) === 0 ) { $ file = $ prefix . substr ( $ file , strlen ( $ stripSuffix ) ) ; } $ result [ $ index ] = [ str_replace ( [ '<<FILE>>' , '<<LINE>>' ] , [ $ file , $ line ] , $ pattern ) , $ reference , ] ; } } } return $ result ; }
Expand translatable string references by adding a link to the online repository where they are defined .
156
public function values ( ) : array { $ ret = [ ] ; foreach ( array_keys ( $ this -> __data ) as $ key ) { $ ret [ $ key ] = $ this -> innerGet ( $ key ) ; } return $ ret ; }
Returns array of all object s stored values
157
public function findByHandleAndVersion ( $ packageHandle , $ packageVersion ) { $ result = null ; $ packageHandle = ( string ) $ packageHandle ; if ( $ packageHandle !== '' ) { $ packageVersion = ( string ) $ packageVersion ; if ( $ packageVersion !== '' ) { $ list = $ this -> createQueryBuilder ( 'v' ) -> innerJoin ( Package :: class , 'p' , Expr \ Join :: WITH , 'v.package = p.id' ) -> where ( 'p.handle = :handle' ) -> setParameter ( 'handle' , $ packageHandle ) -> andWhere ( 'v.version = :version' ) -> setParameter ( 'version' , $ packageVersion ) -> setMaxResults ( 1 ) -> getQuery ( ) -> execute ( ) ; if ( ! empty ( $ list ) ) { $ result = $ list [ 0 ] ; } } } return $ result ; }
Find a version given the package handle and the version .
158
public function addProduct ( $ itemCode , $ itemPrice , $ itemUrl , $ itemQuantity , $ itemTotal = 0 , $ itemName = '' , $ itemImage = '' , $ properties = [ ] ) { $ product = new Product ( $ itemCode , $ itemPrice , $ itemUrl , $ itemQuantity , $ itemTotal , $ itemName , $ itemImage , $ properties ) ; array_push ( $ this -> order , $ product ) ; return $ product ; }
Adds a new product to order collection
159
public function getInputsFromResult ( $ inputResult ) { $ input_array = [ ] ; if ( ! isset ( $ inputResult [ 'inputs' ] ) ) { throw new \ Exception ( 'Inputs Not Found' ) ; } foreach ( $ inputResult [ 'inputs' ] as $ rawInput ) { $ input = new Input ( $ rawInput ) ; $ input_array [ ] = $ input ; } return $ input_array ; }
Parses Request Result and gets Inputs
160
public function init ( $ siteId = '' , $ force = false ) { $ siteId = ! empty ( $ siteId ) ? $ siteId : $ this -> payload -> getSiteId ( ) ; $ hasUserId = $ this -> cookie -> getCookie ( CookieNames :: USER_ID ) ; $ hasUserId = ! empty ( $ hasUserId ) ; $ this -> cookie -> setCookie ( CookieNames :: SITE_ID , $ siteId ) ; $ this -> storeCampaignIdIfExists ( ) ; if ( ! $ hasUserId || $ force ) { $ newUserId = $ this -> replace_dashes ( Uuid :: v4 ( ) ) ; $ this -> cookie -> setCookie ( CookieNames :: USER_ID , $ newUserId , time ( ) + 60 * 60 * 24 * 3650 ) ; return ; } }
Stores a cookie that tells if a user is a new one or returned
161
public function create ( $ siteId , $ userAgent = '' , $ requestIPAddress = '' ) { if ( empty ( $ siteId ) ) { throw new \ Exception ( 'Cannot create an instance without a site id' ) ; } $ cookie = new Cookie ( ) ; $ userId = $ cookie -> getCookie ( CookieNames :: USER_ID ) ; $ userId = ! empty ( $ userId ) ? $ userId : Uuid :: v4 ( ) ; $ payload = new Payload ( new Cookie ( ) , $ siteId , $ userId ) ; $ requestHeaders = [ ] ; $ browserUserAgent = ! empty ( $ userAgent ) ? $ userAgent : Browser :: getUserAgent ( ) ; $ browserIPAddress = ! empty ( $ requestIPAddress ) ? $ requestIPAddress : Browser :: getRequestIPAddress ( ) ; if ( ! empty ( $ browserUserAgent ) ) { $ requestHeaders [ 'X-Original-User-Agent' ] = $ browserUserAgent ; } if ( ! empty ( $ browserIPAddress ) ) { $ requestHeaders [ 'X-Original-Request-IP-Address' ] = $ browserIPAddress ; } $ client = new Client ( [ 'base_uri' => API :: ENDPOINT , RequestOptions :: HEADERS => $ requestHeaders , RequestOptions :: HTTP_ERRORS => false , RequestOptions :: VERIFY => false ] ) ; return new Tracker ( $ cookie , $ payload , $ client ) ; }
Creates a Tracker instance
162
private function configureSourceLocale ( ) { $ em = $ this -> app -> make ( EntityManager :: class ) ; $ repo = $ this -> app -> make ( LocaleRepository :: class ) ; if ( $ repo -> findOneBy ( [ 'isSource' => true ] ) === null ) { $ locale = LocaleEntity :: create ( 'en_US' ) ; $ locale -> setIsApproved ( true ) -> setIsSource ( true ) ; $ em -> persist ( $ locale ) ; $ em -> flush ( $ locale ) ; } }
Configure the source locale .
163
private function registerCLICommands ( ) { $ console = $ this -> app -> make ( 'console' ) ; $ console -> add ( new TransifexTranslationsCommand ( ) ) ; $ console -> add ( new TransifexGlossaryCommand ( ) ) ; $ console -> add ( new ProcessGitRepositoriesCommand ( ) ) ; $ console -> add ( new AcceptPendingJoinRequestsCommand ( ) ) ; $ console -> add ( new SendNotificationsCommand ( ) ) ; $ console -> add ( new RemoveLoggedIPAddressesCommand ( ) ) ; $ console -> add ( new NotifyPackageVersionsCommand ( ) ) ; $ console -> add ( new ProcessRemotePackagesCommand ( ) ) ; }
Register the CLI commands .
164
private function registerAssets ( ) { $ al = AssetList :: getInstance ( ) ; $ al -> registerMultiple ( [ 'jquery/scroll-to' => [ [ 'javascript' , 'js/jquery.scrollTo.min.js' , [ 'minify' => true , 'combine' => true , 'version' => '2.1.2' ] , $ this ] , ] , 'community_translation/online_translation/bootstrap' => [ [ 'javascript' , 'js/bootstrap.min.js' , [ 'minify' => false , 'combine' => true ] , $ this ] , ] , 'community_translation/online_translation/markdown-it' => [ [ 'javascript' , 'js/markdown-it.min.js' , [ 'minify' => false , 'combine' => true ] , $ this ] , ] , 'community_translation/online_translation/core' => [ [ 'css' , 'css/online-translation.css' , [ 'minify' => false , 'combine' => true ] , $ this ] , [ 'javascript' , 'js/online-translation.js' , [ 'minify' => true , 'combine' => true ] , $ this ] , ] , 'jquery/comtraSortable' => [ [ 'css' , 'css/jquery.comtraSortable.css' , [ 'minify' => true , 'combine' => true ] , $ this ] , [ 'javascript' , 'js/jquery.comtraSortable.js' , [ 'minify' => true , 'combine' => true ] , $ this ] , ] , ] ) ; $ al -> registerGroupMultiple ( [ 'jquery/scroll-to' => [ [ [ 'javascript' , 'jquery' ] , [ 'javascript' , 'jquery/scroll-to' ] , ] , ] , 'community_translation/online_translation' => [ [ [ 'css' , 'community_translation/online_translation/core' ] , [ 'javascript' , 'community_translation/online_translation/bootstrap' ] , [ 'javascript' , 'community_translation/online_translation/markdown-it' ] , [ 'javascript' , 'community_translation/online_translation/core' ] , ] , ] , 'jquery/comtraSortable' => [ [ [ 'css' , 'font-awesome' ] , [ 'css' , 'jquery/comtraSortable' ] , [ 'javascript' , 'jquery/comtraSortable' ] , ] , ] , ] ) ; }
Register the assets .
165
public function set ( $ id , callable $ resolver ) { $ this -> innerSet ( $ id , $ resolver ) ; unset ( $ this -> resolved [ $ id ] ) ; unset ( $ this -> singletons [ $ id ] ) ; return $ this ; }
Sets a resolver for entry of the container by its identifier .
166
public function singleton ( $ id , callable $ resolver ) { $ this -> innerSet ( $ id , $ resolver ) ; unset ( $ this -> resolved [ $ id ] ) ; $ this -> singletons [ $ id ] = true ; return $ this ; }
Sets a resolver for entry of the container by its identifier as singleton .
167
public function handleRequest ( string $ method , string $ uri = '' , array $ options = [ ] , array $ parameters = [ ] ) { if ( ! empty ( $ parameters ) ) { if ( $ method === 'GET' ) { $ options [ 'query' ] = $ parameters ; } if ( $ method === 'POST' || $ method === 'PATCH' || $ method === 'DELETE' ) { $ options [ 'json' ] = ( object ) $ parameters ; } } try { $ response = $ this -> client -> request ( $ method , $ uri , $ options ) ; return json_decode ( $ response -> getBody ( ) , true ) ; } catch ( RequestException $ exception ) { $ message = $ exception -> getMessage ( ) ; throw new ApiException ( $ message , $ exception -> getCode ( ) , $ exception ) ; } }
Makes a request using Guzzle
168
public function request ( string $ method , string $ path , array $ parameters = [ ] ) { $ options = [ 'headers' => [ 'Authorization' => sprintf ( 'Key %s' , $ this -> apiKey ) , 'User-Agent' => sprintf ( 'Clarifai PHP (https://github.com/darrynten/clarifai-php);v%s;%s' , \ DarrynTen \ Clarifai \ Clarifai :: VERSION , phpversion ( ) ) , ] , ] ; return $ this -> handleRequest ( $ method , sprintf ( '%s/%s/%s' , $ this -> url , $ this -> version , $ path ) , $ options , $ parameters ) ; }
Makes a request to Clarifai
169
public function generateRawData ( ) { $ rawData = [ 'id' => $ this -> getId ( ) ] ; if ( $ this -> getCreatedAt ( ) ) { $ rawData [ 'created_at' ] = $ this -> getCreatedAt ( ) ; } if ( $ this -> getStatusDescription ( ) || $ this -> getStatusCode ( ) ) { $ rawData [ 'status' ] = $ this -> getStatus ( ) ; } return $ rawData ; }
Generates rawData from modelVersion
170
protected function forceTypes ( $ data ) { if ( in_array ( $ data , array ( 'true' , 'false' ) ) ) { $ data = ( $ data === 'true' ? 1 : 0 ) ; } else if ( is_numeric ( $ data ) ) { $ data = ( int ) $ data ; } else if ( gettype ( $ data ) === 'array' ) { foreach ( $ data as $ key => $ value ) { $ data [ $ key ] = $ this -> forceTypes ( $ value ) ; } } return $ data ; }
Cast values to native PHP variable types .
171
protected function fetchKey ( $ key ) { if ( str_contains ( $ key , '.' ) ) { $ keys = explode ( '.' , $ key ) ; $ search = array_except ( $ keys , 0 ) ; return array ( array_get ( $ keys , 0 ) , implode ( '.' , $ search ) ) ; } return array ( $ key , null ) ; }
Get registry key
172
public function getPaginationHTML ( ) { if ( $ this -> pagination -> haveToPaginate ( ) ) { $ view = new TwitterBootstrap3View ( ) ; $ me = $ this ; $ result = $ view -> render ( $ this -> pagination , function ( $ page ) use ( $ me ) { $ list = $ me -> getItemListObject ( ) ; $ result = ( string ) $ me -> getBaseURL ( ) ; $ result .= strpos ( $ result , '?' ) === false ? '?' : '&' ; $ result .= ltrim ( $ list -> getQueryPaginationPageParameter ( ) , '&' ) . '=' . $ page ; return $ result ; } , [ 'prev_message' => tc ( 'Pagination' , '&larr; Previous' ) , 'next_message' => tc ( 'Pagination' , 'Next &rarr;' ) , 'active_suffix' => '<span class="sr-only">' . tc ( 'Pagination' , '(current)' ) . '</span>' , ] ) ; } else { $ result = '' ; } return $ result ; }
Builds the HTML to be used to control the pagination .
173
public function generateRawData ( ) { $ rawData = [ 'id' => $ this -> getId ( ) ] ; $ rawData [ 'data' ] = [ ] ; $ rawData [ 'data' ] [ 'image' ] = [ ] ; if ( $ this -> getCreatedAt ( ) ) { $ rawData [ 'created_at' ] = $ this -> getCreatedAt ( ) ; } if ( $ this -> getStatusDescription ( ) || $ this -> getStatusCode ( ) ) { $ rawData [ 'status' ] = $ this -> getStatus ( ) ; } if ( $ this -> getImage ( ) ) { $ rawData [ 'data' ] [ 'image' ] [ $ this -> getImageMethod ( ) ] = $ this -> getImage ( ) ; } if ( $ this -> getCrop ( ) ) { $ rawData [ 'data' ] [ 'image' ] [ 'crop' ] = $ this -> getCrop ( ) ; } if ( $ this -> getConcepts ( ) ) { $ rawData [ 'data' ] [ 'concepts' ] = [ ] ; foreach ( $ this -> getConcepts ( ) as $ concept ) { $ rawData [ 'data' ] [ 'concepts' ] [ ] = $ concept -> generateRawData ( ) ; } } if ( $ this -> getMetaData ( ) ) { $ rawData [ 'data' ] [ 'metadata' ] = $ this -> getMetaData ( ) ; } return $ rawData ; }
Generates rawData from Input
174
public function splitTimeWindow ( $ timeWindow , $ default = 3600 ) { $ timeWindow = ( int ) $ timeWindow ; if ( $ timeWindow <= 0 ) { $ timeWindow = ( int ) $ default ; } foreach ( array_keys ( $ this -> getTimeWindowUnits ( ) ) as $ u ) { if ( ( $ timeWindow % $ u ) === 0 ) { $ unit = $ u ; } else { break ; } } return [ ( int ) ( $ timeWindow / $ unit ) , $ unit , ] ; }
Get the representation of a time window expressed in seconds .
175
public function getWidgetHtml ( $ name , $ maxRequests , $ timeWindow ) { list ( $ timeWindowValue , $ timeWindowUnit ) = $ this -> splitTimeWindow ( $ timeWindow ) ; $ html = '<div class="input-group" id="' . $ name . '_container">' ; $ html .= $ this -> form -> number ( $ name . '_maxRequests' , $ maxRequests , [ 'min' => '1' ] ) ; $ html .= '<span class="input-group-addon">' . tc ( 'TimeInterval' , 'requests every' ) . '</span>' ; $ html .= $ this -> form -> number ( $ name . '_timeWindow_value' , $ timeWindowValue , [ 'min' => '1' ] ) ; $ html .= '<div class="input-group-btn">' ; $ timeWindowUnits = $ this -> getTimeWindowUnits ( ) ; $ u = $ this -> form -> getRequestValue ( $ name . '_timeWindow_unit' ) ; if ( isset ( $ timeWindowUnits [ $ u ] ) ) { $ timeWindowUnit = $ u ; } $ html .= '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><span id="' . $ name . '_timeWindow_unitlabel">' . h ( $ timeWindowUnits [ $ timeWindowUnit ] ) . '</span> <span class="caret"></span></button>' ; $ html .= '<ul class="dropdown-menu dropdown-menu-right">' ; foreach ( $ timeWindowUnits as $ unitValue => $ unitName ) { $ html .= '<li><a href="#" data-unit-value="' . $ unitValue . '" data-max-value="' . floor ( PHP_INT_MAX / $ unitValue ) . '">' . h ( $ unitName ) . '</a></li>' ; } $ html .= '</ul>' ; $ html .= '</div>' ; $ html .= $ this -> form -> hidden ( $ name . '_timeWindow_unit' , $ timeWindowUnit ) ; $ html .= '</div>' ; $ html .= <<<EOT<script>$(document).ready(function() { var twValue = $('#{$name}_timeWindow_value'), twUnitLabel = $('#{$name}_timeWindow_unitlabel'), twUnit = $('#{$name}_timeWindow_unit'), twUnitLinks = $('#{$name}_container a[data-unit-value]'); twUnit .on('change', function() { var a = twUnitLinks.filter('[data-unit-value="' + twUnit.val() + '"]'); twUnitLabel.text(a.text()); twValue.attr('max', a.data('max-value')); }) .trigger('change') ; twUnitLinks.on('click', function(e) { e.preventDefault(); twUnit.val($(this).data('unit-value')).trigger('change'); });});</script>EOT ; return $ html ; }
Create the HTML for a rate limit .
176
public function fromWidgetHtml ( $ name , $ defaultTimeWindow = 3600 ) { $ post = $ this -> request -> request ; $ s = $ post -> get ( $ name . '_maxRequests' ) ; $ maxRequests = ( is_scalar ( $ s ) && is_numeric ( $ s ) ) ? ( int ) $ s : null ; if ( $ maxRequests !== null && $ maxRequests <= 0 ) { throw new UserMessageException ( t ( 'Please specify a positive integer for the maximum number of requests (or leave it empty)' ) ) ; } try { $ timeWindow = $ this -> joinTimeWindow ( $ post -> get ( $ name . '_timeWindow_value' ) , $ post -> get ( $ name . '_timeWindow_unit' ) , true ) ; } catch ( UserMessageException $ x ) { if ( $ maxRequests === null ) { $ timeWindow = $ defaultTimeWindow ; } else { throw $ x ; } } return [ $ maxRequests , $ timeWindow ] ; }
Get the rate limit values from the values of the widget .
177
public function describeRate ( $ maxRequests , $ timeWindow ) { if ( $ maxRequests && $ timeWindow ) { list ( $ value , $ unit ) = $ this -> splitTimeWindow ( $ timeWindow ) ; switch ( $ unit ) { case 60 : $ duration = Unit :: format ( $ value , 'duration/minute' , 'long' ) ; break ; case 3600 : $ duration = Unit :: format ( $ value , 'duration/hour' , 'long' ) ; break ; case 86400 : $ duration = Unit :: format ( $ value , 'duration/day' , 'long' ) ; break ; case 604800 : $ duration = Unit :: format ( $ value , 'duration/week' , 'long' ) ; break ; default : $ duration = Unit :: format ( $ timeWindow , 'duration/second' , 'long' ) ; break ; } $ result = t2 ( '%1$d request every %2$s' , '%1$d requests every %2$s' , $ maxRequests , $ duration ) ; } else { $ result = '' ; } return $ result ; }
Format a rate limit .
178
public function setTranslations ( Locale $ locale , Translations $ translations ) { $ this -> translations [ $ locale -> getID ( ) ] = [ $ locale , $ translations ] ; }
Set the translations for a specific locale .
179
public function getTranslations ( Locale $ locale ) { $ localeID = $ locale -> getID ( ) ; $ translations = isset ( $ this -> translations [ $ localeID ] ) ? $ this -> translations [ $ localeID ] [ 1 ] : null ; if ( $ translations === null ) { $ translations = clone $ this -> getSourceStrings ( true ) ; $ translations -> setLanguage ( $ locale -> getID ( ) ) ; $ this -> setTranslations ( $ locale , $ translations ) ; } return $ translations ; }
Get the translations for a specific locale .
180
public function mergeWith ( Parsed $ other ) { $ mergeMethod = Translations :: MERGE_ADD | Translations :: MERGE_PLURAL ; if ( $ other -> sourceStrings !== null ) { if ( $ this -> sourceStrings === null ) { $ this -> sourceStrings = $ other -> sourceStrings ; } else { $ this -> sourceStrings -> mergeWith ( $ other -> sourceStrings , $ mergeMethod ) ; } } foreach ( $ other -> translations as $ key => $ data ) { if ( isset ( $ this -> translations [ $ key ] ) ) { $ this -> translations [ $ key ] [ 1 ] -> mergeWith ( $ data [ 1 ] , $ mergeMethod ) ; } else { $ this -> translations [ $ key ] = $ data ; } } }
Merge another instance into this one .
181
public function generate ( ) { $ pickChars = str_repeat ( static :: DICTIONARY , static :: LENGTH ) ; for ( ; ; ) { $ value = substr ( str_shuffle ( $ pickChars ) , 0 , static :: LENGTH ) ; if ( preg_match ( static :: TOKEN_GENERATION_REGEX , $ value ) ) { $ this -> insertQuery -> execute ( [ $ value ] ) ; if ( $ this -> insertQuery -> rowCount ( ) === 1 ) { break ; } } } return $ value ; }
Generate a new API token .
182
public function isGenerated ( $ token ) { $ result = false ; $ token = ( string ) $ token ; if ( $ token !== '' ) { $ this -> searchQuery -> execute ( [ $ token ] ) ; $ row = $ this -> searchQuery -> fetch ( ) ; $ this -> searchQuery -> closeCursor ( ) ; if ( $ row !== false ) { $ result = true ; } } return $ result ; }
Check if a token has been generated .
183
public function setIsCurrent ( $ value ) { if ( $ value ) { $ this -> current = true ; } else { $ this -> current = null ; } return $ this ; }
Is this the current translation?
184
public function postPersist ( LifecycleEventArgs $ args ) { $ entity = $ args -> getObject ( ) ; if ( $ entity instanceof PackageVersionEntity ) { $ this -> refreshPackageLatestVersion ( $ args -> getObjectManager ( ) , $ entity -> getPackage ( ) ) ; } }
Callback method called when a new entity has been saved .
185
public function postUpdate ( LifecycleEventArgs $ args ) { $ entity = $ args -> getObject ( ) ; if ( $ entity instanceof PackageVersionEntity ) { $ em = $ args -> getObjectManager ( ) ; $ unitOfWork = $ em -> getUnitOfWork ( ) ; $ changeSet = $ unitOfWork -> getEntityChangeSet ( $ entity ) ; if ( in_array ( 'version' , $ changeSet ) ) { $ this -> refreshPackageLatestVersion ( $ em , $ entity -> getPackage ( ) ) ; } } }
Callback method called when a modified entity is going to be saved .
186
public function getByLocale ( LocaleEntity $ locale ) { $ app = Application :: getFacadeApplication ( ) ; $ result = $ this -> find ( $ locale ) ; if ( $ result === null ) { $ em = $ this -> getEntityManager ( ) ; try { $ numTranslatable = ( int ) $ app -> make ( TranslatableRepository :: class ) -> createQueryBuilder ( 't' ) -> select ( 'count(t.id)' ) -> getQuery ( ) -> getSingleScalarResult ( ) ; } catch ( NoResultException $ x ) { $ numTranslatable = 0 ; } if ( $ numTranslatable === 0 ) { $ numApprovedTranslations = 0 ; } else { try { $ numApprovedTranslations = ( int ) $ app -> make ( TranslationRepository :: class ) -> createQueryBuilder ( 't' ) -> select ( 'count(t.id)' ) -> where ( 't.locale = :locale' ) -> setParameter ( 'locale' , $ locale ) -> andWhere ( 't.current = 1' ) -> getQuery ( ) -> getSingleScalarResult ( ) ; } catch ( NoResultException $ x ) { $ numApprovedTranslations = 0 ; } } $ result = LocaleStatsEntity :: create ( $ locale , $ numTranslatable , $ numApprovedTranslations ) ; $ em -> persist ( $ result ) ; $ em -> flush ( $ result ) ; } return $ result ; }
Get the stats for a specific locale . If the stats does not exist yet they are created .
187
public function resetForLocale ( LocaleEntity $ locale ) { $ this -> createQueryBuilder ( 't' ) -> delete ( ) -> where ( 't.locale = :locale' ) -> setParameter ( 'locale' , $ locale ) -> getQuery ( ) -> execute ( ) ; }
Clear the stats for a specific locale .
188
protected function getLocaleGroup ( $ parentName , $ locale ) { if ( ! ( $ locale instanceof LocaleEntity ) ) { $ l = $ this -> app -> make ( LocaleRepository :: class ) -> findApproved ( $ locale ) ; if ( $ l === null ) { throw new UserMessageException ( t ( "The locale identifier '%s' is not valid" , $ locale ) ) ; } $ locale = $ l ; } $ localeID = $ locale -> getID ( ) ; if ( ! isset ( $ this -> localeGroups [ $ parentName ] ) ) { $ this -> localeGroups [ $ parentName ] = [ ] ; } if ( ! isset ( $ this -> localeGroups [ $ parentName ] [ $ localeID ] ) ) { $ this -> localeGroups [ $ parentName ] [ $ localeID ] = $ this -> getGroup ( $ localeID , $ parentName ) ; } return $ this -> localeGroups [ $ parentName ] [ $ localeID ] ; }
Get a locale group given its parent group name .
189
public function getGlobalAdministrators ( ) { if ( $ this -> globalAdministrators === null ) { $ this -> globalAdministrators = $ this -> getGroup ( self :: GROUPNAME_GLOBAL_ADMINISTRATORS ) ; } return $ this -> globalAdministrators ; }
Get the global administrators group .
190
public function decodeAspiringTranslatorsGroup ( Group $ group ) { $ result = null ; $ match = null ; if ( preg_match ( '/^\/' . preg_quote ( self :: GROUPNAME_ASPIRING_TRANSLATORS , '/' ) . '\/(.+)$/' , $ group -> getGroupPath ( ) , $ match ) ) { $ result = $ this -> app -> make ( LocaleRepository :: class ) -> findApproved ( $ match [ 1 ] ) ; } return $ result ; }
Check if a group is an aspiring translators group . If so returns the associated locale entity .
191
public function deleteLocaleGroups ( $ localeID ) { foreach ( [ self :: GROUPNAME_LOCALE_ADMINISTRATORS , self :: GROUPNAME_TRANSLATORS , self :: GROUPNAME_ASPIRING_TRANSLATORS , ] as $ parentGroupName ) { $ path = "/$parentGroupName/$localeID" ; $ group = Group :: getByPath ( $ path ) ; if ( $ group !== null ) { $ group -> delete ( ) ; } } }
Delete the user groups associated to a locale ID .
192
public function clear ( ) { $ i = 0 ; if ( $ glob = @ glob ( $ this -> f3 -> get ( 'ASSETS.public_path' ) . '*' ) ) foreach ( $ glob as $ file ) if ( preg_match ( '/.+?\.(js|css)/i' , basename ( $ file ) ) ) { $ i ++ ; @ unlink ( $ file ) ; } return $ i ; }
reset the temporary public path
193
public function getAssets ( $ group = 'head' , $ type = null ) { $ assets = array ( ) ; if ( ! isset ( $ this -> assets [ $ group ] ) ) return $ assets ; $ types = array_keys ( $ this -> assets [ $ group ] ) ; foreach ( $ types as $ asset_type ) { if ( $ type && $ type != $ asset_type ) continue ; krsort ( $ this -> assets [ $ group ] [ $ asset_type ] ) ; foreach ( $ this -> assets [ $ group ] [ $ asset_type ] as $ prio_set ) foreach ( $ prio_set as $ asset ) { if ( $ asset [ 'origin' ] == 'inline' ) $ assets [ $ asset_type ] [ $ asset [ 'data' ] ] = $ asset ; else $ assets [ $ asset_type ] [ $ asset [ 'path' ] ] = $ asset ; } $ assets [ $ asset_type ] = array_values ( $ assets [ $ asset_type ] ) ; } return $ assets ; }
get sorted unique assets from group
194
public function renderGroup ( $ assets ) { $ out = array ( ) ; if ( $ this -> f3 -> get ( 'ASSETS.trim_public_root' ) ) { $ basePath = $ this -> f3 -> fixslashes ( realpath ( $ this -> f3 -> fixslashes ( $ _SERVER [ 'DOCUMENT_ROOT' ] . $ this -> f3 -> get ( 'BASE' ) ) ) ) ; $ cDir = $ this -> f3 -> fixslashes ( getcwd ( ) ) ; $ trimPublicDir = str_replace ( $ cDir , '' , $ basePath ) ; } foreach ( $ assets as $ asset_type => $ collection ) { if ( $ this -> f3 -> exists ( 'ASSETS.filter.' . $ asset_type , $ filters ) ) { if ( is_string ( $ filters ) ) $ filters = $ this -> f3 -> split ( $ filters ) ; $ flist = array_flip ( $ filters ) ; $ filters = array_values ( array_intersect_key ( array_replace ( $ flist , $ this -> filter ) , $ flist ) ) ; $ collection = $ this -> f3 -> relay ( $ filters , array ( $ collection ) ) ; } foreach ( $ collection as $ asset ) { if ( isset ( $ asset [ 'path' ] ) ) { $ path = $ asset [ 'path' ] ; $ mtime = ( $ this -> f3 -> get ( 'ASSETS.timestamps' ) && $ asset [ 'origin' ] != 'external' && is_file ( $ path ) ) ? '?' . filemtime ( $ path ) : '' ; $ base = ( $ this -> f3 -> get ( 'ASSETS.prepend_base' ) && $ asset [ 'origin' ] != 'external' && is_file ( $ path ) ) ? $ this -> f3 -> get ( 'BASE' ) . '/' : '' ; if ( isset ( $ trimPublicDir ) && $ asset [ 'origin' ] != 'external' ) $ path = substr ( $ path , strlen ( $ trimPublicDir ) ) ; $ asset [ 'path' ] = $ base . $ path . $ mtime ; } $ out [ ] = $ this -> f3 -> call ( $ this -> formatter [ $ asset_type ] , array ( $ asset ) ) ; } } return "\n\t" . implode ( "\n\t" , $ out ) . "\n" ; }
render asset group
195
public function fixRelativePaths ( $ content , $ path , $ targetDir = null ) { $ f3 = $ this -> f3 ; $ method = $ f3 -> get ( 'ASSETS.fixRelativePaths' ) ; if ( $ method !== FALSE ) { $ webBase = $ f3 -> get ( 'BASE' ) ; $ basePath = $ f3 -> fixslashes ( realpath ( $ f3 -> fixslashes ( $ _SERVER [ 'DOCUMENT_ROOT' ] . $ webBase ) ) . DIRECTORY_SEPARATOR ) ; $ content = preg_replace_callback ( '/\b(?<=url)\((?:([\"\']?)(.+?)((\?.*?)?)\1)\)/s' , function ( $ url ) use ( $ path , $ f3 , $ webBase , $ basePath , $ targetDir , $ method ) { if ( preg_match ( '/https?:/' , $ url [ 2 ] ) || ! $ rPath = realpath ( $ path . $ url [ 2 ] ) ) return $ url [ 0 ] ; if ( $ method == 'relative' ) { $ filePathFromBase = str_replace ( $ basePath , '' , $ f3 -> fixslashes ( $ rPath ) ) ; $ rel = $ this -> relPath ( $ targetDir , $ filePathFromBase ) ; return '(' . $ url [ 1 ] . $ rel . ( isset ( $ url [ 4 ] ) ? $ url [ 4 ] : '' ) . $ url [ 1 ] . ')' ; } elseif ( $ method == 'absolute' ) { return '(' . $ url [ 1 ] . preg_replace ( '/' . preg_quote ( $ basePath , '/' ) . '(.+)/' , '\1' , $ webBase . '/' . $ f3 -> fixslashes ( $ rPath ) . ( isset ( $ url [ 4 ] ) ? $ url [ 4 ] : '' ) ) . $ url [ 1 ] . ')' ; } return $ url [ 0 ] ; } , $ content ) ; } return $ content ; }
Rewrite relative URLs in CSS
196
public function relPath ( $ from , $ to ) { $ expFrom = explode ( '/' , $ from ) ; $ expTo = explode ( '/' , $ to ) ; $ max = max ( count ( $ expFrom ) , count ( $ expTo ) ) ; $ rel = [ ] ; $ base = TRUE ; for ( $ i = 0 ; $ i < $ max ; $ i ++ ) { if ( $ base && isset ( $ expTo [ $ i ] ) && isset ( $ expFrom [ $ i ] ) && $ expTo [ $ i ] === $ expFrom [ $ i ] ) continue ; else $ base = FALSE ; if ( ! empty ( $ expFrom [ $ i ] ) ) array_unshift ( $ rel , '..' ) ; if ( ! empty ( $ expTo [ $ i ] ) ) array_push ( $ rel , $ expTo [ $ i ] ) ; } return implode ( '/' , $ rel ) ; }
assemble relative path to go from A to B
197
public function add ( $ path , $ type , $ group = 'head' , $ priority = 5 , $ slot = null , $ params = null ) { if ( ! isset ( $ this -> assets [ $ group ] ) ) $ this -> assets [ $ group ] = array ( ) ; if ( ! isset ( $ this -> assets [ $ group ] [ $ type ] ) ) $ this -> assets [ $ group ] [ $ type ] = array ( ) ; $ asset = array ( 'path' => $ path , 'type' => $ type , 'slot' => $ slot ) + ( $ params ? : array ( ) ) ; if ( preg_match ( '/^(http(s)?:)?\/\/.*/i' , $ path ) ) { $ asset [ 'origin' ] = 'external' ; $ this -> assets [ $ group ] [ $ type ] [ $ priority ] [ ] = $ asset ; return ; } foreach ( $ this -> f3 -> split ( $ this -> f3 -> get ( 'UI' ) ) as $ dir ) if ( is_file ( $ view = $ this -> f3 -> fixslashes ( $ dir . $ path ) ) ) { $ asset [ 'path' ] = ltrim ( $ view , './' ) ; $ asset [ 'origin' ] = 'internal' ; $ this -> assets [ $ group ] [ $ type ] [ $ priority ] [ ] = $ asset ; return ; } if ( $ handler = $ this -> f3 -> get ( 'ASSETS.onFileNotFound' ) ) $ this -> f3 -> call ( $ handler , array ( $ path , $ this ) ) ; $ asset [ 'origin' ] = 'external' ; $ this -> assets [ $ group ] [ $ type ] [ $ priority ] [ ] = $ asset ; }
add an asset
198
public function addJs ( $ path , $ priority = 5 , $ group = 'footer' , $ slot = null ) { $ this -> add ( $ path , 'js' , $ group , $ priority , $ slot ) ; }
add a javascript asset
199
public function addCss ( $ path , $ priority = 5 , $ group = 'head' , $ slot = null ) { $ this -> add ( $ path , 'css' , $ group , $ priority , $ slot ) ; }
add a css asset