idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
28,200
protected function _buildNewPreset ( $ preset_name ) { $ preset = isset ( $ this -> presets_data [ $ preset_name ] ) ? $ this -> presets_data [ $ preset_name ] [ 'data' ] : null ; if ( ! empty ( $ preset ) ) { $ package = $ this -> getPackage ( $ this -> presets_data [ $ preset_name ] [ 'package' ] ) ; $ cls_name = Config :: get ( 'assets-preset-class' ) ; if ( @ class_exists ( $ cls_name ) ) { $ interfaces = class_implements ( $ cls_name ) ; $ config_interface = Config :: getInternal ( 'assets-preset-interface' ) ; if ( in_array ( $ config_interface , $ interfaces ) ) { $ preset_object = new $ cls_name ( $ preset_name , $ preset , $ package ) ; return $ preset_object ; } else { throw new \ DomainException ( sprintf ( 'Preset class "%s" must implement interface "%s"!' , $ cls_name , $ config_interface ) ) ; } } else { throw new \ DomainException ( sprintf ( 'Preset class "%s" not found!' , $ cls_name ) ) ; } } else { throw new \ InvalidArgumentException ( sprintf ( 'Unknown preset "%s"!' , $ preset_name ) ) ; } return null ; }
Build a new preset instance
28,201
public static function buildWebPath ( $ path ) { $ _this = self :: getInstance ( ) ; return trim ( FilesystemHelper :: resolveRelatedPath ( $ _this -> getDocumentRoot ( ) , realpath ( $ path ) ) , '/' ) ; }
Build a web path ready to use in HTML
28,202
public static function find ( $ filename , $ package = null ) { $ _this = self :: getInstance ( ) ; if ( ! is_null ( $ package ) ) { return self :: findInPackage ( $ filename , $ package ) ; } else { return self :: findInPath ( $ filename , $ _this -> getAssetsRealPath ( ) ) ; } }
Find an asset file in the filesystem
28,203
public static function findInPackage ( $ filename , $ package ) { $ _this = self :: getInstance ( ) ; $ package_path = DirectoryHelper :: slashDirname ( $ _this -> getPackageAssetsPath ( $ package ) ) ; if ( ! is_null ( $ package_path ) ) { $ asset_path = $ package_path . $ filename ; if ( file_exists ( $ asset_path ) ) { return self :: buildWebPath ( $ asset_path ) ; } } return null ; }
Find an asset file in the filesystem of a specific package
28,204
public static function findInPath ( $ filename , $ path ) { $ asset_path = DirectoryHelper :: slashDirname ( $ path ) . $ filename ; if ( file_exists ( $ asset_path ) ) { return self :: buildWebPath ( $ asset_path ) ; } return null ; }
Find an asset file in a package s path
28,205
public function getFullDb ( ) { $ filesystem = new Filesystem ( ) ; $ config = $ this -> _composer -> getConfig ( ) ; $ assets_db = $ this -> _autoloader -> getRegistry ( ) ; $ vendor_dir = $ this -> _autoloader -> getAssetsInstaller ( ) -> getVendorDir ( ) ; $ app_base_path = $ this -> _autoloader -> getAssetsInstaller ( ) -> getAppBasePath ( ) ; $ assets_dir = str_replace ( $ app_base_path . '/' , '' , $ this -> _autoloader -> getAssetsInstaller ( ) -> getAssetsDir ( ) ) ; $ assets_vendor_dir = str_replace ( $ app_base_path . '/' . $ assets_dir . '/' , '' , $ this -> _autoloader -> getAssetsInstaller ( ) -> getAssetsVendorDir ( ) ) ; $ document_root = $ this -> _autoloader -> getAssetsInstaller ( ) -> getDocumentRoot ( ) ; $ extra = $ this -> _package -> getExtra ( ) ; $ root_data = $ this -> _autoloader -> getAssetsInstaller ( ) -> parseComposerExtra ( $ this -> _package , $ app_base_path , '' ) ; if ( ! empty ( $ root_data ) ) { $ root_data [ 'relative_path' ] = '../' ; $ assets_db [ $ this -> _package -> getPrettyName ( ) ] = $ root_data ; } $ vendor_path = strtr ( realpath ( $ vendor_dir ) , '\\' , '/' ) ; $ rel_vendor_path = $ filesystem -> findShortestPath ( getcwd ( ) , $ vendor_path , true ) ; $ local_repo = $ this -> _composer -> getRepositoryManager ( ) -> getLocalRepository ( ) ; $ package_map = $ this -> buildPackageMap ( $ this -> _composer -> getInstallationManager ( ) , $ this -> _package , $ local_repo -> getPackages ( ) ) ; foreach ( $ package_map as $ i => $ package ) { if ( $ i === 0 ) { continue ; } $ package_object = $ package [ 0 ] ; $ package_install_path = $ package [ 1 ] ; if ( empty ( $ package_install_path ) ) { $ package_install_path = $ app_base_path ; } $ package_name = $ package_object -> getPrettyName ( ) ; $ data = $ this -> _autoloader -> getAssetsInstaller ( ) -> parseComposerExtra ( $ package_object , $ this -> _autoloader -> getAssetsInstaller ( ) -> getAssetsInstallPath ( $ package_object ) , str_replace ( $ app_base_path . '/' , '' , $ vendor_path ) . '/' . $ package_object -> getPrettyName ( ) ) ; if ( ! empty ( $ data ) ) { $ assets_db [ $ package_name ] = $ data ; } } $ full_db = array ( 'assets-dir' => $ assets_dir , 'assets-vendor-dir' => $ assets_vendor_dir , 'document-root' => $ document_root , 'packages' => $ assets_db ) ; return $ full_db ; }
Build the complete database array
28,206
protected function generateAutoloader ( array $ list_files ) : bool { $ file = $ this -> getObfuscatedPath ( ) . DIRECTORY_SEPARATOR . 'autoloader.php' ; $ contents = "<?php \n\n" ; $ contents .= "\$includes = array(\n" ; $ contents .= " '" . implode ( "',\n '" , $ list_files ) . "'\n" ; $ contents .= ");\n\n" ; $ contents .= "foreach(\$includes as \$file) {\n" ; $ contents .= " require_once(\$file);\n" ; $ contents .= "}\n\n" ; return ( file_put_contents ( $ file , $ contents ) !== false ) ; }
Gera um carregador para os arquivos ofuscados .
28,207
public function process ( $ type , $ manifest = null , $ vars = array ( ) , $ full = false ) { if ( self :: $ current_instance ) throw new \ RuntimeException ( 'There is still a Pipeline instance running' ) ; self :: $ current_instance = $ this ; if ( $ manifest ) $ this -> manifest_name = $ manifest ; else $ this -> manifest_name = 'application' ; $ this -> registered_files [ $ type ] = array ( ) ; $ content = ( string ) new File ( $ this -> manifest_name . '.' . $ type , $ vars ) ; self :: $ current_instance = null ; return $ full ? array ( $ this -> registered_files [ $ type ] , $ content ) : $ content ; }
Runs the pipeline
28,208
public function getDependenciesFileContent ( $ type ) { $ hash = array ( ) ; foreach ( $ this -> getDependencies ( $ type ) as $ dependency ) $ hash [ ] = $ dependency . ':' . filemtime ( $ dependency ) ; return implode ( "\n" , $ hash ) ; }
returns dependency list formatted for storing
28,209
private function getFilterClass ( $ name ) { if ( isset ( $ this -> extensions [ $ name ] ) ) return $ this -> extensions [ $ name ] ; if ( class_exists ( $ class = 'Sprockets\Filter\\' . ucfirst ( $ name ) ) ) return $ class ; return false ; }
finds filter class
28,210
public function applyFilter ( $ content , $ filter , $ file , $ dir , $ vars ) { $ filter = $ this -> getFilter ( $ filter ) ; return $ filter ( $ content , $ file , $ dir , $ vars ) ; }
apply a filter used for singletonization of filters
28,211
public function indexDocument ( $ document ) { if ( isset ( $ document [ '_id' ] [ 'type' ] ) ) { $ collection = $ this -> config -> getCollectionForSearchDocument ( $ this -> storeName , $ document [ '_id' ] [ 'type' ] ) ; } else { throw new \ Tripod \ Exceptions \ SearchException ( "No search document type specified in document" ) ; } try { $ result = $ collection -> updateOne ( array ( '_id' => $ document [ '_id' ] ) , array ( '$set' => $ document ) , array ( 'upsert' => true ) ) ; if ( ! $ result -> isAcknowledged ( ) ) { throw new \ Tripod \ Exceptions \ SearchException ( "Inserting search document not acknowledged" ) ; } } catch ( \ Exception $ e ) { throw new \ Tripod \ Exceptions \ SearchException ( "Failed to Index Document \n" . print_r ( $ document , true ) , 0 , $ e ) ; } }
Indexes the given document
28,212
public function deleteDocument ( $ resource , $ context , $ specId = array ( ) ) { $ query = array ( _ID_KEY . '.' . _ID_RESOURCE => $ this -> labeller -> uri_to_alias ( $ resource ) , _ID_KEY . '.' . _ID_CONTEXT => $ context ) ; try { $ searchTypes = array ( ) ; if ( ! empty ( $ specId ) ) { $ specTypes = $ this -> config -> getSearchDocumentSpecifications ( $ this -> storeName , null , true ) ; if ( is_string ( $ specId ) ) { if ( ! in_array ( $ specId , $ specTypes ) ) { return ; } $ query [ _ID_KEY ] [ _ID_TYPE ] = $ specId ; $ searchTypes [ ] = $ specId ; } elseif ( is_array ( $ specId ) ) { $ specId = array_intersect ( $ specTypes , $ specId ) ; if ( empty ( $ specId ) ) { return ; } $ query [ _ID_KEY . '.' . _ID_TYPE ] = array ( '$in' => array_values ( $ specId ) ) ; $ searchTypes = $ specId ; } } foreach ( $ this -> config -> getCollectionsForSearch ( $ this -> storeName , $ searchTypes ) as $ collection ) { $ collection -> deleteMany ( $ query ) ; } } catch ( \ Exception $ e ) { throw new \ Tripod \ Exceptions \ SearchException ( "Failed to Remove Document with id \n" . print_r ( $ query , true ) , 0 , $ e ) ; } }
Removes a single document from the search index based on the specified resource and context and spec id . If spec id is not specified this method will delete all search documents that match the resource and context .
28,213
public function findImpactedDocuments ( array $ resourcesAndPredicates , $ context ) { $ contextAlias = $ this -> labeller -> uri_to_alias ( $ context ) ; $ specPredicates = array ( ) ; foreach ( $ this -> config -> getSearchDocumentSpecifications ( $ this -> storeName ) as $ spec ) { if ( isset ( $ spec [ _ID_KEY ] ) ) { $ specPredicates [ $ spec [ _ID_KEY ] ] = $ this -> config -> getDefinedPredicatesInSpec ( $ this -> storeName , $ spec [ _ID_KEY ] ) ; } } $ searchDocFilters = array ( ) ; $ resourceFilters = array ( ) ; foreach ( $ resourcesAndPredicates as $ resource => $ resourcePredicates ) { $ resourceAlias = $ this -> labeller -> uri_to_alias ( $ resource ) ; $ id = array ( _ID_RESOURCE => $ resourceAlias , _ID_CONTEXT => $ contextAlias ) ; if ( empty ( $ specPredicates ) || empty ( $ resourcePredicates ) ) { $ resourceFilters [ ] = $ id ; } else { foreach ( $ specPredicates as $ searchDocType => $ predicates ) { if ( array_intersect ( $ resourcePredicates , $ predicates ) ) { if ( ! isset ( $ searchDocFilters [ $ searchDocType ] ) ) { $ searchDocFilters [ $ searchDocType ] = array ( ) ; } $ searchDocFilters [ $ searchDocType ] [ ] = $ id ; } } } } $ searchTypes = array ( ) ; if ( empty ( $ searchDocFilters ) && ! empty ( $ resourceFilters ) ) { $ query = array ( _IMPACT_INDEX => array ( '$in' => $ resourceFilters ) ) ; } else { $ query = array ( ) ; foreach ( $ searchDocFilters as $ searchDocType => $ filters ) { $ query [ ] = array ( _IMPACT_INDEX => array ( '$in' => $ filters ) , '_id.' . _ID_TYPE => $ searchDocType ) ; $ searchTypes [ ] = $ searchDocType ; } if ( ! empty ( $ resourceFilters ) ) { $ query [ ] = array ( _IMPACT_INDEX => array ( '$in' => $ resourceFilters ) ) ; } if ( count ( $ query ) === 1 ) { $ query = $ query [ 0 ] ; } elseif ( count ( $ query ) > 1 ) { $ query = array ( '$or' => $ query ) ; } } if ( empty ( $ query ) ) { return array ( ) ; } $ searchDocs = array ( ) ; foreach ( $ this -> config -> getCollectionsForSearch ( $ this -> storeName , $ searchTypes ) as $ collection ) { $ cursor = $ collection -> find ( $ query , array ( 'projection' => array ( '_id' => true ) ) ) ; foreach ( $ cursor as $ d ) { $ searchDocs [ ] = $ d ; } } return $ searchDocs ; }
Returns the ids of all documents that contain and impact index entry matching the resource and context specified
28,214
public function deleteSearchDocumentsByTypeId ( $ typeId , $ timestamp = null ) { $ searchSpec = $ this -> getSearchDocumentSpecification ( $ typeId ) ; if ( $ searchSpec == null ) { throw new \ Tripod \ Exceptions \ SearchException ( "Could not find a search specification for $typeId" ) ; } $ query = [ '_id.type' => $ typeId ] ; if ( $ timestamp ) { if ( ! ( $ timestamp instanceof \ MongoDB \ BSON \ UTCDateTime ) ) { $ timestamp = new \ MongoDB \ BSON \ UTCDateTime ( $ timestamp ) ; } $ query [ '$or' ] = [ [ \ _CREATED_TS => [ '$lt' => $ timestamp ] ] , [ \ _CREATED_TS => [ '$exists' => false ] ] ] ; } $ deleteResponse = $ this -> getCollectionForSearchSpec ( $ typeId ) -> deleteMany ( $ query ) ; return $ deleteResponse -> getDeletedCount ( ) ; }
Removes all documents from search index based on the specified type id . Here search type id represents to id from mongo tripod config that is converted to _id . type in SEARCH_INDEX_COLLECTION If type id is not specified this method will throw an exception .
28,215
public function dispatch ( $ event ) : void { Assertion :: isObject ( $ event , 'An event should be an object' ) ; $ eventName = get_class ( $ event ) ; $ eventSubscribers = array_merge ( $ this -> subscribedToAllEvents , $ this -> subscribers [ $ eventName ] ?? [ ] ) ; foreach ( $ eventSubscribers as $ eventSubscriber ) { $ eventSubscriber ( $ event ) ; } }
Dispatch a single event .
28,216
public function query ( $ mchBillNo ) { $ params = [ 'appid' => $ this -> merchant -> app_id , 'mch_id' => $ this -> merchant -> merchant_id , 'partner_trade_no' => $ mchBillNo , ] ; return $ this -> request ( self :: API_QUERY , $ params ) ; }
Query MerchantPay .
28,217
public function send ( array $ params ) { $ params [ 'mchid' ] = $ this -> merchant -> merchant_id ; $ params [ 'mch_appid' ] = $ this -> merchant -> app_id ; return $ this -> request ( self :: API_SEND , $ params ) ; }
Send MerchantPay .
28,218
public function check_update ( $ transient ) { if ( empty ( $ transient -> checked ) ) { return $ transient ; } $ remote_version = $ this -> getRemote_version ( ) ; if ( version_compare ( $ this -> current_version , $ remote_version -> new_version , '<' ) ) { $ obj = new \ stdClass ( ) ; $ obj -> slug = $ this -> slug ; $ obj -> new_version = $ remote_version -> new_version ; $ obj -> url = $ remote_version -> url ; $ obj -> plugin = $ this -> plugin_slug ; $ obj -> package = $ remote_version -> package ; $ transient -> response [ $ this -> plugin_slug ] = $ obj ; } return $ transient ; }
Add our self - hosted autoupdate plugin to the filter transient
28,219
public function check_info ( $ false , $ action , $ arg ) { if ( isset ( $ arg -> slug ) && $ arg -> slug === $ this -> slug ) { $ information = $ this -> getRemote_information ( ) ; return $ information ; } return false ; }
Add our self - hosted description to the filter
28,220
public function getRemote_version ( ) { $ params = array ( 'body' => array ( 'action' => 'version' , 'license_user' => $ this -> license_user , 'license_key' => $ this -> license_key , ) , ) ; $ request = wp_remote_post ( $ this -> update_path , $ params ) ; if ( ! is_wp_error ( $ request ) || wp_remote_retrieve_response_code ( $ request ) === 200 ) { return unserialize ( $ request [ 'body' ] ) ; } return false ; }
Return the remote version
28,221
public static function create ( $ file ) { if ( is_string ( $ file ) ) { $ file = new Reader ( $ file ) ; } $ signature = new self ( $ file ) ; $ signature -> addAlgorithm ( new Algorithm \ MD5 ( ) ) ; $ signature -> addAlgorithm ( new Algorithm \ SHA1 ( ) ) ; $ signature -> addAlgorithm ( new Algorithm \ SHA256 ( ) ) ; $ signature -> addAlgorithm ( new Algorithm \ SHA512 ( ) ) ; if ( extension_loaded ( 'openssl' ) ) { $ signature -> addAlgorithm ( new Algorithm \ OpenSSL ( ) ) ; } return $ signature ; }
Creates a new instance with default algorithms registered .
28,222
public function getAlgorithm ( ) { if ( null === $ this -> algorithm ) { $ this -> reader -> seek ( - 4 , SEEK_END ) ; if ( 'GBMB' !== $ this -> reader -> read ( 4 ) ) { throw SignatureException :: createUsingFormat ( 'The archive "%s" is not signed.' , $ this -> reader -> getFile ( ) ) ; } $ this -> reader -> seek ( - 8 , SEEK_END ) ; $ flag = unpack ( 'V' , $ this -> reader -> read ( 4 ) ) ; $ flag = ( int ) $ flag [ 1 ] ; foreach ( $ this -> algorithms as $ algorithm ) { if ( $ flag === $ algorithm -> getFlag ( ) ) { $ this -> algorithm = $ algorithm ; } } if ( null === $ this -> algorithm ) { throw SignatureException :: createUsingFormat ( 'The algorithm for the archive "%s" is not supported.' , $ this -> reader -> getFile ( ) ) ; } } return $ this -> algorithm ; }
Returns the algorithm used for the archive file .
28,223
protected function createSVGArcPath ( $ outerRadius ) { $ color = $ this -> randomCssColor ( ) ; $ ringThickness = $ this -> ringwidth / 2 ; $ startAngle = $ this -> rand ( 20 , 360 ) ; $ stopAngle = $ this -> rand ( 20 , 360 ) ; if ( $ stopAngle < $ startAngle ) { list ( $ startAngle , $ stopAngle ) = array ( $ stopAngle , $ startAngle ) ; } list ( $ xStart , $ yStart ) = $ this -> polarToCartesian ( $ outerRadius , $ startAngle ) ; list ( $ xOuterEnd , $ yOuterEnd ) = $ this -> polarToCartesian ( $ outerRadius , $ stopAngle ) ; $ innerRadius = $ outerRadius - $ ringThickness ; $ SweepFlag = 0 ; $ innerSweepFlag = 1 ; $ largeArcFlag = ( int ) ( $ stopAngle - $ startAngle < 180 ) ; list ( $ xInnerStart , $ yInnerStart ) = $ this -> polarToCartesian ( $ outerRadius - $ ringThickness , $ stopAngle ) ; list ( $ xInnerEnd , $ yInnerEnd ) = $ this -> polarToCartesian ( $ outerRadius - $ ringThickness , $ startAngle ) ; $ fullPath = "<path fill='$color' d=' M $xStart $yStart A $outerRadius $outerRadius 0 $largeArcFlag $SweepFlag $xOuterEnd $yOuterEnd L $xInnerStart $yInnerStart A $innerRadius $innerRadius 0 $largeArcFlag $innerSweepFlag $xInnerEnd $yInnerEnd Z '/>" ; return $ fullPath ; }
Draw a single arc
28,224
protected function randomCssColor ( ) { if ( $ this -> ismono ) { $ alpha = 1 - $ this -> rand ( 0 , 96 ) / 100 ; return "rgba({$this->monocolor[0]}, {$this->monocolor[1]}, {$this->monocolor[2]}, $alpha)" ; } $ r = $ this -> rand ( 0 , 255 ) ; $ g = $ this -> rand ( 0 , 255 ) ; $ b = $ this -> rand ( 0 , 255 ) ; return "rgb($r, $g, $b)" ; }
Create a random valid css color value
28,225
protected function polarToCartesian ( $ radius , $ angleInDegrees ) { $ angleInRadians = $ angleInDegrees * M_PI / 180.0 ; return array ( $ this -> size / 2 + ( $ radius * cos ( $ angleInRadians ) ) , $ this -> size / 2 + ( $ radius * sin ( $ angleInRadians ) ) , ) ; }
Calculate the x y coordinate of a given angle at a given distance from the center
28,226
protected function check ( $ challengeField , $ responseField ) { $ server = $ this -> request -> server ; $ data = array ( 'privatekey' => $ this -> options [ 'private_key' ] , 'remoteip' => $ server -> get ( 'REMOTE_ADDR' ) , 'challenge' => $ challengeField , 'response' => $ responseField ) ; $ curl = curl_init ( $ this -> options [ 'verify_url' ] ) ; curl_setopt ( $ curl , CURLOPT_POST , true ) ; curl_setopt ( $ curl , CURLOPT_RETURNTRANSFER , true ) ; curl_setopt ( $ curl , CURLOPT_CONNECTTIMEOUT , 10 ) ; curl_setopt ( $ curl , CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_0 ) ; curl_setopt ( $ curl , CURLOPT_USERAGENT , 'reCAPTCHA/PHP' ) ; curl_setopt ( $ curl , CURLOPT_POSTFIELDS , $ data ) ; curl_setopt ( $ curl , CURLOPT_HEADER , true ) ; $ response = curl_exec ( $ curl ) ; $ response = explode ( "\r\n\r\n" , $ response , 2 ) ; return ( isset ( $ response [ 1 ] ) && preg_match ( '/true/' , $ response [ 1 ] ) ) ; }
Makes a request to recaptcha service and checks if recaptcha field is valid .
28,227
public function getVersion ( ) { $ cpuinfo = preg_split ( "/\n/" , file_get_contents ( '/proc/cpuinfo' ) ) ; foreach ( $ cpuinfo as $ line ) { if ( preg_match ( '/Revision\s*:\s*([^\s]*)\s*/' , $ line , $ matches ) ) { return hexdec ( $ matches [ 1 ] ) ; } } return 0 ; }
Get RaspberryPi version
28,228
protected function getRealKey ( $ key ) { if ( $ alias = array_search ( $ key , $ this -> aliases , true ) ) { $ key = $ alias ; } return $ key ; }
Return the raw name of attribute .
28,229
public function account ( $ account ) { if ( isset ( $ this -> accounts [ $ account ] ) ) { return $ this -> accounts [ $ account ] ; } if ( ! isset ( $ this [ 'config' ] [ 'account' ] [ $ account ] ) ) { throw new InvalidConfigException ( 'This account not exist.' ) ; } return $ this -> accounts [ $ account ] = new self ( array_merge ( $ this [ 'config' ] -> all ( ) , $ this [ 'config' ] [ 'account' ] [ $ account ] ) ) ; }
Load account .
28,230
public function logConfiguration ( $ config ) { $ config = new Config ( $ config ) ; if ( $ config -> has ( 'account' ) ) { $ config -> forget ( 'account' ) ; } $ keys = [ 'corp_id' , 'secret' , 'suite.suite_id' , 'suite.secret' ] ; foreach ( $ keys as $ key ) { ! $ config -> has ( $ key ) || $ config [ $ key ] = '***' . substr ( $ config [ $ key ] , - 5 ) ; } Log :: debug ( 'Current config:' , $ config -> toArray ( ) ) ; }
Log configuration .
28,231
public function result ( ) { if ( is_null ( $ this -> start_time ) ) { throw new \ Exception ( 'Timer: start method not called !' ) ; } else if ( is_null ( $ this -> end_time ) ) { throw new \ Exception ( 'Timer: stop method not called !' ) ; } if ( $ this -> result == null ) { list ( $ endTimeMicroSeconds , $ endTimeSeconds ) = explode ( ' ' , $ this -> end_time ) ; list ( $ startTimeMicroSeconds , $ startTimeSeconds ) = explode ( ' ' , $ this -> start_time ) ; $ differenceInMilliSeconds = ( ( float ) $ endTimeSeconds - ( float ) $ startTimeSeconds ) * 1000 ; $ this -> result = round ( ( $ differenceInMilliSeconds + ( ( float ) $ endTimeMicroSeconds * 1000 ) ) - ( float ) $ startTimeMicroSeconds * 1000 ) ; } return $ this -> result ; }
Calculate difference between start and end time of event and return in milli - seconds .
28,232
public function microResult ( ) { if ( is_null ( $ this -> start_time ) ) { throw new \ Tripod \ Exceptions \ TimerException ( 'Timer: start method not called !' ) ; } else if ( is_null ( $ this -> end_time ) ) { throw new \ Tripod \ Exceptions \ TimerException ( 'Timer: stop method not called !' ) ; } if ( $ this -> micro_result == null ) { list ( $ endTimeMicroSeconds , $ endTimeSeconds ) = explode ( ' ' , $ this -> end_time ) ; list ( $ startTimeMicroSeconds , $ startTimeSeconds ) = explode ( ' ' , $ this -> start_time ) ; $ differenceInMicroSeconds = ( ( float ) $ endTimeSeconds - ( float ) $ startTimeSeconds ) * 1000000 ; $ this -> micro_result = round ( ( $ differenceInMicroSeconds + ( ( float ) $ endTimeMicroSeconds * 1000000 ) ) - ( float ) $ startTimeMicroSeconds * 1000000 ) ; } return $ this -> micro_result ; }
Calculate difference between start and end time of event and return in micro - seconds .
28,233
public static function fromAttributeValues ( AttributeValue ... $ values ) : self { $ attribs = array_map ( function ( AttributeValue $ value ) { return new AttributeTypeAndValue ( new AttributeType ( $ value -> oid ( ) ) , $ value ) ; } , $ values ) ; return new self ( ... $ attribs ) ; }
Convenience method to initialize RDN from AttributeValue objects .
28,234
public function toString ( ) : string { $ parts = array_map ( function ( AttributeTypeAndValue $ tv ) { return $ tv -> toString ( ) ; } , $ this -> _attribs ) ; return implode ( "+" , $ parts ) ; }
Get name - component string conforming to RFC 2253 .
28,235
public function equals ( RDN $ other ) : bool { if ( count ( $ this ) != count ( $ other ) ) { return false ; } $ attribs1 = $ this -> _attribs ; $ attribs2 = $ other -> _attribs ; if ( count ( $ attribs1 ) > 1 ) { $ attribs1 = self :: fromASN1 ( $ this -> toASN1 ( ) ) -> _attribs ; $ attribs2 = self :: fromASN1 ( $ other -> toASN1 ( ) ) -> _attribs ; } for ( $ i = count ( $ attribs1 ) - 1 ; $ i >= 0 ; -- $ i ) { $ tv1 = $ attribs1 [ $ i ] ; $ tv2 = $ attribs2 [ $ i ] ; if ( ! $ tv1 -> equals ( $ tv2 ) ) { return false ; } } return true ; }
Check whether RDN is semantically equal to other .
28,236
public function allOf ( string $ name ) : array { $ oid = AttributeType :: attrNameToOID ( $ name ) ; $ attribs = array_filter ( $ this -> _attribs , function ( AttributeTypeAndValue $ tv ) use ( $ oid ) { return $ tv -> oid ( ) == $ oid ; } ) ; return array_values ( $ attribs ) ; }
Get all AttributeTypeAndValue objects of the given attribute type .
28,237
public function getData ( ) { try { $ this -> parse ( ) ; $ organized_statements = array ( ) ; foreach ( $ this -> dependencies as $ name => $ preset ) { foreach ( $ preset -> getStatements ( ) as $ type => $ statements ) { if ( ! isset ( $ organized_statements [ $ type ] ) ) { $ organized_statements [ $ type ] = array ( ) ; } foreach ( $ statements as $ statement ) { $ organized_statements [ $ type ] [ ] = $ statement ; } } } foreach ( $ organized_statements as $ type => $ stacks ) { $ organized_statements [ $ type ] = $ preset -> getOrderedStatements ( $ stacks ) ; } } catch ( \ Exception $ e ) { throw $ e ; } return $ organized_statements ; }
Return the parsed and transformed statement array
28,238
protected function isMessage ( $ message ) { if ( is_array ( $ message ) ) { foreach ( $ message as $ element ) { if ( ! is_subclass_of ( $ element , AbstractMessage :: class ) ) { return false ; } } return true ; } return is_subclass_of ( $ message , AbstractMessage :: class ) ; }
Whether response is message .
28,239
protected function buildReply ( $ to , $ from , $ message ) { $ base = [ 'ToUserName' => $ to , 'FromUserName' => $ from , 'CreateTime' => time ( ) , 'MsgType' => is_array ( $ message ) ? current ( $ message ) -> getType ( ) : $ message -> getType ( ) , ] ; $ transformer = new Transformer ( ) ; return XML :: build ( array_merge ( $ base , $ transformer -> transform ( $ message ) ) ) ; }
Build reply XML .
28,240
public function addMockData ( $ data , $ form ) { if ( $ page = SiteTree :: get ( ) -> byID ( $ data [ 'ID' ] ) ) { $ page -> fill ( array ( 'only_empty' => true , 'include_relations' => false , 'download_images' => false ) ) ; $ this -> owner -> response -> addHeader ( 'X-Status' , 'Added mock data' ) ; } return $ this -> owner -> getResponseNegotiator ( ) -> respond ( $ this -> owner -> request ) ; }
A form action that takes the current page ID to populate it with mock data
28,241
public function handle ( $ request , Closure $ next ) { $ request -> setTrustedProxies ( [ '127.0.0.1' , $ request -> server -> get ( 'REMOTE_ADDR' ) ] ) ; return $ next ( $ request ) ; }
use aws elb https
28,242
public function getSSOUrl ( $ loginTicket , $ target , $ agentId = null ) { return $ this -> getLoginUrl ( $ loginTicket , $ target , $ agentId ) ; }
Get the SSO URL .
28,243
public function getLoginUrl ( $ loginTicket , $ target , $ agentId = null ) { $ params = [ 'login_ticket' => $ loginTicket , 'target' => $ target , 'agentid' => $ agentId , ] ; return $ this -> parseJSON ( 'json' , [ self :: API_GET_LOGIN_URL , $ params ] ) ; }
Get the Login URL .
28,244
public function play_turn ( $ turn ) { $ directions = [ 'forward' , 'left' , 'right' ] ; foreach ( $ directions as $ direction ) { foreach ( $ turn -> look ( $ direction ) as $ space ) { if ( $ space -> is_player ( ) ) { $ turn -> shoot ( $ direction ) ; return ; } elseif ( ! $ space -> is_empty ( ) ) { break ; } } } }
Play turn .
28,245
public function drop ( ) { $ this -> curl -> drop ( $ this -> base ) ; $ this -> curl -> createCacheIndex ( $ this -> base , $ this -> createCache ) ; $ this -> dropChain ( ) ; }
Clears all values from the cache .
28,246
public function iAuthenticateAs ( $ user ) { if ( ! isset ( $ this -> users [ $ user ] ) ) { throw new ClientErrorResponseException ( 'User ' . $ user . ' does not exist' ) ; } $ this -> addGuzzleHeader ( 'Authorization' , 'Bearer ' . $ this -> users [ $ user ] ) ; }
Calls specified command
28,247
public function iCallCommandWithBodyText ( $ command , PyStringNode $ string ) { $ this -> executeCommand ( $ command , array ( 'body' => $ this -> addStoredValues ( $ string -> getRaw ( ) ) ) ) ; }
Calls specified command with text
28,248
public function iGetAResponseWithAStatusCodeOf ( $ code ) { $ actual = $ this -> getGuzzleResponse ( ) -> getStatusCode ( ) ; if ( $ actual != $ code ) { throw new ClientErrorResponseException ( 'Actual status code ' . $ actual . ' does not match expected ' . 'status code ' . $ code . ' with message: ' . $ this -> getGuzzleResponse ( ) -> getMessage ( ) ) ; } }
Checks status code in reponse
28,249
public function theResponseBodyMatches ( PyStringNode $ body ) { $ this -> compareValues ( $ this -> getGuzzleResponse ( ) -> getBody ( true ) , $ this -> addStoredValues ( $ body -> getRaw ( ) ) ) ; }
Checks response body matches the following value
28,250
public function theResponseContainsTheFollowingString ( PyStringNode $ string ) { $ response = $ this -> getGuzzleResponse ( ) -> getBody ( true ) ; $ formatted = $ this -> addStoredValues ( $ string -> getRaw ( ) ) ; if ( strpos ( $ response , $ formatted ) === false ) { throw new ClientErrorResponseException ( 'Actual response ' . $ response . ' does not contain ' . 'string ' . $ formatted ) ; } }
Check response contains a specified string
28,251
public function theResponseContainsTheFollowingValue ( TableNode $ table ) { $ data = array ( ) ; $ item = $ this -> getGuzzleResult ( ) ; foreach ( $ table -> getRowsHash ( ) as $ field => $ value ) { $ ref = & $ data ; foreach ( explode ( '[' , $ field ) as $ part ) { $ part = trim ( $ part , ']' ) ; $ ref = & $ ref [ $ part ] ; } $ ref = $ this -> addStoredValues ( $ value ) ; } $ this -> compareValues ( $ item , $ data ) ; }
Check response contains specified values
28,252
public function theResponseContainsTheFollowingValueFromJSON ( PyStringNode $ string ) { $ this -> compareValues ( $ this -> getGuzzleResult ( ) , json_decode ( $ this -> addStoredValues ( $ string -> getRaw ( ) ) , true ) ) ; }
Check response contains specified values from JSON
28,253
protected function castValue ( $ value ) { switch ( $ value ) { case 'false' : return false ; case 'true' : return true ; } if ( is_numeric ( $ value ) ) { $ value = intval ( $ value ) ; } return $ value ; }
Cast value into type depending on content
28,254
protected function addStoredValues ( $ string ) { preg_match_all ( '/\{stored\[(.*?)\]\}/si' , $ string , $ matches ) ; $ length = count ( $ matches [ 0 ] ) ; for ( $ i = 0 ; $ i < $ length ; $ i ++ ) { $ parts = explode ( '][' , $ matches [ 1 ] [ $ i ] ) ; $ value = $ this -> storedResult ; foreach ( $ parts as $ part ) { if ( isset ( $ value [ $ part ] ) ) { $ value = $ value [ $ part ] ; } } $ string = str_replace ( $ matches [ 0 ] [ $ i ] , $ value , $ string ) ; } return $ string ; }
Adds stored values to string
28,255
protected function setReadPreferenceToPrimary ( ) { $ dbReadPref = $ this -> getDatabase ( ) -> __debugInfo ( ) [ 'readPreference' ] ; $ dbPref = $ dbReadPref -> getMode ( ) ; $ dbTagsets = $ dbReadPref -> getTagsets ( ) ; $ this -> originalDbReadPreference = $ this -> db -> __debugInfo ( ) [ 'readPreference' ] -> getMode ( ) ; if ( $ dbPref !== ReadPreference :: RP_PRIMARY ) { $ this -> db = $ this -> db -> withOptions ( array ( 'readPreference' => new ReadPreference ( ReadPreference :: RP_PRIMARY , $ dbTagsets ) ) ) ; } $ collReadPref = $ this -> getCollection ( ) -> __debugInfo ( ) [ 'readPreference' ] ; $ collPref = $ collReadPref -> getMode ( ) ; $ collTagsets = $ collReadPref -> getTagsets ( ) ; $ this -> originalCollectionReadPreference = $ collPref ; if ( $ collPref !== ReadPreference :: RP_PRIMARY ) { $ this -> collection = $ this -> collection -> withOptions ( array ( 'readPreference' => new ReadPreference ( ReadPreference :: RP_PRIMARY , $ collTagsets ) ) ) ; } }
Change the read preferences to RP_PRIMARY Used for a write operation
28,256
protected function resetOriginalReadPreference ( ) { $ dbReadPref = $ this -> db -> __debugInfo ( ) [ 'readPreference' ] ; if ( $ this -> originalDbReadPreference !== $ dbReadPref -> getMode ( ) ) { $ pref = ( isset ( $ this -> originalDbReadPreference ) ? $ this -> originalDbReadPreference : $ this -> readPreference ) ; $ dbTagsets = $ dbReadPref -> getTagsets ( ) ; $ this -> db = $ this -> db -> withOptions ( array ( 'readPreference' => new ReadPreference ( $ pref , $ dbTagsets ) ) ) ; } $ collReadPref = $ this -> getCollection ( ) -> __debugInfo ( ) [ 'readPreference' ] ; if ( $ this -> originalCollectionReadPreference !== $ collReadPref -> getMode ( ) ) { $ pref = ( isset ( $ this -> originalCollectionReadPreference ) ? $ this -> originalCollectionReadPreference : $ this -> readPreference ) ; $ collTagsets = $ collReadPref -> getTagsets ( ) ; $ this -> collection = $ this -> collection -> withOptions ( array ( 'readPreference' => new ReadPreference ( $ pref , $ collTagsets ) ) ) ; } }
Reset the original read preference after changing with setReadPreferenceToPrimary
28,257
protected function validateGraphCardinality ( \ Tripod \ ExtendedGraph $ graph ) { $ config = $ this -> getConfigInstance ( ) ; $ cardinality = $ config -> getCardinality ( $ this -> getStoreName ( ) , $ this -> getPodName ( ) ) ; $ namespaces = $ config -> getNamespaces ( ) ; $ graphSubjects = $ graph -> get_subjects ( ) ; if ( empty ( $ cardinality ) || $ graph -> is_empty ( ) ) { return ; } foreach ( $ cardinality as $ qname => $ cardinalityValue ) { list ( $ namespace , $ predicateName ) = explode ( ':' , $ qname ) ; if ( ! array_key_exists ( $ namespace , $ namespaces ) ) { throw new \ Tripod \ Exceptions \ CardinalityException ( "Namespace '{$namespace}' not defined for qname: {$qname}" ) ; } if ( $ cardinalityValue == 1 ) { foreach ( $ graphSubjects as $ subjectUri ) { $ predicateUri = $ namespaces [ $ namespace ] . $ predicateName ; $ predicateValues = $ graph -> get_subject_property_values ( $ subjectUri , $ predicateUri ) ; if ( count ( $ predicateValues ) > 1 ) { $ v = array ( ) ; foreach ( $ predicateValues as $ predicateValue ) { $ v [ ] = $ predicateValue [ 'value' ] ; } throw new \ Tripod \ Exceptions \ CardinalityException ( "Cardinality failed on {$subjectUri} for '{$qname}' - should only have 1 value and has: " . implode ( ', ' , $ v ) ) ; } } } } }
Ensure that the graph we want to persist has data with valid cardinality .
28,258
private function addOperatorToChange ( & $ changes , $ operator , $ kvp ) { if ( ! isset ( $ changes [ $ operator ] ) || ! is_array ( $ changes [ $ operator ] ) ) { $ changes [ $ operator ] = array ( ) ; } foreach ( $ kvp as $ key => $ value ) { if ( isset ( $ changes [ $ operator ] [ $ key ] ) ) { $ value = array_merge ( $ value , $ changes [ $ operator ] [ $ key ] ) ; } $ changes [ $ operator ] [ $ key ] = $ value ; } }
Helper method to add operator to a set of existing changes ready to be sent to Mongo
28,259
protected function subjectsAndPredicatesOfChangeUrisToAliases ( array $ subjectsAndPredicatesOfChange ) { $ aliases = array ( ) ; foreach ( $ subjectsAndPredicatesOfChange as $ subject => $ predicates ) { $ subjectAlias = $ this -> labeller -> uri_to_alias ( $ subject ) ; $ aliases [ $ subjectAlias ] = array ( ) ; foreach ( $ predicates as $ predicate ) { $ aliases [ $ subjectAlias ] [ ] = $ this -> labeller -> uri_to_alias ( $ predicate ) ; } } return $ aliases ; }
Normalize our subjects and predicates of change to use aliases rather than fq uris
28,260
protected function getDocumentForUpdate ( $ subjectOfChange , $ contextAlias , Array $ cbds ) { foreach ( $ cbds as $ c ) { if ( $ c [ _ID_KEY ] == array ( _ID_RESOURCE => $ this -> labeller -> uri_to_alias ( $ subjectOfChange ) , _ID_CONTEXT => $ contextAlias ) ) { return $ c ; break ; } } return null ; }
Given a set of CBD s return the CBD that matches the Subject of Change
28,261
protected function processSyncOperations ( Array $ subjectsAndPredicatesOfChange , $ contextAlias ) { foreach ( $ this -> getSyncOperations ( ) as $ op ) { $ composite = $ this -> tripod -> getComposite ( $ op ) ; $ opSubjects = $ composite -> getImpactedSubjects ( $ subjectsAndPredicatesOfChange , $ contextAlias ) ; if ( ! empty ( $ opSubjects ) ) { foreach ( $ opSubjects as $ subject ) { $ t = new \ Tripod \ Timer ( ) ; $ t -> start ( ) ; $ subject -> update ( $ subject ) ; $ t -> stop ( ) ; $ this -> timingLog ( MONGO_ON_THE_FLY_MR , array ( "duration" => $ t -> result ( ) , "storeName" => $ subject -> getStoreName ( ) , "podName" => $ subject -> getPodName ( ) , "resourceId" => $ subject -> getResourceId ( ) ) ) ; $ this -> getStat ( ) -> timer ( MONGO_ON_THE_FLY_MR , $ t -> result ( ) ) ; } } } }
Processes each subject synchronously
28,262
protected function queueASyncOperations ( array $ subjectsAndPredicatesOfChange , $ contextAlias ) { $ operations = $ this -> getAsyncOperations ( ) ; if ( ! empty ( $ operations ) ) { $ data = [ 'changes' => $ subjectsAndPredicatesOfChange , 'operations' => $ operations , 'storeName' => $ this -> storeName , 'podName' => $ this -> podName , 'contextAlias' => $ contextAlias , 'statsConfig' => $ this -> getStatsConfig ( ) ] ; if ( isset ( $ this -> queueName ) ) { $ data [ OP_QUEUE ] = $ this -> queueName ; $ queueName = $ this -> queueName ; } else { $ configInstance = $ this -> getConfigInstance ( ) ; $ queueName = $ configInstance :: getDiscoverQueueName ( ) ; } $ this -> getDiscoverImpactedSubjects ( ) -> createJob ( $ data , $ queueName ) ; } }
Adds the operations to the queue to be performed asynchronously
28,263
protected function lockAllDocuments ( $ subjectsOfChange , $ transaction_id , $ contextAlias ) { for ( $ retry = 1 ; $ retry <= $ this -> retriesToGetLock ; $ retry ++ ) { $ originalCBDs = array ( ) ; $ lockedSubjects = array ( ) ; foreach ( $ subjectsOfChange as $ s ) { $ this -> debugLog ( MONGO_LOCK , array ( 'description' => 'Driver::lockAllDocuments - Attempting to get lock' , 'transaction_id' => $ transaction_id , 'subject' => $ s , 'attempt' => $ retry ) ) ; $ document = $ this -> lockSingleDocument ( $ s , $ transaction_id , $ contextAlias ) ; if ( ! empty ( $ document ) ) { $ this -> debugLog ( MONGO_LOCK , array ( 'description' => 'Driver::lockAllDocuments - Got the lock' , 'transaction_id' => $ transaction_id , 'subject' => $ s , 'retry' => $ retry ) ) ; $ this -> getStat ( ) -> increment ( MONGO_LOCK ) ; $ originalCBDs [ ] = $ document ; $ lockedSubjects [ ] = $ s ; } } if ( count ( $ subjectsOfChange ) == count ( $ lockedSubjects ) ) { return $ originalCBDs ; } else { if ( count ( $ lockedSubjects ) ) { $ this -> unlockAllDocuments ( $ transaction_id ) ; } $ this -> debugLog ( MONGO_LOCK , array ( 'description' => "Driver::lockAllDocuments - Unable to lock all " . count ( $ subjectsOfChange ) . " documents, unlocked " . count ( $ lockedSubjects ) . " locked documents" , 'transaction_id' => $ transaction_id , 'documentsToLock' => implode ( "," , $ subjectsOfChange ) , 'documentsLocked' => implode ( "," , $ lockedSubjects ) , 'retry' => $ retry ) ) ; $ n = mt_rand ( 25 , 40 ) ; usleep ( $ n * 1000 ) ; } } $ this -> errorLog ( MONGO_LOCK , array ( 'description' => 'Unable to lock all required documents. Exhausted retries' , 'retries' => $ this -> retriesToGetLock , 'transaction_id' => $ transaction_id , 'subjectsOfChange' => implode ( ", " , $ subjectsOfChange ) , 'mongoDriverError' => $ this -> getLastDBError ( $ this -> getDatabase ( ) ) , ) ) ; return NULL ; }
Attempts to lock all subjects of change in a pass if failed unlocked locked subjects and do a retry of all again .
28,264
public function removeInertLocks ( $ transaction_id , $ reason ) { $ query = array ( _LOCKED_FOR_TRANS => $ transaction_id ) ; $ docs = $ this -> getLocksCollection ( ) -> find ( $ query ) ; if ( $ this -> getLocksCollection ( ) -> count ( $ query ) == 0 ) { return false ; } else { $ auditCollection = $ this -> getAuditManualRollbacksCollection ( ) ; $ auditDocumentId = $ this -> generateIdForNewMongoDocument ( ) ; try { $ documents = array ( ) ; foreach ( $ docs as $ doc ) { $ documents [ ] = $ doc [ _ID_KEY ] [ _ID_RESOURCE ] ; } $ result = $ auditCollection -> insertOne ( array ( _ID_KEY => $ auditDocumentId , 'type' => AUDIT_TYPE_REMOVE_INERT_LOCKS , 'status' => AUDIT_STATUS_IN_PROGRESS , 'reason' => $ reason , 'transaction_id' => $ transaction_id , 'documents' => $ documents , _CREATED_TS => $ this -> getMongoDate ( ) , ) ) ; if ( ! $ result -> isAcknowledged ( ) ) { $ error = $ this -> getLastDBError ( $ this -> getDatabase ( ) ) ; throw new \ Exception ( "Failed to create audit entry with error message- " . $ error [ 'err' ] ) ; } } catch ( \ Exception $ e ) { $ this -> errorLog ( MONGO_LOCK , array ( 'description' => 'Driver::removeInertLocks - failed' , 'transaction_id' => $ transaction_id , 'exception-message' => $ e -> getMessage ( ) ) ) ; throw $ e ; } try { $ this -> unlockAllDocuments ( $ transaction_id ) ; $ result = $ auditCollection -> updateOne ( array ( _ID_KEY => $ auditDocumentId ) , array ( MONGO_OPERATION_SET => array ( "status" => AUDIT_STATUS_COMPLETED , _UPDATED_TS => $ this -> getMongoDate ( ) ) ) ) ; if ( ! $ result -> isAcknowledged ( ) ) { $ error = $ this -> getLastDBError ( $ this -> getDatabase ( ) ) ; throw new \ Exception ( "Failed to update audit entry with error message- " . $ error [ 'err' ] ) ; } } catch ( \ Exception $ e ) { $ logInfo = array ( 'description' => 'Driver::removeInertLocks - failed' , 'transaction_id' => $ transaction_id , 'exception-message' => $ e -> getMessage ( ) ) ; $ result = $ auditCollection -> updateOne ( array ( _ID_KEY => $ auditDocumentId ) , array ( MONGO_OPERATION_SET => array ( "status" => AUDIT_STATUS_ERROR , _UPDATED_TS => $ this -> getMongoDate ( ) , 'error' => $ e -> getMessage ( ) ) ) ) ; if ( ! $ result -> isAcknowledged ( ) ) { $ error = $ this -> getLastDBError ( $ this -> getDatabase ( ) ) ; $ logInfo [ 'additional-error' ] = "Failed to update audit entry with error message- " . $ error [ 'err' ] ; } $ this -> errorLog ( MONGO_LOCK , $ logInfo ) ; throw $ e ; } } return true ; }
Remove locks that are there forever creates a audit entry to keep track who and why removed these locks .
28,265
protected function unlockAllDocuments ( $ transaction_id ) { $ result = $ this -> getLocksCollection ( ) -> deleteMany ( array ( _LOCKED_FOR_TRANS => $ transaction_id ) , array ( 'w' => 1 ) ) ; if ( ! $ result -> isAcknowledged ( ) ) { $ this -> errorLog ( MONGO_LOCK , array ( 'description' => 'Driver::unlockAllDocuments - Failed to unlock documents (transaction_id - ' . $ transaction_id . ')' , 'mongoDriverError' => $ this -> getLastDBError ( $ this -> getLocksDatabase ( ) ) , $ result ) ) ; throw new \ Exception ( "Failed to unlock documents as part of transaction : " . $ transaction_id ) ; } return true ; }
Unlocks documents locked by current transaction
28,266
protected function lockSingleDocument ( $ s , $ transaction_id , $ contextAlias ) { $ countEntriesInLocksCollection = $ this -> getLocksCollection ( ) -> count ( array ( _ID_KEY => array ( _ID_RESOURCE => $ this -> labeller -> uri_to_alias ( $ s ) , _ID_CONTEXT => $ contextAlias ) ) ) ; if ( $ countEntriesInLocksCollection > 0 ) { return false ; } else { try { $ result = $ this -> getLocksCollection ( ) -> insertOne ( array ( _ID_KEY => array ( _ID_RESOURCE => $ this -> labeller -> uri_to_alias ( $ s ) , _ID_CONTEXT => $ contextAlias ) , _LOCKED_FOR_TRANS => $ transaction_id , _LOCKED_FOR_TRANS_TS => \ Tripod \ Mongo \ DateUtil :: getMongoDate ( ) ) , array ( "w" => 1 ) ) ; if ( ! $ result -> isAcknowledged ( ) ) { $ error = $ this -> getLastDBError ( $ this -> getDatabase ( ) ) ; throw new \ Exception ( "Failed to lock document with error message- " . $ error [ 'err' ] ) ; } } catch ( \ Exception $ e ) { $ this -> debugLog ( MONGO_LOCK , array ( 'description' => 'Driver::lockSingleDocument - failed with exception' , 'transaction_id' => $ transaction_id , 'subject' => $ s , 'exception-message' => $ e -> getMessage ( ) ) ) ; return false ; } $ document = $ this -> getCollection ( ) -> findOne ( array ( _ID_KEY => array ( _ID_RESOURCE => $ this -> labeller -> uri_to_alias ( $ s ) , _ID_CONTEXT => $ contextAlias ) ) ) ; if ( empty ( $ document ) ) { try { $ result = $ this -> getCollection ( ) -> insertOne ( array ( _ID_KEY => array ( _ID_RESOURCE => $ this -> labeller -> uri_to_alias ( $ s ) , _ID_CONTEXT => $ contextAlias ) ) , array ( "w" => 1 ) ) ; if ( ! $ result -> isAcknowledged ( ) ) { $ error = $ this -> getLastDBError ( $ this -> getDatabase ( ) ) ; throw new \ Exception ( "Failed to create new document with error message- " . $ error [ 'err' ] ) ; } $ document = $ this -> getCollection ( ) -> findOne ( array ( _ID_KEY => array ( _ID_RESOURCE => $ this -> labeller -> uri_to_alias ( $ s ) , _ID_CONTEXT => $ contextAlias ) ) ) ; } catch ( \ Exception $ e ) { $ this -> errorLog ( MONGO_LOCK , array ( 'description' => 'Driver::lockSingleDocument - failed when creating new document' , 'transaction_id' => $ transaction_id , 'subject' => $ s , 'exception-message' => $ e -> getMessage ( ) , 'mongoDriverError' => $ this -> getDatabase ( ) -> lastError ( ) ) ) ; return false ; } } return $ document ; } }
Lock and return a single document for editing
28,267
protected function applyTransaction ( Array $ transaction ) { $ changes = $ transaction [ 'changes' ] ; $ newCBDs = $ transaction [ 'newCBDs' ] ; $ subjectsOfChange = array ( ) ; foreach ( $ changes as $ c ) { if ( $ c [ 'rdf:type' ] [ VALUE_URI ] == "cs:ChangeSet" ) { array_push ( $ subjectsOfChange , $ c [ 'cs:subjectOfChange' ] [ 'u' ] ) ; } } foreach ( $ subjectsOfChange as $ s ) { foreach ( $ newCBDs as $ n ) { if ( $ n [ _ID_KEY ] [ _ID_RESOURCE ] == $ s ) { $ this -> updateCollection ( array ( _ID_KEY => $ n [ _ID_KEY ] ) , $ n , array ( 'upsert' => true ) ) ; break ; } } } }
Saves a transaction
28,268
protected function getContextAlias ( $ context = null ) { $ contextAlias = $ this -> labeller -> uri_to_alias ( ( empty ( $ context ) ) ? $ this -> defaultContext : $ context ) ; return ( empty ( $ contextAlias ) ) ? $ this -> getConfigInstance ( ) -> getDefaultContextAlias ( ) : $ contextAlias ; }
Returns the context alias curie for the supplied context or default context
28,269
public static function load ( $ class_name = null , $ safe = false ) { if ( empty ( $ class_name ) ) { $ class_name = self :: getInternal ( 'assets-config-class' ) ; } if ( empty ( self :: $ __registry ) ) { self :: $ __registry = array_combine ( self :: $ _requires , array_pad ( array ( ) , count ( self :: $ _requires ) , null ) ) ; } if ( empty ( self :: $ __configurator ) || $ class_name != get_class ( self :: $ __configurator ) ) { if ( $ safe && ! class_exists ( $ class_name ) ) { $ class_name = self :: getInternal ( 'assets-config-class' ) ; } if ( class_exists ( $ class_name ) ) { $ interfaces = class_implements ( $ class_name ) ; $ config_interface = self :: getInternal ( 'assets-config-interface' ) ; if ( in_array ( $ config_interface , $ interfaces ) ) { self :: $ __configurator = new $ class_name ; $ defaults = self :: $ __configurator -> getDefaults ( ) ; if ( self :: _validateConfig ( $ defaults ) ) { self :: $ __registry = $ defaults ; } else { Error :: thrower ( sprintf ( 'Configuration class "%s" do not define all required values!' , $ class_name ) , '\Exception' , __CLASS__ , __METHOD__ , __LINE__ ) ; } } else { Error :: thrower ( sprintf ( 'Configuration class "%s" must implement interface "%s"!' , $ class_name , $ config_interface ) , '\DomainException' , __CLASS__ , __METHOD__ , __LINE__ ) ; } } else { Error :: thrower ( sprintf ( 'Configuration class "%s" not found!' , $ class_name ) , '\DomainException' , __CLASS__ , __METHOD__ , __LINE__ ) ; } } }
Load a config object
28,270
private function validateForumId ( $ id ) { try { $ forum = Forum :: where ( 'id' , $ id ) -> firstOrFail ( ) ; return $ forum ; } catch ( \ Exception $ e ) { return false ; } }
Validates if the forum exists if so returns it .
28,271
public function replayHistory ( EventDispatcher $ eventDispatcher ) : void { $ allEvents = $ this -> storageFacility -> loadAllEvents ( ) ; foreach ( $ allEvents as $ rawEvent ) { $ eventDispatcher -> dispatch ( $ this -> restoreEvent ( $ rawEvent ) ) ; } }
Load all previous events and dispatch them to the provided EventDispatcher .
28,272
public function generate ( ) { $ this -> loadOpenApiFile ( ) ; $ this -> makeOutputDirectory ( ) ; if ( ! is_null ( $ this -> testsOutputPath ) ) { $ this -> makeTestsOutputDirectory ( ) ; } $ this -> parseOperations ( ) ; $ this -> computeInPathParameters ( ) ; $ this -> computeInQueryParameters ( ) ; $ this -> computeBodyParameters ( ) ; $ this -> computeOperationsResponsesMakers ( ) ; $ this -> computeOperationsDefaultResponsesMakers ( ) ; $ this -> makeMainClient ( ) ; $ this -> makeMainException ( ) ; $ this -> makeUnexpectedResponseException ( ) ; if ( ! is_null ( $ this -> testsOutputPath ) ) { $ this -> makeMainClientTest ( ) ; } $ this -> loadTemplates ( ) ; $ this -> writeTemplates ( ) ; }
Run generation of the PHP client library files
28,273
protected function makeMainException ( ) { $ this -> mainExceptionData [ 'uses' ] = [ 'RuntimeException' ] ; $ this -> mainExceptionData [ 'className' ] = 'ApiException' ; $ this -> mainExceptionData [ 'classPhpDocTitle' ] = 'Api Exception class' ; $ this -> mainExceptionData [ 'namespace' ] = $ this -> namespace . '\\Exceptions' ; $ this -> mainExceptionData [ 'extends' ] = 'RuntimeException' ; }
Make the main exception data
28,274
protected function makeUnexpectedResponseException ( ) { $ this -> unexpectedResponseExceptionData [ 'uses' ] = [ 'Exception' , 'Psr\Http\Message\ResponseInterface' ] ; $ this -> unexpectedResponseExceptionData [ 'className' ] = 'UnexpectedResponseException' ; $ this -> unexpectedResponseExceptionData [ 'classPhpDocTitle' ] = 'Api Unexpected Response Exception class' ; $ this -> unexpectedResponseExceptionData [ 'namespace' ] = $ this -> namespace . '\\Exceptions' ; $ this -> unexpectedResponseExceptionData [ 'extends' ] = 'ApiException' ; }
Make the unexpected response exception data
28,275
protected function makeMainClient ( ) { $ this -> mainClientData [ 'uses' ] = [ 'GuzzleHttp\Client as GuzzleClient' ] ; $ this -> mainClientData [ 'managers' ] = [ ] ; $ this -> mainClientData [ 'className' ] = 'ApiClient' ; $ this -> mainClientData [ 'classPhpDocTitle' ] = $ this -> openApiFileContent [ 'info' ] [ 'title' ] . ' client class' ; $ this -> mainClientData [ 'classPhpDocTitle' ] .= $ this -> openApiFileContent [ 'info' ] [ 'version' ] ? ( ' (version ' . $ this -> openApiFileContent [ 'info' ] [ 'version' ] . ')' ) : '' ; $ this -> mainClientData [ 'namespace' ] = $ this -> namespace ; $ this -> mainClientData [ 'info' ] = $ this -> openApiFileContent [ 'info' ] ; $ firstKey = array_keys ( $ this -> openApiFileContent [ 'servers' ] ) [ 0 ] ; $ this -> mainClientData [ 'apiBaseUrl' ] = $ this -> openApiFileContent [ 'servers' ] [ $ firstKey ] [ 'url' ] ; $ this -> mainClientData [ 'useBearerToken' ] = false ; if ( isset ( $ this -> openApiFileContent [ 'security' ] ) ) { foreach ( $ this -> openApiFileContent [ 'security' ] as $ s ) { foreach ( $ s as $ securityRequirement => $ scope ) { if ( ! isset ( $ this -> mainClientData [ 'security' ] ) ) { $ this -> mainClientData [ 'security' ] = [ ] ; } $ this -> mainClientData [ 'security' ] [ $ securityRequirement ] = $ this -> openApiFileContent [ 'components' ] [ 'securitySchemes' ] [ $ securityRequirement ] ; if ( $ this -> openApiFileContent [ 'components' ] [ 'securitySchemes' ] [ $ securityRequirement ] [ 'type' ] == 'http' ) { if ( $ this -> openApiFileContent [ 'components' ] [ 'securitySchemes' ] [ $ securityRequirement ] [ 'scheme' ] == 'bearer' ) { $ this -> mainClientData [ 'useBearerToken' ] = true ; } } if ( $ this -> openApiFileContent [ 'components' ] [ 'securitySchemes' ] [ $ securityRequirement ] [ 'type' ] == 'oauth2' ) { $ this -> mainClientData [ 'useBearerToken' ] = true ; } } } } if ( $ this -> mainClientData [ 'useBearerToken' ] ) { $ this -> mainClientData [ 'uses' ] [ ] = 'Psr\Http\Message\RequestInterface' ; $ this -> mainClientData [ 'uses' ] [ ] = 'GuzzleHttp\HandlerStack' ; $ this -> mainClientData [ 'uses' ] [ ] = 'GuzzleHttp\Handler\CurlHandler' ; $ this -> mainClientData [ 'uses' ] [ ] = 'GuzzleHttp\Middleware' ; } foreach ( $ this -> managersData as $ managerName => $ managerData ) { $ this -> mainClientData [ 'uses' ] [ ] = $ this -> namespace . '\\Managers\\' . $ managerName . 'Manager' ; $ this -> mainClientData [ 'managers' ] [ $ managerName ] = [ 'name' => $ managerName , 'className' => $ managerName . 'Manager' , 'lowerCamelCaseClassName' => lcfirst ( $ managerName . 'Manager' ) ] ; } }
Make the main client data
28,276
protected function computeInPathParameters ( ) { foreach ( $ this -> openApiFileContent [ 'paths' ] as $ path => $ operations ) { foreach ( $ operations as $ httpMethod => $ operation ) { if ( isset ( $ operation [ 'tags' ] ) ) { $ extractedTags = [ ] ; foreach ( $ operation [ 'tags' ] as $ tag ) { $ split = explode ( ':' , $ tag ) ; if ( count ( $ split ) == 2 ) { switch ( $ split [ 0 ] ) { case 'Manager' : if ( ! isset ( $ extractedTags [ 'Managers' ] ) ) { $ extractedTags [ 'Managers' ] = [ ] ; } $ extractedTags [ 'Managers' ] [ ] = $ split [ 1 ] ; break ; case 'Resource' : if ( ! isset ( $ extractedTags [ 'Resources' ] ) ) { $ extractedTags [ 'Resources' ] = [ ] ; } $ extractedTags [ 'Resources' ] [ ] = $ split [ 1 ] ; break ; } } } foreach ( $ extractedTags as $ tagType => $ typeTags ) { foreach ( $ typeTags as $ typeTag ) { switch ( $ tagType ) { case 'Managers' : $ this -> prepareManager ( $ typeTag ) ; $ this -> managersData [ ucfirst ( $ typeTag ) ] [ 'routes' ] [ $ operation [ 'operationId' ] ] [ 'inPathParameters' ] = $ this -> getRouteOperationInPathParameters ( $ operation ) ; break ; case 'Resources' : $ this -> prepareResource ( $ typeTag ) ; $ this -> resourcesData [ ucfirst ( $ typeTag ) ] [ 'routes' ] [ $ operation [ 'operationId' ] ] [ 'inPathParameters' ] = $ this -> getRouteOperationInPathParameters ( $ operation , ucfirst ( $ typeTag ) , $ this -> resourcesData [ ucfirst ( $ typeTag ) ] [ 'properties' ] ) ; break ; } } } } } } }
Add in path parameters map based on resource properties
28,277
protected function computeInQueryParameters ( ) { foreach ( $ this -> openApiFileContent [ 'paths' ] as $ path => $ operations ) { foreach ( $ operations as $ httpMethod => $ operation ) { if ( isset ( $ operation [ 'tags' ] ) ) { $ extractedTags = [ ] ; foreach ( $ operation [ 'tags' ] as $ tag ) { $ split = explode ( ':' , $ tag ) ; if ( count ( $ split ) == 2 ) { switch ( $ split [ 0 ] ) { case 'Manager' : if ( ! isset ( $ extractedTags [ 'Managers' ] ) ) { $ extractedTags [ 'Managers' ] = [ ] ; } $ extractedTags [ 'Managers' ] [ ] = $ split [ 1 ] ; break ; case 'Resource' : if ( ! isset ( $ extractedTags [ 'Resources' ] ) ) { $ extractedTags [ 'Resources' ] = [ ] ; } $ extractedTags [ 'Resources' ] [ ] = $ split [ 1 ] ; break ; } } } foreach ( $ extractedTags as $ tagType => $ typeTags ) { foreach ( $ typeTags as $ typeTag ) { switch ( $ tagType ) { case 'Managers' : $ this -> managersData [ ucfirst ( $ typeTag ) ] [ 'routes' ] [ $ operation [ 'operationId' ] ] [ 'inQueryParameters' ] = $ this -> getRouteOperationInQueryParameters ( $ operation ) ; break ; case 'Resources' : $ this -> resourcesData [ ucfirst ( $ typeTag ) ] [ 'routes' ] [ $ operation [ 'operationId' ] ] [ 'inQueryParameters' ] = $ this -> getRouteOperationInQueryParameters ( $ operation , ucfirst ( $ typeTag ) , $ this -> resourcesData [ ucfirst ( $ typeTag ) ] [ 'properties' ] ) ; break ; } } } } } } }
Add in query parameters data based on resource properties
28,278
protected function computeOperationsDefaultResponsesMakers ( ) { foreach ( $ this -> openApiFileContent [ 'paths' ] as $ path => $ operations ) { foreach ( $ operations as $ httpMethod => $ operation ) { if ( isset ( $ operation [ 'tags' ] ) ) { $ extractedTags = [ ] ; foreach ( $ operation [ 'tags' ] as $ tag ) { $ split = explode ( ':' , $ tag ) ; if ( count ( $ split ) == 2 ) { switch ( $ split [ 0 ] ) { case 'Manager' : if ( ! isset ( $ extractedTags [ 'Managers' ] ) ) { $ extractedTags [ 'Managers' ] = [ ] ; } $ extractedTags [ 'Managers' ] [ ] = $ split [ 1 ] ; break ; case 'Resource' : if ( ! isset ( $ extractedTags [ 'Resources' ] ) ) { $ extractedTags [ 'Resources' ] = [ ] ; } $ extractedTags [ 'Resources' ] [ ] = $ split [ 1 ] ; break ; } } } foreach ( $ extractedTags as $ tagType => $ typeTags ) { foreach ( $ typeTags as $ typeTag ) { switch ( $ tagType ) { case 'Managers' : if ( isset ( $ this -> managersData [ ucfirst ( $ typeTag ) ] [ 'routes' ] [ $ operation [ 'operationId' ] ] [ 'defaultReturn' ] ) ) { $ defaultReturn = $ this -> managersData [ ucfirst ( $ typeTag ) ] [ 'routes' ] [ $ operation [ 'operationId' ] ] [ 'defaultReturn' ] ; if ( ! is_null ( $ defaultReturn ) ) { $ this -> managersData [ ucfirst ( $ typeTag ) ] [ 'routes' ] [ $ operation [ 'operationId' ] ] [ 'defaultResponseMaker' ] = $ this -> computeOperationDefaultResponsesMaker ( 'Managers' , $ typeTag , $ operation , $ defaultReturn ) ; } } break ; case 'Resources' : if ( isset ( $ this -> resourcesData [ ucfirst ( $ typeTag ) ] [ 'routes' ] [ $ operation [ 'operationId' ] ] [ 'defaultReturn' ] ) ) { $ defaultReturn = $ this -> resourcesData [ ucfirst ( $ typeTag ) ] [ 'routes' ] [ $ operation [ 'operationId' ] ] [ 'defaultReturn' ] ; if ( ! is_null ( $ defaultReturn ) ) { $ this -> resourcesData [ ucfirst ( $ typeTag ) ] [ 'routes' ] [ $ operation [ 'operationId' ] ] [ 'defaultResponseMaker' ] = $ this -> computeOperationDefaultResponsesMaker ( 'Resources' , $ typeTag , $ operation , $ defaultReturn ) ; } } break ; } } } } } } }
Add operation default responses makers
28,279
protected function analyzeRouteOperationResponses ( $ path , $ httpMethod , $ operation ) { if ( ! isset ( $ operation [ 'responses' ] ) ) { return null ; } $ resolvedResponsesReferences = [ ] ; foreach ( $ operation [ 'responses' ] as $ httpCode => $ response ) { if ( ! isset ( $ response [ 'content' ] ) ) { continue ; } $ mediaType = array_keys ( $ response [ 'content' ] ) [ 0 ] ; if ( ! isset ( $ response [ 'content' ] [ $ mediaType ] [ 'schema' ] ) ) { continue ; } if ( isset ( $ response [ 'content' ] [ $ mediaType ] [ 'schema' ] [ '$ref' ] ) ) { $ resolved = $ this -> resolveReference ( $ response [ 'content' ] [ $ mediaType ] [ 'schema' ] [ '$ref' ] ) ; $ this -> makeResponseResource ( $ resolved [ 'name' ] , $ resolved [ 'target' ] ) ; $ resolvedResponsesReferences [ $ httpCode ] = $ resolved ; } else { } } if ( count ( $ resolvedResponsesReferences ) == 0 ) { return null ; } return $ resolvedResponsesReferences ; }
Analyze the route operation responses and return te first resolved response reference if exists
28,280
protected function getRouteOperationExceptedResponseCode ( $ operation ) { if ( ! isset ( $ operation [ 'responses' ] ) ) { return null ; } foreach ( $ operation [ 'responses' ] as $ httpCode => $ response ) { return $ httpCode ; } return null ; }
Return the route operation excepted result HTTP code .
28,281
protected function resolveReference ( $ ref ) { if ( strpos ( $ ref , '#/components/' ) !== 0 ) { throw new Exception ( 'Can not resolve this $ref atm (todo) : ' . $ ref ) ; } $ componentPath = str_replace ( '#/components/' , '' , $ ref ) ; $ pathParts = explode ( '/' , $ componentPath ) ; $ target = $ this -> openApiFileContent [ 'components' ] ; $ processingPathParts = [ '#' , 'components' ] ; $ targetName = '' ; foreach ( $ pathParts as $ pathPart ) { $ processingPathParts [ ] = $ pathPart ; if ( ! isset ( $ target [ $ pathPart ] ) ) { throw new Exception ( 'Can not resolve $ref "' . $ ref . '" : Segment not found at "' . implode ( '/' , $ processingPathParts ) . '"' ) ; } $ target = $ target [ $ pathPart ] ; $ targetName = $ pathPart ; } return [ 'name' => $ targetName , 'target' => $ target ] ; }
Resolve OpenAPI reference
28,282
protected function getRouteOperationInPathParameters ( $ operation , $ resourceName = '' , $ resourceProperties = [ ] ) { $ result = [ ] ; if ( isset ( $ operation [ 'parameters' ] ) ) { foreach ( $ operation [ 'parameters' ] as $ p ) { if ( isset ( $ p [ '$ref' ] ) ) { $ parameter = $ this -> resolveReference ( $ p [ '$ref' ] ) [ 'target' ] ; } else { $ parameter = $ p ; } if ( $ parameter [ 'in' ] != 'path' ) { continue ; } $ result [ $ parameter [ 'name' ] ] = null ; if ( count ( $ resourceProperties ) > 0 ) { $ pattern = '/(\w+)Id$/' ; if ( preg_match ( $ pattern , $ parameter [ 'name' ] ) ) { $ resourcePropertyToMatch = ucfirst ( substr ( $ parameter [ 'name' ] , 0 , strlen ( $ parameter [ 'name' ] ) - 2 ) ) ; $ snakeCaseResourcePropertyToMatch = strtolower ( preg_replace ( '/(?<!^)[A-Z]/' , '_$0' , $ resourcePropertyToMatch ) ) ; foreach ( $ resourceProperties as $ resourceProperty ) { if ( $ resourceProperty [ 'name' ] == $ snakeCaseResourcePropertyToMatch ) { $ result [ $ parameter [ 'name' ] ] = '$this->' . $ snakeCaseResourcePropertyToMatch ; } } } } if ( is_null ( $ result [ $ parameter [ 'name' ] ] ) && ( $ resourceName != '' ) ) { $ pattern = '/(\w+)Id$/' ; if ( preg_match ( $ pattern , $ parameter [ 'name' ] ) ) { $ resourcePropertyToMatch = ucfirst ( substr ( $ parameter [ 'name' ] , 0 , strlen ( $ parameter [ 'name' ] ) - 2 ) ) ; if ( $ resourceName == $ resourcePropertyToMatch ) { $ result [ $ parameter [ 'name' ] ] = '$this->id' ; } } } if ( is_null ( $ result [ $ parameter [ 'name' ] ] ) && ( $ resourceName != '' ) ) { $ snakeCaseParameterName = strtolower ( preg_replace ( '/(?<!^)[A-Z]/' , '_$0' , $ parameter [ 'name' ] ) ) ; foreach ( $ resourceProperties as $ resourceProperty ) { if ( $ resourceProperty [ 'name' ] == $ snakeCaseParameterName ) { $ result [ $ parameter [ 'name' ] ] = '$this->' . $ snakeCaseParameterName ; } } } if ( is_null ( $ result [ $ parameter [ 'name' ] ] ) ) { $ result [ $ parameter [ 'name' ] ] = '$' . $ parameter [ 'name' ] ; } } } return $ result ; }
Return a map of the operation path parameters With the path parameter name as the key and the property name as the value if it s resource related
28,283
protected function isParameterExistsInResourceProperties ( $ p , $ resourceName = '' , $ resourceProperties ) { if ( isset ( $ p [ '$ref' ] ) ) { $ parameter = $ this -> resolveReference ( $ p [ '$ref' ] ) [ 'target' ] ; } else { $ parameter = $ p ; } if ( count ( $ resourceProperties ) > 0 ) { $ pattern = '/(\w+)Id$/' ; if ( preg_match ( $ pattern , $ parameter [ 'name' ] ) ) { $ resourcePropertyToMatch = ucfirst ( substr ( $ parameter [ 'name' ] , 0 , strlen ( $ parameter [ 'name' ] ) - 2 ) ) ; $ snakeCaseResourcePropertyToMatch = strtolower ( preg_replace ( '/(?<!^)[A-Z]/' , '_$0' , $ resourcePropertyToMatch ) ) ; foreach ( $ resourceProperties as $ resourceProperty ) { if ( $ resourceProperty [ 'name' ] == $ snakeCaseResourcePropertyToMatch ) { return true ; } } } } $ pattern = '/(\w+)Id$/' ; if ( preg_match ( $ pattern , $ parameter [ 'name' ] ) ) { $ resourcePropertyToMatch = ucfirst ( substr ( $ parameter [ 'name' ] , 0 , strlen ( $ parameter [ 'name' ] ) - 2 ) ) ; if ( $ resourceName == $ resourcePropertyToMatch ) { return true ; } } $ snakeCaseParameterName = strtolower ( preg_replace ( '/(?<!^)[A-Z]/' , '_$0' , $ parameter [ 'name' ] ) ) ; foreach ( $ resourceProperties as $ resourceProperty ) { if ( $ resourceProperty [ 'name' ] == $ snakeCaseParameterName ) { return true ; } } return false ; }
Check if a parameter exists in the resource properties
28,284
protected function writeTemplates ( ) { $ this -> writeManagersTemplates ( ) ; $ this -> writeResourcesTemplates ( ) ; $ this -> writeMainClientTemplate ( ) ; $ this -> writeMainExceptionTemplate ( ) ; $ this -> writeUnexpectedResponseExceptionTemplate ( ) ; if ( ! is_null ( $ this -> testsOutputPath ) ) { $ this -> writeMainClientTestTemplate ( ) ; $ this -> writeManagersTestsTemplates ( ) ; } }
Write templates files
28,285
protected function writeMainExceptionTemplate ( ) { $ data = $ this -> mainExceptionData ; $ filePath = $ this -> outputPath . DIRECTORY_SEPARATOR . 'Exceptions' . DIRECTORY_SEPARATOR . 'ApiException.php' ; if ( ! is_null ( $ this -> outputInterface ) ) { $ this -> outputInterface -> writeln ( '<info>Writing ' . $ filePath . '</info>' ) ; } file_put_contents ( $ filePath , $ this -> mainExceptionTemplate -> render ( $ data ) ) ; }
Write main exception template file
28,286
protected function writeUnexpectedResponseExceptionTemplate ( ) { $ data = $ this -> unexpectedResponseExceptionData ; $ filePath = $ this -> outputPath . DIRECTORY_SEPARATOR . 'Exceptions' . DIRECTORY_SEPARATOR . 'UnexpectedResponseException.php' ; if ( ! is_null ( $ this -> outputInterface ) ) { $ this -> outputInterface -> writeln ( '<info>Writing ' . $ filePath . '</info>' ) ; } file_put_contents ( $ filePath , $ this -> unexpectedResponseExceptionTemplate -> render ( $ data ) ) ; }
Write main unexpected response exception template file
28,287
protected function writeMainClientTemplate ( ) { $ data = $ this -> mainClientData ; $ filePath = $ this -> outputPath . DIRECTORY_SEPARATOR . 'ApiClient.php' ; if ( ! is_null ( $ this -> outputInterface ) ) { $ this -> outputInterface -> writeln ( '<info>Writing ' . $ filePath . '</info>' ) ; } file_put_contents ( $ filePath , $ this -> mainClientTemplate -> render ( $ data ) ) ; }
Write main client template file
28,288
protected function writeManagersTemplates ( ) { foreach ( $ this -> managersData as $ managerName => $ managerData ) { $ data = [ 'className' => $ managerName . 'Manager' , 'classPhpDocTitle' => $ managerName . ' manager class' , 'namespace' => $ this -> namespace . '\Managers' , 'routes' => $ managerData [ 'routes' ] , ] ; if ( isset ( $ managerData [ 'uses' ] ) ) { $ data [ 'uses' ] = $ managerData [ 'uses' ] ; } $ filePath = $ this -> outputPath . DIRECTORY_SEPARATOR . 'Managers' . DIRECTORY_SEPARATOR . $ managerName . 'Manager.php' ; if ( ! is_null ( $ this -> outputInterface ) ) { $ this -> outputInterface -> writeln ( '<info>Writing ' . $ filePath . '</info>' ) ; } file_put_contents ( $ filePath , $ this -> managerTemplate -> render ( $ data ) ) ; } }
Write managers templates files
28,289
protected function writeResourcesTemplates ( ) { foreach ( $ this -> resourcesData as $ resourceName => $ resourceData ) { $ data = [ 'className' => $ resourceName , 'classPhpDocTitle' => $ resourceName . ' resource class' , 'namespace' => $ this -> namespace . '\Resources' , 'routes' => $ resourceData [ 'routes' ] ] ; if ( isset ( $ resourceData [ 'uses' ] ) ) { $ data [ 'uses' ] = $ resourceData [ 'uses' ] ; } if ( isset ( $ resourceData [ 'properties' ] ) ) { $ data [ 'properties' ] = $ resourceData [ 'properties' ] ; } $ filePath = $ this -> outputPath . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . $ resourceName . '.php' ; if ( ! is_null ( $ this -> outputInterface ) ) { $ this -> outputInterface -> writeln ( '<info>Writing ' . $ filePath . '</info>' ) ; } file_put_contents ( $ filePath , $ this -> resourceTemplate -> render ( $ data ) ) ; } }
Write resources templates files
28,290
protected function prepareManager ( $ managerTag ) { if ( isset ( $ this -> managersData [ ucfirst ( $ managerTag ) ] ) ) { return ; } $ this -> managersData [ ucfirst ( $ managerTag ) ] = [ 'className' => ucfirst ( $ managerTag ) , 'routes' => [ ] , 'uses' => [ $ this -> namespace . '\\ApiClient' , $ this -> namespace . '\\Exceptions\\UnexpectedResponseException' ] ] ; }
Prepare new manager data if not already done
28,291
protected function prepareResource ( $ resourceTag ) { if ( isset ( $ this -> resourcesData [ ucfirst ( $ resourceTag ) ] ) ) { return ; } $ this -> resourcesData [ ucfirst ( $ resourceTag ) ] = [ 'className' => ucfirst ( $ resourceTag ) , 'routes' => [ ] , 'uses' => [ $ this -> namespace . '\\ApiClient' , $ this -> namespace . '\\Exceptions\\UnexpectedResponseException' ] ] ; }
Prepare new resource data if not already done
28,292
protected function loadTemplates ( ) { $ loader = new \ Twig_Loader_Filesystem ( dirname ( __FILE__ ) . DIRECTORY_SEPARATOR . 'templates' ) ; $ this -> twigEnv = new Twig_Environment ( $ loader , [ 'cache' => false , 'debug' => true ] ) ; $ this -> twigEnv -> addExtension ( new Twig_Extension_Debug ( ) ) ; $ filter = new \ Twig_Filter ( 'phpdoc' , function ( $ string , $ indentationCount = 0 , $ indentChar = "\t" ) { $ result = str_repeat ( $ indentChar , $ indentationCount ) . '/**' . "\n" ; $ lines = explode ( "\n" , trim ( $ string ) ) ; foreach ( $ lines as $ line ) { $ result .= str_repeat ( $ indentChar , $ indentationCount ) . ' * ' . $ line . "\n" ; } $ result .= str_repeat ( $ indentChar , $ indentationCount ) . ' */' . "\n" ; return $ result ; } ) ; $ this -> twigEnv -> addFilter ( $ filter ) ; $ this -> managerTemplate = $ this -> twigEnv -> load ( 'manager.php.twig' ) ; $ this -> resourceTemplate = $ this -> twigEnv -> load ( 'resource.php.twig' ) ; $ this -> mainClientTemplate = $ this -> twigEnv -> load ( 'mainClient.php.twig' ) ; $ this -> mainExceptionTemplate = $ this -> twigEnv -> load ( 'mainException.php.twig' ) ; $ this -> unexpectedResponseExceptionTemplate = $ this -> twigEnv -> load ( 'unexpectedResponseException.php.twig' ) ; if ( ! is_null ( $ this -> testsOutputPath ) ) { $ this -> mainClientTestTemplate = $ this -> twigEnv -> load ( 'mainClientTest.php.twig' ) ; $ this -> managerTestTemplate = $ this -> twigEnv -> load ( 'managerTest.php.twig' ) ; } }
Load Twig templates filesystem and custom filters
28,293
protected function loadOpenApiFile ( ) { if ( ! is_null ( $ this -> outputInterface ) ) { $ this -> outputInterface -> writeln ( '<info>Loading OpenAPI file : ' . $ this -> openApiFilePath . '</info>' ) ; } $ fileContent = file_get_contents ( $ this -> openApiFilePath ) ; $ jsonException = null ; if ( ! is_null ( $ this -> outputInterface ) ) { $ this -> outputInterface -> writeln ( '<info>Decode JSON from OpenAPI file</info>' ) ; } try { $ this -> openApiFileContent = json_decode ( $ fileContent , true ) ; } catch ( Exception $ e ) { $ jsonException = $ e ; } $ jsonLastError = json_last_error ( ) ; if ( $ jsonLastError != JSON_ERROR_NONE ) { if ( ! is_null ( $ this -> outputInterface ) ) { $ this -> outputInterface -> writeln ( '<info>Can not decode JSON, try YAML</info>' ) ; } $ this -> openApiFileContent = Yaml :: parse ( $ fileContent , Yaml :: PARSE_OBJECT | Yaml :: PARSE_OBJECT_FOR_MAP | Yaml :: PARSE_DATETIME | Yaml :: PARSE_EXCEPTION_ON_INVALID_TYPE ) ; } if ( ! is_null ( $ this -> outputInterface ) ) { $ this -> outputInterface -> writeln ( '<info>File decoded</info>' ) ; } }
Load the OpenAPI file content
28,294
protected function makeOutputDirectory ( ) { if ( file_exists ( $ this -> outputPath ) ) { if ( ! is_null ( $ this -> outputInterface ) ) { $ this -> outputInterface -> writeln ( '<info>Main output directory already created (' . $ this -> outputPath . ')</info>' ) ; } } else { if ( ! is_null ( $ this -> outputInterface ) ) { $ this -> outputInterface -> writeln ( '<info>Making main output directory (' . $ this -> outputPath . ')</info>' ) ; } mkdir ( $ this -> outputPath , 0755 , true ) ; } $ managersDirectoryPath = $ this -> outputPath . DIRECTORY_SEPARATOR . "Managers" ; if ( file_exists ( $ managersDirectoryPath ) ) { if ( ! is_null ( $ this -> outputInterface ) ) { $ this -> outputInterface -> writeln ( '<info>Managers output directory already created (' . $ managersDirectoryPath . ')</info>' ) ; } } else { if ( ! is_null ( $ this -> outputInterface ) ) { $ this -> outputInterface -> writeln ( '<info>Making managers output directory (' . $ managersDirectoryPath . ')</info>' ) ; } mkdir ( $ managersDirectoryPath , 0755 , true ) ; } $ resourcesDirectoryPath = $ this -> outputPath . DIRECTORY_SEPARATOR . "Resources" ; if ( file_exists ( $ resourcesDirectoryPath ) ) { if ( ! is_null ( $ this -> outputInterface ) ) { $ this -> outputInterface -> writeln ( '<info>Resources output directory already created (' . $ resourcesDirectoryPath . ')</info>' ) ; } } else { if ( ! is_null ( $ this -> outputInterface ) ) { $ this -> outputInterface -> writeln ( '<info>Making resources output directory (' . $ resourcesDirectoryPath . ')</info>' ) ; } mkdir ( $ resourcesDirectoryPath , 0755 , true ) ; } $ exceptionsDirectoryPath = $ this -> outputPath . DIRECTORY_SEPARATOR . "Exceptions" ; if ( file_exists ( $ exceptionsDirectoryPath ) ) { if ( ! is_null ( $ this -> outputInterface ) ) { $ this -> outputInterface -> writeln ( '<info>Exceptions output directory already created (' . $ exceptionsDirectoryPath . ')</info>' ) ; } } else { if ( ! is_null ( $ this -> outputInterface ) ) { $ this -> outputInterface -> writeln ( '<info>Making exceptions output directory (' . $ exceptionsDirectoryPath . ')</info>' ) ; } mkdir ( $ exceptionsDirectoryPath , 0755 , true ) ; } }
Make the output directory
28,295
public function create ( $ chatId , $ name , $ owner , array $ userList ) { $ params = [ 'chatid' => $ chatId , 'name' => $ name , 'owner' => $ owner , 'userlist' => $ userList , ] ; return $ this -> parseJSON ( 'json' , [ self :: API_CREATE , $ params ] ) ; }
Create chat .
28,296
public function update ( $ chatId , $ opUser , array $ chatInfo = [ ] ) { $ params = array_merge ( $ chatInfo , [ 'chatid' => $ chatId , 'op_user' => $ opUser , ] ) ; return $ this -> parseJSON ( 'json' , [ self :: API_UPDATE , $ params ] ) ; }
Update chat .
28,297
public function quit ( $ chatId , $ opUser ) { $ params = [ 'chatid' => $ chatId , 'op_user' => $ opUser , ] ; return $ this -> parseJSON ( 'json' , [ self :: API_QUIT , $ params ] ) ; }
Quit chat .
28,298
public function clear ( $ chatId , array $ chat ) { $ params = [ 'chatid' => $ chatId , 'chat' => $ chat , ] ; return $ this -> parseJSON ( 'json' , [ self :: API_CLEAR_NOTIFY , $ params ] ) ; }
Clear chat .
28,299
public function send ( $ type , $ id , $ sender , $ msgType , $ message ) { $ content = ( new Transformer ( $ msgType , $ message ) ) -> transform ( ) ; $ params = array_merge ( [ 'receiver' => [ 'type' => $ type , 'id' => $ id , ] , 'sender' => $ sender , ] , $ content ) ; return $ this -> parseJSON ( 'json' , [ self :: API_SEND , $ params ] ) ; }
Send chat .