idx int64 0 60.3k | question stringlengths 99 4.85k | target stringlengths 5 718 |
|---|---|---|
400 | protected function getRequireFiltersComponent ( SearchQuery $ searchQuery ) { $ fq = array ( ) ; foreach ( $ searchQuery -> require as $ field => $ values ) { $ requireq = array ( ) ; foreach ( $ values as $ value ) { if ( $ value === SearchQuery :: $ missing ) { $ requireq [ ] = "(*:* -{$field}:[* TO *])" ; } elseif ( $ value === SearchQuery :: $ present ) { $ requireq [ ] = "{$field}:[* TO *]" ; } elseif ( $ value instanceof SearchQuery_Range ) { $ start = $ value -> start ; if ( $ start === null ) { $ start = '*' ; } $ end = $ value -> end ; if ( $ end === null ) { $ end = '*' ; } $ requireq [ ] = "$field:[$start TO $end]" ; } else { $ requireq [ ] = $ field . ':"' . $ value . '"' ; } } $ fq [ ] = '+(' . implode ( ' ' , $ requireq ) . ')' ; } return $ fq ; } | Parse all require constraints for inclusion in a filter query |
401 | protected function getExcludeFiltersComponent ( SearchQuery $ searchQuery ) { $ fq = array ( ) ; foreach ( $ searchQuery -> exclude as $ field => $ values ) { $ field = $ this -> sanitiseClassName ( $ field ) ; $ excludeq = [ ] ; $ missing = false ; foreach ( $ values as $ value ) { if ( $ value === SearchQuery :: $ missing ) { $ missing = true ; } elseif ( $ value === SearchQuery :: $ present ) { $ excludeq [ ] = "{$field}:[* TO *]" ; } elseif ( $ value instanceof SearchQuery_Range ) { $ start = $ value -> start ; if ( $ start === null ) { $ start = '*' ; } $ end = $ value -> end ; if ( $ end === null ) { $ end = '*' ; } $ excludeq [ ] = "$field:[$start TO $end]" ; } else { $ excludeq [ ] = $ field . ':"' . $ value . '"' ; } } $ fq [ ] = ( $ missing ? "+{$field}:[* TO *] " : '' ) . '-(' . implode ( ' ' , $ excludeq ) . ')' ; } return $ fq ; } | Parse all exclude constraints for inclusion in a filter query |
402 | public function getFiltersComponent ( SearchQuery $ searchQuery ) { $ criteriaComponent = $ this -> getCriteriaComponent ( $ searchQuery ) ; $ components = array_merge ( $ this -> getRequireFiltersComponent ( $ searchQuery ) , $ this -> getExcludeFiltersComponent ( $ searchQuery ) ) ; if ( $ criteriaComponent !== null ) { $ components [ ] = $ criteriaComponent ; } return $ components ; } | Get all filter conditions for this search |
403 | public function alterQuery ( $ query , $ index ) { if ( $ this -> isFieldFiltered ( '_subsite' , $ query ) || ! $ this -> appliesToEnvironment ( ) ) { return ; } $ subsite = $ this -> currentState ( ) ; $ query -> addFilter ( '_subsite' , [ $ subsite , SearchQuery :: $ missing ] ) ; } | This field has been altered to allow a user to obtain search results for a particular subsite When attempting to do this in project code SearchVariantSubsites kicks and overwrites any filter you ve applied This fix prevents the module from doing this if a filter is applied on the index or the query or if a field is being excluded specifically before being executed . |
404 | public function addClass ( $ class , $ options = array ( ) ) { if ( $ this -> fulltextFields || $ this -> filterFields || $ this -> sortFields ) { throw new Exception ( 'Can\'t add class to Index after fields have already been added' ) ; } $ options = array_merge ( array ( 'include_children' => true ) , $ options ) ; $ this -> classes [ $ class ] = $ options ; } | Add a DataObject subclass whose instances should be included in this index |
405 | public function addFulltextField ( $ field , $ forceType = null , $ extraOptions = array ( ) ) { $ this -> fulltextFields = array_merge ( $ this -> fulltextFields , $ this -> fieldData ( $ field , $ forceType , $ extraOptions ) ) ; } | Add a field that should be fulltext searchable |
406 | public function addFilterField ( $ field , $ forceType = null , $ extraOptions = array ( ) ) { $ this -> filterFields = array_merge ( $ this -> filterFields , $ this -> fieldData ( $ field , $ forceType , $ extraOptions ) ) ; } | Add a field that should be filterable |
407 | public function addSortField ( $ field , $ forceType = null , $ extraOptions = array ( ) ) { $ this -> sortFields = array_merge ( $ this -> sortFields , $ this -> fieldData ( $ field , $ forceType , $ extraOptions ) ) ; } | Add a field that should be sortable |
408 | public function addAllFulltextFields ( $ includeSubclasses = true ) { foreach ( $ this -> getClasses ( ) as $ class => $ options ) { $ classHierarchy = SearchIntrospection :: hierarchy ( $ class , $ includeSubclasses , true ) ; foreach ( $ classHierarchy as $ dataClass ) { $ fields = DataObject :: getSchema ( ) -> databaseFields ( $ dataClass ) ; foreach ( $ fields as $ field => $ type ) { list ( $ type , $ args ) = ClassInfo :: parse_class_spec ( $ type ) ; $ object = Injector :: inst ( ) -> get ( $ type , false , [ 'Name' => 'test' ] ) ; if ( $ object instanceof DBString ) { $ this -> addFulltextField ( $ field ) ; } } } } } | Add all database - backed text fields as fulltext searchable fields . |
409 | public function variantStateExcluded ( $ state ) { foreach ( $ this -> excludedVariantStates as $ excludedstate ) { $ matches = true ; foreach ( $ excludedstate as $ variant => $ variantstate ) { if ( ! isset ( $ state [ $ variant ] ) || $ state [ $ variant ] != $ variantstate ) { $ matches = false ; break ; } } if ( $ matches ) { return true ; } } } | Returns true if some variant state should be ignored |
410 | public function getDerivedFields ( ) { if ( $ this -> derivedFields === null ) { $ this -> derivedFields = array ( ) ; foreach ( $ this -> getFieldsIterator ( ) as $ name => $ field ) { if ( count ( $ field [ 'lookup_chain' ] ) < 2 ) { continue ; } $ key = sha1 ( $ field [ 'base' ] . serialize ( $ field [ 'lookup_chain' ] ) ) ; $ fieldname = "{$field['class']}:{$field['field']}" ; if ( isset ( $ this -> derivedFields [ $ key ] ) ) { $ this -> derivedFields [ $ key ] [ 'fields' ] [ $ fieldname ] = $ fieldname ; SearchIntrospection :: add_unique_by_ancestor ( $ this -> derivedFields [ 'classes' ] , $ field [ 'class' ] ) ; } else { $ chain = array_reverse ( $ field [ 'lookup_chain' ] ) ; array_shift ( $ chain ) ; $ this -> derivedFields [ $ key ] = array ( 'base' => $ field [ 'base' ] , 'fields' => array ( $ fieldname => $ fieldname ) , 'classes' => array ( $ field [ 'class' ] ) , 'chain' => $ chain ) ; } } } return $ this -> derivedFields ; } | Returns an array where each member is all the fields and the classes that are at the end of some specific lookup chain from one of the base classes |
411 | public static function handle_manipulation ( $ manipulation ) { if ( ! static :: config ( ) -> get ( 'enabled' ) ) { return ; } foreach ( $ manipulation as $ table => $ details ) { if ( ! isset ( $ manipulation [ $ table ] [ 'class' ] ) ) { $ manipulation [ $ table ] [ 'class' ] = DataObject :: getSchema ( ) -> tableClass ( $ table ) ; } $ manipulation [ $ table ] [ 'state' ] = array ( ) ; } SearchVariant :: call ( 'extractManipulationState' , $ manipulation ) ; $ writes = array ( ) ; foreach ( $ manipulation as $ table => $ details ) { if ( ! isset ( $ details [ 'id' ] ) ) { continue ; } $ id = $ details [ 'id' ] ; $ state = $ details [ 'state' ] ; $ class = $ details [ 'class' ] ; $ command = $ details [ 'command' ] ; $ fields = isset ( $ details [ 'fields' ] ) ? $ details [ 'fields' ] : array ( ) ; $ base = DataObject :: getSchema ( ) -> baseDataClass ( $ class ) ; $ key = "$id:$base:" . serialize ( $ state ) ; $ statefulids = array ( array ( 'id' => $ id , 'state' => $ state ) ) ; if ( ! isset ( $ writes [ $ key ] ) ) { $ writes [ $ key ] = array ( 'base' => $ base , 'class' => $ class , 'id' => $ id , 'statefulids' => $ statefulids , 'command' => $ command , 'fields' => array ( ) ) ; } elseif ( is_subclass_of ( $ class , $ writes [ $ key ] [ 'class' ] ) ) { $ writes [ $ key ] [ 'class' ] = $ class ; } foreach ( $ fields as $ field => $ value ) { $ writes [ $ key ] [ 'fields' ] [ "$class:$field" ] = $ value ; } } foreach ( array_keys ( $ writes ) as $ key ) { if ( $ writes [ $ key ] [ 'command' ] !== 'delete' && empty ( $ writes [ $ key ] [ 'fields' ] ) ) { unset ( $ writes [ $ key ] ) ; } } SearchVariant :: call ( 'extractManipulationWriteState' , $ writes ) ; static :: process_writes ( $ writes ) ; } | Called by the ProxyDBExtension database connector with every manipulation made against the database . |
412 | public static function process_writes ( $ writes ) { foreach ( $ writes as $ write ) { foreach ( FullTextSearch :: get_indexes ( ) as $ index => $ instance ) { if ( SearchIntrospection :: is_subclass_of ( $ write [ 'class' ] , $ instance -> dependancyList ) ) { $ dirtyids = $ instance -> getDirtyIDs ( $ write [ 'class' ] , $ write [ 'id' ] , $ write [ 'statefulids' ] , $ write [ 'fields' ] ) ; foreach ( $ dirtyids as $ dirtyclass => $ ids ) { if ( $ ids ) { if ( ! self :: $ processor ) { self :: $ processor = Injector :: inst ( ) -> create ( SearchUpdateImmediateProcessor :: class ) ; } self :: $ processor -> addDirtyIDs ( $ dirtyclass , $ ids , $ index ) ; } } } } } if ( self :: $ processor && ! self :: $ registered && self :: config ( ) -> get ( 'flush_on_shutdown' ) ) { register_shutdown_function ( array ( SearchUpdater :: class , "flush_dirty_indexes" ) ) ; self :: $ registered = true ; } } | Send updates to the current search processor for execution |
413 | public static function hierarchy ( $ class , $ includeSubclasses = true , $ dataOnly = false ) { $ key = "$class!" . ( $ includeSubclasses ? 'sc' : 'an' ) . '!' . ( $ dataOnly ? 'do' : 'al' ) ; if ( ! isset ( self :: $ hierarchy [ $ key ] ) ) { $ classes = array_values ( ClassInfo :: ancestry ( $ class ) ) ; if ( $ includeSubclasses ) { $ classes = array_unique ( array_merge ( $ classes , array_values ( ClassInfo :: subclassesFor ( $ class ) ) ) ) ; } $ idx = array_search ( DataObject :: class , $ classes ) ; if ( $ idx !== false ) { array_splice ( $ classes , 0 , $ idx + 1 ) ; } if ( $ dataOnly ) { foreach ( $ classes as $ i => $ class ) { if ( ! DataObject :: getSchema ( ) -> classHasTable ( $ class ) ) { unset ( $ classes [ $ i ] ) ; } } } self :: $ hierarchy [ $ key ] = $ classes ; } return self :: $ hierarchy [ $ key ] ; } | Get all the classes involved in a DataObject hierarchy - both super and optionally subclasses |
414 | public static function add_unique_by_ancestor ( & $ list , $ class ) { if ( self :: is_subclass_of ( $ class , $ list ) ) { return ; } $ children = ClassInfo :: subclassesFor ( $ class ) ; $ list = array_diff ( $ list , $ children ) ; $ list [ ] = $ class ; } | Add classes to list keeping only the parent when parent & child are both in list after add |
415 | public static function create ( $ target , $ value = null , $ comparison = null , AbstractSearchQueryWriter $ searchQueryWriter = null ) { return new SearchCriteria ( $ target , $ value , $ comparison , $ searchQueryWriter ) ; } | Static create method provided so that you can perform method chaining . |
416 | public static function force_index_list ( ) { $ indexes = func_get_args ( ) ; if ( ! $ indexes ) { self :: get_indexes ( null , true ) ; return ; } if ( is_array ( $ indexes [ 0 ] ) ) { $ indexes = $ indexes [ 0 ] ; } self :: $ all_indexes = array ( ) ; self :: $ indexes_by_subclass = array ( ) ; foreach ( $ indexes as $ class => $ index ) { if ( is_string ( $ index ) ) { $ class = $ index ; $ index = singleton ( $ class ) ; } if ( is_numeric ( $ class ) ) { $ class = get_class ( $ index ) ; } self :: $ all_indexes [ $ class ] = $ index ; } } | Sometimes like when in tests you want to restrain the actual indexes to a subset |
417 | protected function getStreamHandler ( FormatterInterface $ formatter , $ stream , $ level = Logger :: DEBUG , $ bubble = true ) { $ stream = Director :: is_cli ( ) ? $ stream : 'php://output' ; $ handler = Injector :: inst ( ) -> createWithArgs ( StreamHandler :: class , array ( $ stream , $ level , $ bubble ) ) ; $ handler -> setFormatter ( $ formatter ) ; return $ handler ; } | Generate a handler for the given stream |
418 | protected function getFormatter ( ) { $ format = LineFormatter :: SIMPLE_FORMAT ; if ( ! Director :: is_cli ( ) ) { $ format = "<p>$format</p>" ; } return Injector :: inst ( ) -> createWithArgs ( LineFormatter :: class , array ( $ format ) ) ; } | Gets a formatter for standard output |
419 | protected function prepareIndexes ( ) { $ originalState = SearchVariant :: current_state ( ) ; $ dirtyIndexes = array ( ) ; $ dirty = $ this -> getSource ( ) ; $ indexes = FullTextSearch :: get_indexes ( ) ; foreach ( $ dirty as $ base => $ statefulids ) { if ( ! $ statefulids ) { continue ; } foreach ( $ statefulids as $ statefulid ) { $ state = $ statefulid [ 'state' ] ; $ ids = $ statefulid [ 'ids' ] ; SearchVariant :: activate_state ( $ state ) ; $ objs = DataObject :: get ( $ base ) -> byIDs ( array_keys ( $ ids ) ) ; foreach ( $ objs as $ obj ) { foreach ( $ ids [ $ obj -> ID ] as $ index ) { if ( ! $ indexes [ $ index ] -> variantStateExcluded ( $ state ) ) { $ indexes [ $ index ] -> add ( $ obj ) ; $ dirtyIndexes [ $ index ] = $ indexes [ $ index ] ; } } unset ( $ ids [ $ obj -> ID ] ) ; } foreach ( $ ids as $ id => $ fromindexes ) { foreach ( $ fromindexes as $ index ) { if ( ! $ indexes [ $ index ] -> variantStateExcluded ( $ state ) ) { $ indexes [ $ index ] -> delete ( $ base , $ id , $ state ) ; $ dirtyIndexes [ $ index ] = $ indexes [ $ index ] ; } } } } } SearchVariant :: activate_state ( $ originalState ) ; return $ dirtyIndexes ; } | Generates the list of indexes to process for the dirty items |
420 | public function process ( ) { $ indexes = $ this -> prepareIndexes ( ) ; foreach ( $ indexes as $ index ) { if ( ! $ this -> commitIndex ( $ index ) ) { return false ; } } return true ; } | Process all indexes returning true if successful |
421 | public static function queue ( $ dirty = true , $ startAfter = null ) { $ commit = Injector :: inst ( ) -> create ( __CLASS__ ) ; $ id = singleton ( QueuedJobService :: class ) -> queueJob ( $ commit , $ startAfter ) ; if ( $ dirty ) { $ indexes = FullTextSearch :: get_indexes ( ) ; static :: $ dirty_indexes = array_keys ( $ indexes ) ; } return $ id ; } | This method is invoked once indexes with dirty ids have been updapted and a commit is necessary |
422 | public function getAllIndexes ( ) { if ( empty ( $ this -> indexes ) ) { $ indexes = FullTextSearch :: get_indexes ( ) ; $ this -> indexes = array_keys ( $ indexes ) ; } return $ this -> indexes ; } | Get the list of index names we should process |
423 | protected function discardJob ( ) { $ this -> skipped = true ; if ( empty ( static :: $ dirty_indexes ) ) { $ this -> addMessage ( "Indexing already completed this request: Discarding this job" ) ; return ; } $ cooldown = Config :: inst ( ) -> get ( __CLASS__ , 'cooldown' ) ; $ now = new DateTime ( DBDatetime :: now ( ) -> getValue ( ) ) ; $ now -> add ( new DateInterval ( 'PT' . $ cooldown . 'S' ) ) ; $ runat = $ now -> Format ( 'Y-m-d H:i:s' ) ; $ this -> addMessage ( "Indexing already run this request, but incomplete. Re-scheduling for {$runat}" ) ; static :: queue ( false , $ runat ) ; } | Abort this job potentially rescheduling a replacement if there is still work to do |
424 | protected function commitIndex ( $ index ) { $ name = get_class ( $ index ) ; if ( in_array ( $ name , $ this -> completed ) ) { $ this -> addMessage ( "Skipping already comitted index {$name}" ) ; return ; } $ this -> addMessage ( "Committing index {$name}" ) ; $ index -> getService ( ) -> commit ( false , false , false ) ; $ this -> addMessage ( "Committing index {$name} was successful" ) ; if ( in_array ( $ name , static :: $ dirty_indexes ) ) { static :: $ dirty_indexes = array_diff ( static :: $ dirty_indexes , array ( $ name ) ) ; } $ this -> completed [ ] = $ name ; } | Commits a specific index |
425 | protected static function isNodeError ( string $ error ) : bool { $ error = json_decode ( $ error , true ) ; return ( $ error [ '__rialto_error__' ] ?? false ) === true ; } | Determines if the string contains a Node error . |
426 | protected function setTraceAndGetMessage ( $ error , bool $ appendStackTraceToMessage = false ) : string { $ error = is_string ( $ error ) ? json_decode ( $ error , true ) : $ error ; $ this -> originalTrace = $ error [ 'stack' ] ?? null ; $ message = $ error [ 'message' ] ; if ( $ appendStackTraceToMessage ) { $ message .= "\n\n" . $ error [ 'stack' ] ; } return $ message ; } | Set the original trace and return the message . |
427 | protected function consolidateOptions ( array $ implementationOptions , array $ userOptions ) : array { $ userOptions = array_diff_key ( $ userOptions , array_flip ( $ this -> forbiddenOptions ) ) ; return array_merge ( $ implementationOptions , $ userOptions ) ; } | Clean the user options . |
428 | protected function logProcessStandardStreams ( ) : void { if ( ! empty ( $ output = $ this -> process -> getIncrementalOutput ( ) ) ) { $ this -> logger -> notice ( 'Received data on stdout: {output}' , [ 'pid' => $ this -> processPid , 'stream' => 'stdout' , 'output' => $ output , ] ) ; } if ( ! empty ( $ errorOutput = $ this -> process -> getIncrementalErrorOutput ( ) ) ) { $ this -> logger -> error ( 'Received data on stderr: {output}' , [ 'pid' => $ this -> processPid , 'stream' => 'stderr' , 'output' => $ errorOutput , ] ) ; } } | Log data from the process standard streams . |
429 | protected function applyOptions ( array $ options ) : void { $ this -> logger -> info ( 'Applying options...' , [ 'options' => $ options ] ) ; $ this -> options = array_merge ( $ this -> options , $ options ) ; $ this -> logger -> debug ( 'Options applied and merged with defaults' , [ 'options' => $ this -> options ] ) ; } | Apply the options . |
430 | protected function getProcessScriptPath ( ) : string { static $ scriptPath = null ; if ( $ scriptPath !== null ) { return $ scriptPath ; } $ scriptPath = __DIR__ . '/node-process/serve.js' ; $ process = new SymfonyProcess ( [ $ this -> options [ 'executable_path' ] , '-e' , "process.stdout.write(require.resolve('@nesk/rialto/src/node-process/serve.js'))" , ] ) ; $ exitCode = $ process -> run ( ) ; if ( $ exitCode === 0 ) { $ scriptPath = $ process -> getOutput ( ) ; } return $ scriptPath ; } | Return the script path of the Node process . |
431 | protected function createNewProcess ( string $ connectionDelegatePath ) : SymfonyProcess { $ realConnectionDelegatePath = realpath ( $ connectionDelegatePath ) ; if ( $ realConnectionDelegatePath === false ) { throw new RuntimeException ( "Cannot find file or directory '$connectionDelegatePath'." ) ; } $ processOptions = array_diff_key ( $ this -> options , array_flip ( self :: USELESS_OPTIONS_FOR_PROCESS ) ) ; return new SymfonyProcess ( array_merge ( [ $ this -> options [ 'executable_path' ] ] , $ this -> options [ 'debug' ] ? [ '--inspect' ] : [ ] , [ $ this -> getProcessScriptPath ( ) ] , [ $ realConnectionDelegatePath ] , [ json_encode ( ( object ) $ processOptions ) ] ) ) ; } | Create a new Node process . |
432 | protected function startProcess ( SymfonyProcess $ process ) : int { $ this -> logger -> info ( 'Starting process with command line: {commandline}' , [ 'commandline' => $ process -> getCommandLine ( ) , ] ) ; $ process -> start ( ) ; $ pid = $ process -> getPid ( ) ; $ this -> logger -> info ( 'Process started with PID {pid}' , [ 'pid' => $ pid ] ) ; return $ pid ; } | Start the Node process . |
433 | protected function checkProcessStatus ( ) : void { $ this -> logProcessStandardStreams ( ) ; $ process = $ this -> process ; if ( ! empty ( $ process -> getErrorOutput ( ) ) ) { if ( IdleTimeoutException :: exceptionApplies ( $ process ) ) { throw new IdleTimeoutException ( $ this -> options [ 'idle_timeout' ] , new NodeFatalException ( $ process , $ this -> options [ 'debug' ] ) ) ; } else if ( NodeFatalException :: exceptionApplies ( $ process ) ) { throw new NodeFatalException ( $ process , $ this -> options [ 'debug' ] ) ; } elseif ( $ process -> isTerminated ( ) && ! $ process -> isSuccessful ( ) ) { throw new ProcessFailedException ( $ process ) ; } } if ( $ process -> isTerminated ( ) ) { throw new Exceptions \ ProcessUnexpectedlyTerminatedException ( $ process ) ; } } | Check if the process is still running without errors . |
434 | protected function serverPort ( ) : int { if ( $ this -> serverPort !== null ) { return $ this -> serverPort ; } $ iterator = $ this -> process -> getIterator ( SymfonyProcess :: ITER_SKIP_ERR | SymfonyProcess :: ITER_KEEP_OUTPUT ) ; foreach ( $ iterator as $ data ) { return $ this -> serverPort = ( int ) $ data ; } $ this -> checkProcessStatus ( ) ; } | Return the port of the server . |
435 | public function executeInstruction ( Instruction $ instruction , bool $ instructionShouldBeLogged = true ) { $ this -> checkProcessStatus ( ) ; $ serializedInstruction = json_encode ( $ instruction ) ; if ( $ instructionShouldBeLogged ) { $ this -> logger -> debug ( 'Sending an instruction to the port {port}...' , [ 'pid' => $ this -> processPid , 'port' => $ this -> serverPort ( ) , 'instruction' => json_decode ( $ serializedInstruction , true ) , ] ) ; } $ this -> client -> selectWrite ( 1 ) ; $ this -> client -> write ( $ serializedInstruction ) ; $ value = $ this -> readNextProcessValue ( $ instructionShouldBeLogged ) ; if ( $ value === null ) { $ this -> checkProcessStatus ( ) ; } return $ value ; } | Send an instruction to the process for execution . |
436 | protected function readNextProcessValue ( bool $ valueShouldBeLogged = true ) { $ readTimeout = $ this -> options [ 'read_timeout' ] ; $ payload = '' ; try { $ startTimestamp = microtime ( true ) ; do { $ this -> client -> selectRead ( $ readTimeout ) ; $ packet = $ this -> client -> read ( static :: SOCKET_PACKET_SIZE ) ; $ chunksLeft = ( int ) substr ( $ packet , 0 , static :: SOCKET_HEADER_SIZE ) ; $ chunk = substr ( $ packet , static :: SOCKET_HEADER_SIZE ) ; $ payload .= $ chunk ; if ( $ chunksLeft > 0 ) { usleep ( self :: SOCKET_NEXT_CHUNK_DELAY * 1000 ) ; } } while ( $ chunksLeft > 0 ) ; } catch ( SocketException $ exception ) { $ this -> waitForProcessTermination ( ) ; $ this -> checkProcessStatus ( ) ; preg_match ( '/\(([A-Z_]+?)\)$/' , $ exception -> getMessage ( ) , $ socketErrorMatches ) ; $ socketErrorCode = constant ( $ socketErrorMatches [ 1 ] ) ; $ elapsedTime = microtime ( true ) - $ startTimestamp ; if ( $ socketErrorCode === SOCKET_EAGAIN && $ readTimeout !== null && $ elapsedTime >= $ readTimeout ) { throw new Exceptions \ ReadSocketTimeoutException ( $ readTimeout , $ exception ) ; } throw $ exception ; } $ this -> logProcessStandardStreams ( ) ; [ 'logs' => $ logs , 'value' => $ value ] = json_decode ( base64_decode ( $ payload ) , true ) ; foreach ( $ logs ? : [ ] as $ log ) { $ level = ( new \ ReflectionClass ( LogLevel :: class ) ) -> getConstant ( $ log [ 'level' ] ) ; $ messageContainsLineBreaks = strstr ( $ log [ 'message' ] , PHP_EOL ) !== false ; $ formattedMessage = $ messageContainsLineBreaks ? "\n{log}\n" : '{log}' ; $ this -> logger -> log ( $ level , "Received a $log[origin] log: $formattedMessage" , [ 'pid' => $ this -> processPid , 'port' => $ this -> serverPort ( ) , 'log' => $ log [ 'message' ] , ] ) ; } $ value = $ this -> unserialize ( $ value ) ; if ( $ valueShouldBeLogged ) { $ this -> logger -> debug ( 'Received data from the port {port}...' , [ 'pid' => $ this -> processPid , 'port' => $ this -> serverPort ( ) , 'data' => $ value , ] ) ; } if ( $ value instanceof NodeException ) { throw $ value ; } return $ value ; } | Read the next value written by the process . |
437 | public static function create ( ... $ arguments ) { trigger_error ( __METHOD__ . '() has been deprecated and will be removed from v2.' , E_USER_DEPRECATED ) ; if ( isset ( $ arguments [ 0 ] ) && is_string ( $ arguments [ 0 ] ) ) { return new static ( [ ] , $ arguments [ 0 ] , $ arguments [ 1 ] ?? [ ] ) ; } return new static ( ... $ arguments ) ; } | Create a new JS function . |
438 | public function call ( string $ name , ... $ arguments ) : self { $ this -> type = self :: TYPE_CALL ; $ this -> name = $ name ; $ this -> setValue ( $ arguments , $ this -> type ) ; return $ this ; } | Define a method call . |
439 | public function get ( string $ name ) : self { $ this -> type = self :: TYPE_GET ; $ this -> name = $ name ; $ this -> setValue ( null , $ this -> type ) ; return $ this ; } | Define a getter . |
440 | public function set ( string $ name , $ value ) : self { $ this -> type = self :: TYPE_SET ; $ this -> name = $ name ; $ this -> setValue ( $ value , $ this -> type ) ; return $ this ; } | Define a setter . |
441 | protected function setValue ( $ value , string $ type ) { $ this -> value = $ type !== self :: TYPE_CALL ? $ this -> validateValue ( $ value ) : array_map ( function ( $ value ) { return $ this -> validateValue ( $ value ) ; } , $ value ) ; } | Set the instruction value . |
442 | public static function exceptionApplies ( Process $ process ) : bool { if ( Node \ FatalException :: exceptionApplies ( $ process ) ) { $ error = json_decode ( $ process -> getErrorOutput ( ) , true ) ; return $ error [ 'message' ] === 'The idle timeout has been reached.' ; } return false ; } | Check if the exception can be applied to the process . |
443 | public function setProcessSupervisor ( ProcessSupervisor $ processSupervisor ) : void { if ( $ this -> processSupervisor !== null ) { throw new RuntimeException ( 'The process supervisor has already been set.' ) ; } $ this -> processSupervisor = $ processSupervisor ; } | Set the process supervisor . |
444 | protected function proxyAction ( string $ actionType , string $ name , $ value = null ) { switch ( $ actionType ) { case Instruction :: TYPE_CALL : $ value = $ value ?? [ ] ; $ instruction = Instruction :: withCall ( $ name , ... $ value ) ; break ; case Instruction :: TYPE_GET : $ instruction = Instruction :: withGet ( $ name ) ; break ; case Instruction :: TYPE_SET : $ instruction = Instruction :: withSet ( $ name , $ value ) ; break ; } $ identifiesResource = $ this instanceof ShouldIdentifyResource ; $ instruction -> linkToResource ( $ identifiesResource ? $ this : null ) ; if ( $ this -> catchInstructionErrors ) { $ instruction -> shouldCatchErrors ( true ) ; } return $ this -> getProcessSupervisor ( ) -> executeInstruction ( $ instruction ) ; } | Proxy an action . |
445 | public function setResourceIdentity ( ResourceIdentity $ identity ) : void { if ( $ this -> resourceIdentity !== null ) { throw new RuntimeException ( 'The resource identity has already been set.' ) ; } $ this -> resourceIdentity = $ identity ; } | Set the identity of the resource . |
446 | protected function unserialize ( $ value ) { if ( ! is_array ( $ value ) ) { return $ value ; } else { if ( ( $ value [ '__rialto_error__' ] ?? false ) === true ) { return new Exception ( $ value , $ this -> options [ 'debug' ] ) ; } else if ( ( $ value [ '__rialto_resource__' ] ?? false ) === true ) { if ( $ this -> delegate instanceof ShouldHandleProcessDelegation ) { $ classPath = $ this -> delegate -> resourceFromOriginalClassName ( $ value [ 'class_name' ] ) ? : $ this -> delegate -> defaultResource ( ) ; } else { $ classPath = $ this -> defaultResource ( ) ; } $ resource = new $ classPath ; if ( $ resource instanceof ShouldIdentifyResource ) { $ resource -> setResourceIdentity ( new ResourceIdentity ( $ value [ 'class_name' ] , $ value [ 'id' ] ) ) ; } if ( $ resource instanceof ShouldCommunicateWithProcessSupervisor ) { $ resource -> setProcessSupervisor ( $ this ) ; } return $ resource ; } else { return array_map ( function ( $ value ) { return $ this -> unserialize ( $ value ) ; } , $ value ) ; } } } | Unserialize a value . |
447 | public static function getAllResults ( ClientInterface $ client , $ url ) { $ data = [ ] ; do { $ response = $ client -> get ( $ url ) ; $ data = array_merge ( $ data , $ response -> json ( ) ) ; $ url = GithubApplication :: parseLinkHeader ( $ response ) [ 'next' ] ; } while ( $ url ) ; return $ data ; } | Helper function to retrieve all the pages of results from a GitHub API call and returns them as a single array |
448 | public function setAccessToken ( $ token ) { if ( $ token instanceof Token \ TokenInterface ) { $ this -> rawToken = $ token ; } else { $ this -> rawToken = is_array ( $ token ) ? $ this -> tokenFactory ( $ token ) : $ this -> tokenFactory ( [ 'access_token' => $ token ] ) ; } if ( $ this -> rawToken === null ) { throw new Exception \ OAuth2Exception ( "setAccessToken() takes a string, array or TokenInterface object" ) ; } return $ this ; } | Manually set the access token . |
449 | public function getAccessToken ( ) { if ( $ this -> rawToken === null ) { $ this -> rawToken = $ this -> tokenPersistence -> restoreToken ( new Token \ RawToken ( ) ) ; } if ( $ this -> rawToken === null || $ this -> rawToken -> isExpired ( ) ) { $ this -> tokenPersistence -> deleteToken ( ) ; $ this -> requestNewAccessToken ( ) ; if ( $ this -> rawToken ) { $ this -> tokenPersistence -> saveToken ( $ this -> rawToken ) ; } } return $ this -> rawToken ? $ this -> rawToken -> getAccessToken ( ) : null ; } | Get a valid access token . |
450 | public function unserialize ( array $ data ) { if ( ! isset ( $ data [ 'access_token' ] ) ) { throw new \ InvalidArgumentException ( 'Unable to create a RawToken without an "access_token"' ) ; } $ this -> accessToken = $ data [ 'access_token' ] ; $ this -> refreshToken = isset ( $ data [ 'refresh_token' ] ) ? $ data [ 'refresh_token' ] : null ; $ this -> expiresAt = isset ( $ data [ 'expires_at' ] ) ? $ data [ 'expires_at' ] : null ; return $ this ; } | Unserialize token data |
451 | public function add ( $ key , $ value ) { if ( ! array_key_exists ( $ key , $ this -> data ) ) { $ this -> data [ $ key ] = $ value ; } elseif ( is_array ( $ this -> data [ $ key ] ) ) { $ this -> data [ $ key ] [ ] = $ value ; } else { $ this -> data [ $ key ] = [ $ this -> data [ $ key ] , $ value ] ; } return $ this ; } | Add a value to a key . If a key of the same name has already been added the key value will be converted into an array and the new value will be pushed to the end of the array . |
452 | public function map ( callable $ closure , array $ context = [ ] ) { $ collection = new static ( ) ; foreach ( $ this as $ key => $ value ) { $ collection [ $ key ] = $ closure ( $ key , $ value , $ context ) ; } return $ collection ; } | Returns a Collection containing all the elements of the collection after applying the callback function to each one . |
453 | public function filter ( callable $ closure ) { $ collection = new static ( ) ; foreach ( $ this -> data as $ key => $ value ) { if ( $ closure ( $ key , $ value ) ) { $ collection [ $ key ] = $ value ; } } return $ collection ; } | Iterates over each key value pair in the collection passing them to the callable . If the callable returns true the current value from input is returned into the result Collection . |
454 | protected function viewExistsOrFail ( $ view , $ message = 'The view [:view] not found' ) { if ( ! $ this -> isViewExists ( $ view ) ) { abort ( 500 , str_replace ( ':view' , $ view , $ message ) ) ; } } | Check if view exists or fail . |
455 | private function isJsonRequestValid ( Request $ request , $ methods ) { $ methods = $ this -> getMethods ( $ methods ) ; return ! ( in_array ( $ request -> method ( ) , $ methods ) && ! $ request -> isJson ( ) ) ; } | Validate json Request . |
456 | private function getMethods ( $ methods ) { $ methods = $ methods ?? $ this -> methods ; if ( is_string ( $ methods ) ) $ methods = ( array ) $ methods ; return is_array ( $ methods ) ? array_map ( 'strtoupper' , $ methods ) : [ ] ; } | Get request methods . |
457 | protected function registerProvider ( $ provider , array $ options = [ ] , $ force = false ) { return $ this -> app -> register ( $ provider , $ options , $ force ) ; } | Register a service provider . |
458 | protected function registerConsoleServiceProvider ( $ provider , array $ options = [ ] , $ force = false ) { if ( $ this -> app -> runningInConsole ( ) ) return $ this -> registerProvider ( $ provider , $ options , $ force ) ; return null ; } | Register a console service provider . |
459 | protected function frame ( $ text ) { $ line = '+' . str_repeat ( '-' , strlen ( $ text ) + 4 ) . '+' ; $ this -> info ( $ line ) ; $ this -> info ( "| $text |" ) ; $ this -> info ( $ line ) ; } | Display frame the text info . |
460 | protected function setData ( $ name , $ value = null ) { if ( is_array ( $ name ) ) { $ this -> data = array_merge ( $ this -> data , $ name ) ; } elseif ( is_string ( $ name ) ) { $ this -> data [ $ name ] = $ value ; } return $ this ; } | Set view data . |
461 | public static function policies ( ) { $ abilities = array_values ( ( new \ ReflectionClass ( $ instance = new static ) ) -> getConstants ( ) ) ; return array_map ( function ( $ constant ) use ( $ instance ) { $ method = Str :: camel ( last ( explode ( '.' , $ constant ) ) . 'Policy' ) ; if ( ! method_exists ( $ instance , $ method ) ) throw new MissingPolicyException ( "Missing policy [$method] method in " . get_class ( $ instance ) . "." ) ; return $ method ; } , array_combine ( $ abilities , $ abilities ) ) ; } | Get the policies . |
462 | protected function registerConfig ( $ separator = '.' ) { $ this -> multiConfigs ? $ this -> registerMultipleConfigs ( $ separator ) : $ this -> mergeConfigFrom ( $ this -> getConfigFile ( ) , $ this -> getConfigKey ( ) ) ; } | Register configs . |
463 | private function registerMultipleConfigs ( $ separator = '.' ) { foreach ( glob ( $ this -> getConfigFolder ( ) . '/*.php' ) as $ configPath ) { $ this -> mergeConfigFrom ( $ configPath , $ this -> getConfigKey ( ) . $ separator . basename ( $ configPath , '.php' ) ) ; } } | Register all package configs . |
464 | protected function publishAll ( $ load = true ) { $ this -> publishConfig ( ) ; $ this -> publishMigrations ( ) ; $ this -> publishViews ( $ load ) ; $ this -> publishTranslations ( $ load ) ; $ this -> publishFactories ( ) ; } | Publish all the package files . |
465 | private function guessComposerCommand ( ) { $ candidateNames = array ( 'composer' , 'composer.phar' ) ; $ executableFinder = new ExecutableFinder ( ) ; foreach ( $ candidateNames as $ candidateName ) { if ( $ composerPath = $ executableFinder -> find ( $ candidateName , null , array ( getcwd ( ) ) ) ) { return array ( realpath ( $ composerPath ) ) ; } } foreach ( $ candidateNames as $ candidateName ) { $ composerPath = sprintf ( '%s/%s' , getcwd ( ) , $ candidateName ) ; if ( file_exists ( $ composerPath ) ) { $ phpFinder = new PhpExecutableFinder ( ) ; return array_merge ( array ( $ phpFinder -> find ( false ) , $ composerPath , ) , $ phpFinder -> findArguments ( ) ) ; } } return ; } | Guess and build the command to call composer . |
466 | public function run ( ) { $ maxATime = time ( ) - self :: TTL ; $ files = Finder :: create ( ) -> in ( $ this -> storePath ) -> depth ( 1 ) -> name ( Runner :: BOOTSTRAP_FILENAME ) -> filter ( function ( SplFileInfo $ d ) use ( $ maxATime ) { return $ d -> getATime ( ) < $ maxATime ; } ) ; $ directories = array ( ) ; foreach ( $ files as $ file ) { $ directories [ ] = dirname ( $ file ) ; } $ this -> filesystem -> remove ( $ directories ) ; } | Remove old workingDirectories . |
467 | public function load ( ) { $ config = new UserConfiguration ( ) ; if ( ! file_exists ( $ this -> storagePath ) ) { return $ config ; } try { $ data = Yaml :: parse ( file_get_contents ( $ this -> storagePath ) ) ; } catch ( ParseException $ e ) { throw new ConfigException ( sprintf ( 'The config file "%s" is not a valid YAML.' , $ this -> storagePath ) , 0 , $ e ) ; } if ( is_array ( $ data ) ) { $ config -> load ( $ data ) ; } return $ config ; } | Load stored configuration . Returns an empty UserConfiguration if no previous configuration was stored . |
468 | public function save ( UserConfiguration $ config ) { file_put_contents ( $ this -> storagePath , Yaml :: dump ( $ config -> toArray ( ) , 3 , 2 ) ) ; return $ this ; } | Save the given configuration . |
469 | public function download ( ) { $ handle = curl_init ( ) ; $ http_proxy = filter_input ( INPUT_ENV , 'HTTPS_PROXY' , FILTER_SANITIZE_URL ) ; curl_setopt_array ( $ handle , array ( CURLOPT_URL => sprintf ( 'https://api.github.com/gists/%s' , $ this -> id ) , CURLOPT_HTTPHEADER => array ( 'Accept: application/vnd.github.v3+json' , 'User-Agent: Melody-Script' , ) , CURLOPT_RETURNTRANSFER => 1 , ) ) ; if ( $ http_proxy ) { curl_setopt ( $ handle , CURLOPT_PROXY , $ http_proxy ) ; } $ content = curl_exec ( $ handle ) ; curl_close ( $ handle ) ; if ( ! $ content ) { throw new \ InvalidArgumentException ( sprintf ( 'Gist "%s" not found' , $ this -> id ) ) ; } return json_decode ( $ content , true ) ; } | Call Github and return JSON data . |
470 | public function tokenize ( $ input ) { $ tokens = [ ] ; $ currentIndex = 0 ; while ( $ currentIndex < strlen ( $ input ) ) { $ token = $ this -> findMatchingToken ( substr ( $ input , $ currentIndex ) ) ; if ( ! $ token ) { throw new UnknownTokenException ( substr ( $ input , $ currentIndex ) ) ; } $ tokens [ ] = $ token ; $ currentIndex += $ token -> length ( ) ; } return $ tokens ; } | Convert an input string to a list of tokens . |
471 | private function findMatchingToken ( $ input ) { foreach ( $ this -> tokenDefinitions as $ tokenDefinition ) { $ token = $ tokenDefinition -> match ( $ input ) ; if ( $ token ) { return $ token ; } } return null ; } | Find a matching token at the begining of the provided input . |
472 | private static function parseReal ( $ value ) { if ( $ value == '' ) return null ; $ x = str_replace ( ',' , '.' , $ value ) ; if ( static :: isSignedReal ( $ x ) ) return floatval ( $ x ) ; else throw new SyntaxErrorException ( ) ; } | convert string to floating point number if possible |
473 | public static function parse ( $ value ) { if ( $ value instanceof Complex ) return $ value ; if ( $ value instanceof Rational ) return new Complex ( $ value . p / $ value . q , 0 ) ; if ( is_int ( $ value ) ) return new Complex ( $ value , 0 ) ; if ( is_float ( $ value ) ) return new Complex ( $ value , 0 ) ; if ( ! is_string ( $ value ) ) throw new SyntaxErrorException ( ) ; $ matches = array ( ) ; $ valid = \ preg_match ( '#^([-,\+])?([0-9/,\.]*?)([-,\+]?)([0-9/,\.]*?)i$#' , \ trim ( $ value ) , $ matches ) ; if ( $ valid == 1 ) { $ real = $ matches [ 2 ] ; if ( $ real === '' ) { $ matches [ 3 ] = $ matches [ 1 ] ; $ real = '0' ; } $ imaginary = $ matches [ 4 ] ; if ( $ imaginary === '' ) $ imaginary = '1' ; if ( $ matches [ 1 ] && $ matches [ 1 ] == '-' ) { $ real = '-' . $ real ; } if ( $ matches [ 3 ] && $ matches [ 3 ] == '-' ) { $ imaginary = '-' . $ imaginary ; } try { $ a = Rational :: parse ( $ real ) ; $ realPart = $ a -> p / $ a -> q ; } catch ( SyntaxErrorException $ e ) { $ realPart = static :: parseReal ( $ real ) ; } try { $ b = Rational :: parse ( $ imaginary ) ; $ imaginaryPart = $ b -> p / $ b -> q ; } catch ( SyntaxErrorException $ e ) { $ imaginaryPart = static :: parseReal ( $ imaginary ) ; } } else { try { $ a = Rational :: parse ( $ value ) ; $ realPart = $ a -> p / $ a -> q ; $ imaginaryPart = 0 ; } catch ( SyntaxErrorException $ e ) { $ realPart = static :: parseReal ( $ value ) ; $ imaginaryPart = 0 ; } } $ z = new Complex ( $ realPart , $ imaginaryPart ) ; return $ z ; } | convert data to a complex number if possible |
474 | private static function toFloat ( $ x ) { if ( is_float ( $ x ) ) return $ x ; if ( is_int ( $ x ) ) return $ x ; if ( is_string ( $ x ) ) { $ r = Rational :: parse ( $ x ) ; return $ r -> p / $ r -> q ; } throw new SyntaxErrorException ( ) ; } | convert data to a floating point number if possible |
475 | public static function create ( $ real , $ imag ) { $ x = static :: toFloat ( $ real ) ; $ y = static :: toFloat ( $ imag ) ; return new Complex ( $ x , $ y ) ; } | create a complex number from its real and imaginary parts |
476 | public static function add ( $ z , $ w ) { if ( ! ( $ z instanceof Complex ) ) $ z = static :: parse ( $ z ) ; if ( ! ( $ w instanceof Complex ) ) $ w = static :: parse ( $ w ) ; return static :: create ( $ z -> x + $ w -> x , $ z -> y + $ w -> y ) ; } | add two complex numbers |
477 | public static function sub ( $ z , $ w ) { if ( ! ( $ z instanceof Complex ) ) $ z = static :: parse ( $ z ) ; if ( ! ( $ w instanceof Complex ) ) $ w = static :: parse ( $ w ) ; return static :: create ( $ z -> x - $ w -> x , $ z -> y - $ w -> y ) ; } | subtract two complex numbers |
478 | public static function mul ( $ z , $ w ) { if ( ! ( $ z instanceof Complex ) ) $ z = static :: parse ( $ z ) ; if ( ! ( $ w instanceof Complex ) ) $ w = static :: parse ( $ w ) ; return static :: create ( $ z -> x * $ w -> x - $ z -> y * $ w -> y , $ z -> x * $ w -> y + $ z -> y * $ w -> x ) ; } | multiply two complex numbers |
479 | public static function div ( $ z , $ w ) { if ( ! ( $ z instanceof Complex ) ) $ z = static :: parse ( $ z ) ; if ( ! ( $ w instanceof Complex ) ) $ w = static :: parse ( $ w ) ; $ d = $ w -> x * $ w -> x + $ w -> y * $ w -> y ; if ( $ d == 0 ) throw new DivisionByZeroException ( ) ; return static :: create ( ( $ z -> x * $ w -> x + $ z -> y * $ w -> y ) / $ d , ( - $ z -> x * $ w -> y + $ z -> y * $ w -> x ) / $ d ) ; } | divide two complex numbers |
480 | public static function pow ( $ z , $ w ) { if ( is_int ( $ w ) ) return static :: powi ( $ z , $ w ) ; return static :: exp ( static :: mul ( $ w , static :: log ( $ z ) ) ) ; } | powers of two complex numbers |
481 | private static function powi ( $ z , $ n ) { if ( $ n < 0 ) return static :: div ( 1 , static :: powi ( $ z , - $ n ) ) ; if ( $ n == 0 ) return new Complex ( 1 , 0 ) ; $ y = new Complex ( 1 , 0 ) ; while ( $ n > 1 ) { if ( $ n % 2 == 0 ) { $ n = $ n / 2 ; } else { $ y = static :: mul ( $ z , $ y ) ; $ n = ( $ n - 1 ) / 2 ; } $ z = static :: mul ( $ z , $ z ) ; } return static :: mul ( $ z , $ y ) ; } | integer power of a complex number |
482 | public static function sin ( $ z ) { if ( ! ( $ z instanceof Complex ) ) $ z = static :: parse ( $ z ) ; return static :: create ( sin ( $ z -> x ) * cosh ( $ z -> y ) , cos ( $ z -> x ) * sinh ( $ z -> y ) ) ; } | complex sine function |
483 | public static function tan ( $ z ) { if ( ! ( $ z instanceof Complex ) ) $ z = static :: parse ( $ z ) ; $ d = cos ( $ z -> x ) * cos ( $ z -> x ) + sinh ( $ z -> y ) * sinh ( $ z -> y ) ; return static :: create ( sin ( $ z -> x ) * cos ( $ z -> x ) / $ d , sinh ( $ z -> y ) * cosh ( $ z -> y ) / $ d ) ; } | complex tangent function |
484 | public static function arcsin ( $ z ) { if ( ! ( $ z instanceof Complex ) ) $ z = static :: parse ( $ z ) ; $ I = new Complex ( 0 , 1 ) ; $ iz = static :: mul ( $ z , $ I ) ; $ temp = static :: sqrt ( static :: sub ( 1 , static :: mul ( $ z , $ z ) ) ) ; return static :: div ( static :: log ( static :: add ( $ iz , $ temp ) ) , $ I ) ; } | complex inverse sine function |
485 | public static function arccos ( $ z ) { if ( ! ( $ z instanceof Complex ) ) $ z = static :: parse ( $ z ) ; $ I = new Complex ( 0 , 1 ) ; $ temp = static :: mul ( static :: sqrt ( static :: sub ( 1 , static :: mul ( $ z , $ z ) ) ) , $ I ) ; return static :: div ( static :: log ( static :: add ( $ z , $ temp ) ) , $ I ) ; } | complex inverse cosine function |
486 | public static function arctan ( $ z ) { if ( ! ( $ z instanceof Complex ) ) $ z = static :: parse ( $ z ) ; $ I = new Complex ( 0 , 1 ) ; $ iz = static :: mul ( $ z , $ I ) ; $ w = static :: div ( static :: add ( 1 , $ iz ) , static :: sub ( 1 , $ iz ) ) ; $ logw = static :: log ( $ w ) ; return static :: div ( $ logw , new Complex ( 0 , 2 ) ) ; } | complex inverse tangent function |
487 | public static function arccot ( $ z ) { if ( ! ( $ z instanceof Complex ) ) $ z = static :: parse ( $ z ) ; return static :: sub ( M_PI / 2 , static :: arctan ( $ z ) ) ; } | complex inverse cotangent function |
488 | public static function exp ( $ z ) { if ( ! ( $ z instanceof Complex ) ) $ z = static :: parse ( $ z ) ; $ r = exp ( $ z -> x ) ; return new Complex ( $ r * cos ( $ z -> y ) , $ r * sin ( $ z -> y ) ) ; } | complex exponential function |
489 | public static function log ( $ z ) { if ( ! ( $ z instanceof Complex ) ) $ z = static :: parse ( $ z ) ; $ r = $ z -> abs ( ) ; $ theta = $ z -> arg ( ) ; if ( $ r == 0 ) return new Complex ( NAN , NAN ) ; return new Complex ( log ( $ r ) , $ theta ) ; } | complex logarithm function |
490 | public static function arsinh ( $ z ) { if ( ! ( $ z instanceof Complex ) ) $ z = static :: parse ( $ z ) ; return static :: log ( static :: add ( $ z , static :: sqrt ( static :: add ( 1 , static :: mul ( $ z , $ z ) ) ) ) ) ; } | complex inverse hyperbolic sine function |
491 | public static function arcosh ( $ z ) { if ( ! ( $ z instanceof Complex ) ) $ z = static :: parse ( $ z ) ; return static :: log ( static :: add ( $ z , static :: sqrt ( static :: add ( - 1 , static :: mul ( $ z , $ z ) ) ) ) ) ; } | complex inverse hyperbolic cosine function |
492 | public static function artanh ( $ z ) { if ( ! ( $ z instanceof Complex ) ) $ z = static :: parse ( $ z ) ; return static :: div ( static :: log ( static :: div ( static :: add ( 1 , $ z ) , static :: sub ( 1 , $ z ) ) ) , 2 ) ; } | complex inverse hyperbolic tangent function |
493 | public static function sqrt ( $ z ) { if ( ! ( $ z instanceof Complex ) ) $ z = static :: parse ( $ z ) ; $ r = sqrt ( $ z -> abs ( ) ) ; $ theta = $ z -> arg ( ) / 2 ; return new Complex ( $ r * cos ( $ theta ) , $ r * sin ( $ theta ) ) ; } | complex square root function |
494 | public function visitVariableNode ( VariableNode $ node ) { $ name = $ node -> getName ( ) ; if ( array_key_exists ( $ name , $ this -> variables ) ) { return $ this -> variables [ $ name ] ; } throw new UnknownVariableException ( $ name ) ; } | Evaluate a VariableNode |
495 | public function simplify ( ExpressionNode $ node ) { switch ( $ node -> getOperator ( ) ) { case '+' : return $ this -> addition ( $ node -> getLeft ( ) , $ node -> getRight ( ) ) ; case '-' : return $ this -> subtraction ( $ node -> getLeft ( ) , $ node -> getRight ( ) ) ; case '*' : return $ this -> multiplication ( $ node -> getLeft ( ) , $ node -> getRight ( ) ) ; case '/' : return $ this -> division ( $ node -> getLeft ( ) , $ node -> getRight ( ) ) ; case '^' : return $ this -> exponentiation ( $ node -> getLeft ( ) , $ node -> getRight ( ) ) ; } } | Simplify the given ExpressionNode using the appropriate factory . |
496 | public function lowerPrecedenceThan ( $ other ) { if ( ! ( $ other instanceof ExpressionNode ) ) return false ; if ( $ this -> getPrecedence ( ) < $ other -> getPrecedence ( ) ) return true ; if ( $ this -> getPrecedence ( ) > $ other -> getPrecedence ( ) ) return false ; if ( $ this -> associativity == self :: LEFT_ASSOC ) return true ; return false ; } | Returns true if the current Node has lower precedence than the one we compare with . |
497 | public static function gcd ( $ a , $ b ) { $ sign = 1 ; if ( $ a < 0 ) $ sign = - $ sign ; if ( $ b < 0 ) $ sign = - $ sign ; while ( $ b != 0 ) { $ m = $ a % $ b ; $ a = $ b ; $ b = $ m ; } return $ sign * abs ( $ a ) ; } | Compute greates common denominator using the Euclidean algorithm |
498 | protected function numericFactors ( $ leftOperand , $ rightOperand ) { if ( $ this -> isNumeric ( $ rightOperand ) && $ rightOperand -> getValue ( ) == 0 ) { throw new DivisionByZeroException ( ) ; } if ( $ this -> isNumeric ( $ rightOperand ) && $ rightOperand -> getValue ( ) == 1 ) { return $ leftOperand ; } if ( $ this -> isNumeric ( $ leftOperand ) && $ leftOperand -> getValue ( ) == 0 ) { return new IntegerNode ( 0 ) ; } if ( ! $ this -> isNumeric ( $ leftOperand ) || ! $ this -> isNumeric ( $ rightOperand ) ) { return null ; } $ type = $ this -> resultingType ( $ leftOperand , $ rightOperand ) ; switch ( $ type ) { case Node :: NumericFloat : return new NumberNode ( $ leftOperand -> getValue ( ) / $ rightOperand -> getValue ( ) ) ; case Node :: NumericRational : case Node :: NumericInteger : $ p = $ leftOperand -> getNumerator ( ) * $ rightOperand -> getDenominator ( ) ; $ q = $ leftOperand -> getDenominator ( ) * $ rightOperand -> getNumerator ( ) ; return new RationalNode ( $ p , $ q ) ; } return null ; } | Simplify division nodes when factors are numeric |
499 | protected function sanitize ( $ operand ) { if ( is_int ( $ operand ) ) return new IntegerNode ( $ operand ) ; if ( is_float ( $ operand ) ) return new NumberNode ( $ operand ) ; return $ operand ; } | Convert ints and floats to NumberNodes |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.