idx
int64 0
60.3k
| question
stringlengths 101
6.21k
| target
stringlengths 7
803
|
|---|---|---|
3,400
|
public static function isMobileOnlyBrowser ( $ browser ) { return in_array ( $ browser , self :: $ mobileOnlyBrowsers ) || ( in_array ( $ browser , self :: $ availableBrowsers ) && in_array ( array_search ( $ browser , self :: $ availableBrowsers ) , self :: $ mobileOnlyBrowsers ) ) ; }
|
Returns if the given browser is mobile only
|
3,401
|
public function parse ( ) { $ result = null ; if ( $ this -> preMatchOverall ( ) ) { foreach ( $ this -> getRegexes ( ) as $ regex ) { $ matches = $ this -> matchUserAgent ( $ regex [ 'regex' ] ) ; if ( $ matches ) { $ result = array ( 'type' => $ this -> parserName , 'name' => $ this -> buildByMatch ( $ regex [ 'name' ] , $ matches ) , 'version' => $ this -> buildVersion ( $ regex [ 'version' ] , $ matches ) ) ; break ; } } } return $ result ; }
|
Parses the current UA and checks whether it contains any client information
|
3,402
|
public static function getAvailableClients ( ) { $ instance = new static ( ) ; $ regexes = $ instance -> getRegexes ( ) ; $ names = array ( ) ; foreach ( $ regexes as $ regex ) { if ( $ regex [ 'name' ] != '$1' ) { $ names [ ] = $ regex [ 'name' ] ; } } natcasesort ( $ names ) ; return array_unique ( $ names ) ; }
|
Returns all names defined in the regexes
|
3,403
|
public function parse ( ) { $ result = null ; if ( $ this -> preMatchOverall ( ) ) { if ( $ this -> discardDetails ) { $ result = true ; } else { foreach ( $ this -> getRegexes ( ) as $ regex ) { $ matches = $ this -> matchUserAgent ( $ regex [ 'regex' ] ) ; if ( $ matches ) { unset ( $ regex [ 'regex' ] ) ; $ result = $ regex ; break ; } } } } return $ result ; }
|
Parses the current UA and checks whether it contains bot information
|
3,404
|
public static function getOsFamily ( $ osLabel ) { foreach ( self :: $ osFamilies as $ family => $ labels ) { if ( in_array ( $ osLabel , $ labels ) ) { return $ family ; } } return false ; }
|
Returns the operating system family for the given operating system
|
3,405
|
public static function getNameFromId ( $ os , $ ver = false ) { if ( array_key_exists ( $ os , self :: $ operatingSystems ) ) { $ osFullName = self :: $ operatingSystems [ $ os ] ; return trim ( $ osFullName . " " . $ ver ) ; } return false ; }
|
Returns the full name for the given short name
|
3,406
|
public static function setVersionTruncation ( $ type ) { if ( in_array ( $ type , array ( self :: VERSION_TRUNCATION_BUILD , self :: VERSION_TRUNCATION_NONE , self :: VERSION_TRUNCATION_MAJOR , self :: VERSION_TRUNCATION_MINOR , self :: VERSION_TRUNCATION_PATCH ) ) ) { self :: $ maxMinorParts = $ type ; } }
|
Set how DeviceDetector should return versions
|
3,407
|
protected function matchUserAgent ( $ regex ) { $ regex = '/(?:^|[^A-Z0-9\-_]|[^A-Z0-9\-]_|sprd-)(?:' . str_replace ( '/' , '\/' , $ regex ) . ')/i' ; if ( preg_match ( $ regex , $ this -> userAgent , $ matches ) ) { return $ matches ; } return false ; }
|
Matches the useragent against the given regex
|
3,408
|
protected function preMatchOverall ( ) { $ regexes = $ this -> getRegexes ( ) ; static $ overAllMatch ; $ cacheKey = $ this -> parserName . DeviceDetector :: VERSION . '-all' ; $ cacheKey = preg_replace ( '/([^a-z0-9_-]+)/i' , '' , $ cacheKey ) ; if ( empty ( $ overAllMatch ) ) { $ overAllMatch = $ this -> getCache ( ) -> fetch ( $ cacheKey ) ; } if ( empty ( $ overAllMatch ) ) { $ overAllMatch = array_reduce ( array_reverse ( $ regexes ) , function ( $ val1 , $ val2 ) { if ( ! empty ( $ val1 ) ) { return $ val1 . '|' . $ val2 [ 'regex' ] ; } else { return $ val2 [ 'regex' ] ; } } ) ; $ this -> getCache ( ) -> save ( $ cacheKey , $ overAllMatch ) ; } return $ this -> matchUserAgent ( $ overAllMatch ) ; }
|
Tests the useragent against a combination of all regexes
|
3,409
|
public static function for ( $ baseQuery , ? Request $ request = null ) : self { if ( is_string ( $ baseQuery ) ) { $ baseQuery = ( $ baseQuery ) :: query ( ) ; } return new static ( $ baseQuery , $ request ?? request ( ) ) ; }
|
Create a new QueryBuilder for a request and model .
|
3,410
|
private function bootstrapApplicationEnvironment ( $ appBootstrap , $ appenv , $ debug ) { $ appBootstrap = $ this -> normalizeBootstrapClass ( $ appBootstrap ) ; $ this -> middleware = new $ appBootstrap ; if ( $ this -> middleware instanceof ApplicationEnvironmentAwareInterface ) { $ this -> middleware -> initialize ( $ appenv , $ debug ) ; } }
|
Bootstrap application environment
|
3,411
|
public function add ( Slave $ slave ) { $ port = $ slave -> getPort ( ) ; if ( isset ( $ this -> slaves [ $ port ] ) ) { throw new \ Exception ( "Slave port $port already occupied." ) ; } if ( $ slave -> getPort ( ) !== $ port ) { throw new \ Exception ( "Slave mis-assigned." ) ; } $ this -> slaves [ $ port ] = $ slave ; }
|
Add slave to pool
|
3,412
|
public function remove ( Slave $ slave ) { $ port = $ slave -> getPort ( ) ; $ this -> getByPort ( $ port ) ; unset ( $ this -> slaves [ $ port ] ) ; }
|
Remove from pool
|
3,413
|
public function getByPort ( $ port ) { if ( ! isset ( $ this -> slaves [ $ port ] ) ) { throw new \ Exception ( "Slave port $port empty." ) ; } return $ this -> slaves [ $ port ] ; }
|
Get slave by port
|
3,414
|
public function getByConnection ( ConnectionInterface $ connection ) { $ hash = spl_object_hash ( $ connection ) ; foreach ( $ this -> slaves as $ slave ) { if ( $ slave -> getConnection ( ) && $ hash === spl_object_hash ( $ slave -> getConnection ( ) ) ) { return $ slave ; } } throw new \ Exception ( "Slave connection not registered." ) ; }
|
Get slave slaves by connection
|
3,415
|
public function getByStatus ( $ status ) { return array_filter ( $ this -> slaves , function ( $ slave ) use ( $ status ) { return $ status === Slave :: ANY || $ status === $ slave -> getStatus ( ) ; } ) ; }
|
Get multiple slaves by status
|
3,416
|
public function getStatusSummary ( ) { $ map = [ 'total' => Slave :: ANY , 'ready' => Slave :: READY , 'busy' => Slave :: BUSY , 'created' => Slave :: CREATED , 'registered' => Slave :: REGISTERED , 'closed' => Slave :: CLOSED ] ; return array_map ( function ( $ state ) { return count ( $ this -> getByStatus ( $ state ) ) ; } , $ map ) ; }
|
Return a human - readable summary of the slaves in the pool .
|
3,417
|
public function register ( $ pid , ConnectionInterface $ connection ) { if ( $ this -> status !== self :: CREATED ) { throw new \ LogicException ( 'Cannot register a slave that is not in created state' ) ; } $ this -> pid = $ pid ; $ this -> connection = $ connection ; $ this -> status = self :: REGISTERED ; }
|
Register a slave after it s process started
|
3,418
|
public function ready ( ) { if ( $ this -> status !== self :: REGISTERED ) { throw new \ LogicException ( 'Cannot ready a slave that is not in registered state' ) ; } $ this -> status = self :: READY ; }
|
Ready a slave after bootstrap completed
|
3,419
|
public function occupy ( ) { if ( $ this -> status !== self :: READY ) { throw new \ LogicException ( 'Cannot occupy a slave that is not in ready state' ) ; } $ this -> status = self :: BUSY ; }
|
Occupies a slave for request handling
|
3,420
|
public function release ( ) { if ( $ this -> status !== self :: BUSY ) { throw new \ LogicException ( 'Cannot release a slave that is not in busy state' ) ; } $ this -> status = self :: READY ; $ this -> handledRequests ++ ; }
|
Releases a slave from request handling
|
3,421
|
public function handle ( ConnectionInterface $ incoming ) { $ this -> incoming = $ incoming ; $ this -> incoming -> on ( 'data' , [ $ this , 'handleData' ] ) ; $ this -> incoming -> on ( 'close' , function ( ) { $ this -> connectionOpen = false ; } ) ; $ this -> start = microtime ( true ) ; $ this -> requestSentAt = microtime ( true ) ; $ this -> getNextSlave ( ) ; if ( $ this -> maxExecutionTime > 0 ) { $ this -> maxExecutionTimer = $ this -> loop -> addTimer ( $ this -> maxExecutionTime , [ $ this , 'maxExecutionTimeExceeded' ] ) ; } }
|
Handle incoming client connection
|
3,422
|
public function handleData ( $ data ) { $ this -> incomingBuffer .= $ data ; if ( $ this -> connection && $ this -> isHeaderEnd ( $ this -> incomingBuffer ) ) { $ remoteAddress = ( string ) $ this -> incoming -> getRemoteAddress ( ) ; $ headersToReplace = [ 'X-PHP-PM-Remote-IP' => trim ( parse_url ( $ remoteAddress , PHP_URL_HOST ) , '[]' ) , 'X-PHP-PM-Remote-Port' => trim ( parse_url ( $ remoteAddress , PHP_URL_PORT ) , '[]' ) ] ; $ buffer = $ this -> replaceHeader ( $ this -> incomingBuffer , $ headersToReplace ) ; $ this -> connection -> write ( $ buffer ) ; $ this -> incoming -> removeListener ( 'data' , [ $ this , 'handleData' ] ) ; $ this -> incoming -> pipe ( $ this -> connection ) ; } }
|
Buffer incoming data until slave connection is available and headers have been received
|
3,423
|
public function getNextSlave ( ) { if ( ! $ this -> connectionOpen ) { return ; } $ available = $ this -> slaves -> getByStatus ( Slave :: READY ) ; if ( count ( $ available ) ) { $ slave = array_shift ( $ available ) ; if ( $ this -> tryOccupySlave ( $ slave ) ) { return ; } } if ( time ( ) < ( $ this -> requestSentAt + $ this -> timeout ) ) { $ this -> loop -> futureTick ( [ $ this , 'getNextSlave' ] ) ; } else { $ this -> output -> writeln ( sprintf ( 'No slaves available to handle the request and timeout %d seconds exceeded' , $ this -> timeout ) ) ; $ this -> incoming -> write ( $ this -> createErrorResponse ( '503 Service Temporarily Unavailable' , 'Service Temporarily Unavailable' ) ) ; $ this -> incoming -> end ( ) ; } }
|
Get next free slave from pool Asynchronously keep trying until slave becomes available
|
3,424
|
public function tryOccupySlave ( Slave $ slave ) { if ( $ slave -> isExpired ( ) ) { $ slave -> close ( ) ; $ this -> output -> writeln ( sprintf ( 'Restart worker #%d because it reached its TTL' , $ slave -> getPort ( ) ) ) ; $ slave -> getConnection ( ) -> close ( ) ; return false ; } $ this -> redirectionTries ++ ; $ this -> slave = $ slave ; $ this -> verboseTimer ( function ( $ took ) { return sprintf ( '<info>took abnormal %.3f seconds for choosing next free worker</info>' , $ took ) ; } ) ; $ this -> slave -> occupy ( ) ; $ connector = new UnixConnector ( $ this -> loop ) ; $ connector = new TimeoutConnector ( $ connector , $ this -> timeout , $ this -> loop ) ; $ socketPath = $ this -> getSlaveSocketPath ( $ this -> slave -> getPort ( ) ) ; $ connector -> connect ( $ socketPath ) -> then ( [ $ this , 'slaveConnected' ] , [ $ this , 'slaveConnectFailed' ] ) ; return true ; }
|
Slave available handler
|
3,425
|
public function slaveConnected ( ConnectionInterface $ connection ) { $ this -> connection = $ connection ; $ this -> verboseTimer ( function ( $ took ) { return sprintf ( '<info>Took abnormal %.3f seconds for connecting to worker %d</info>' , $ took , $ this -> slave -> getPort ( ) ) ; } ) ; $ this -> handleData ( '' ) ; $ this -> incoming -> on ( 'close' , [ $ this -> connection , 'close' ] ) ; $ this -> connection -> on ( 'close' , [ $ this , 'slaveClosed' ] ) ; $ this -> connection -> on ( 'data' , function ( $ data ) { $ this -> lastOutgoingData = $ data ; } ) ; $ this -> connection -> pipe ( $ this -> incoming , [ 'end' => false ] ) ; }
|
Handle successful slave connection
|
3,426
|
public function maxExecutionTimeExceeded ( ) { if ( ! $ this -> connectionOpen ) { return false ; } $ this -> incoming -> write ( $ this -> createErrorResponse ( '504 Gateway Timeout' , 'Maximum execution time exceeded' ) ) ; $ this -> lastOutgoingData = 'not empty' ; $ this -> slave -> close ( ) ; $ this -> output -> writeln ( sprintf ( 'Maximum execution time of %d seconds exceeded. Closing worker.' , $ this -> maxExecutionTime ) ) ; $ this -> slave -> getConnection ( ) -> close ( ) ; }
|
Stop the worker if the max execution time has been exceeded and return 504
|
3,427
|
public function slaveClosed ( ) { $ this -> verboseTimer ( function ( $ took ) { return sprintf ( '<info>Worker %d took abnormal %.3f seconds for handling a connection</info>' , $ this -> slave -> getPort ( ) , $ took ) ; } ) ; if ( $ this -> lastOutgoingData == '' ) { $ this -> output -> writeln ( 'Script did not return a valid HTTP response. Maybe it has called exit() prematurely?' ) ; $ this -> incoming -> write ( $ this -> createErrorResponse ( '502 Bad Gateway' , 'Slave returned an invalid HTTP response. Maybe the script has called exit() prematurely?' ) ) ; } $ this -> incoming -> end ( ) ; if ( $ this -> maxExecutionTime > 0 ) { $ this -> loop -> cancelTimer ( $ this -> maxExecutionTimer ) ; } if ( $ this -> slave -> getStatus ( ) === Slave :: LOCKED ) { $ this -> slave -> close ( ) ; $ this -> output -> writeln ( sprintf ( 'Marking locked worker #%d as closed' , $ this -> slave -> getPort ( ) ) ) ; $ this -> slave -> getConnection ( ) -> close ( ) ; } elseif ( $ this -> slave -> getStatus ( ) !== Slave :: CLOSED ) { $ this -> slave -> release ( ) ; $ connection = $ this -> slave -> getConnection ( ) ; $ maxRequests = $ this -> slave -> getMaxRequests ( ) ; if ( $ this -> slave -> getHandledRequests ( ) >= $ maxRequests ) { $ this -> slave -> close ( ) ; $ this -> output -> writeln ( sprintf ( 'Restart worker #%d because it reached max requests of %d' , $ this -> slave -> getPort ( ) , $ maxRequests ) ) ; $ connection -> close ( ) ; } $ memoryLimit = $ this -> slave -> getMemoryLimit ( ) ; if ( $ memoryLimit > 0 && $ this -> slave -> getUsedMemory ( ) >= $ memoryLimit ) { $ this -> slave -> close ( ) ; $ this -> output -> writeln ( sprintf ( 'Restart worker #%d because it reached memory limit of %d' , $ this -> slave -> getPort ( ) , $ memoryLimit ) ) ; $ connection -> close ( ) ; } } }
|
Handle slave disconnected
|
3,428
|
public function slaveConnectFailed ( \ Exception $ e ) { $ this -> slave -> release ( ) ; $ this -> verboseTimer ( function ( $ took ) use ( $ e ) { return sprintf ( '<error>Connection to worker %d failed. Try #%d, took %.3fs ' . '(timeout %ds). Error message: [%d] %s</error>' , $ this -> slave -> getPort ( ) , $ this -> redirectionTries , $ took , $ this -> timeout , $ e -> getCode ( ) , $ e -> getMessage ( ) ) ; } , true ) ; unset ( $ this -> slave ) ; $ delay = min ( $ this -> timeout , floor ( $ this -> redirectionTries / 10 ) / 100 ) ; $ this -> loop -> addTimer ( $ delay , [ $ this , 'getNextSlave' ] ) ; }
|
Handle failed slave connection
|
3,429
|
protected function verboseTimer ( $ callback , $ always = false ) { $ took = microtime ( true ) - $ this -> start ; if ( ( $ always || $ took > 1 ) && $ this -> output -> isVeryVerbose ( ) ) { $ message = $ callback ( $ took ) ; $ this -> output -> writeln ( $ message ) ; } $ this -> start = microtime ( true ) ; }
|
Section timer . Measure execution time hand output if verbose mode .
|
3,430
|
protected function replaceHeader ( $ header , $ headersToReplace ) { $ result = $ header ; foreach ( $ headersToReplace as $ key => $ value ) { if ( false !== $ headerPosition = stripos ( $ result , $ key . ':' ) ) { $ length = strpos ( substr ( $ header , $ headerPosition ) , "\r\n" ) ; $ result = substr_replace ( $ result , "$key: $value" , $ headerPosition , $ length ) ; } else { $ end = strpos ( $ result , "\r\n\r\n" ) ; $ result = substr_replace ( $ result , "\r\n$key: $value" , $ end , 0 ) ; } } return $ result ; }
|
Replaces or injects header
|
3,431
|
public function prepareShutdown ( ) { if ( $ this -> inShutdown ) { return false ; } if ( $ this -> errorLogger && $ logs = $ this -> errorLogger -> cleanLogs ( ) ) { $ messages = array_map ( function ( $ item ) { $ message = $ item [ 1 ] ; $ context = $ item [ 2 ] ; if ( isset ( $ context [ 'file' ] ) ) { $ message .= ' in ' . $ context [ 'file' ] . ':' . $ context [ 'line' ] ; } if ( isset ( $ context [ 'stack' ] ) ) { foreach ( $ context [ 'stack' ] as $ idx => $ stack ) { $ message .= PHP_EOL . sprintf ( "#%d: %s%s %s%s" , $ idx , isset ( $ stack [ 'class' ] ) ? $ stack [ 'class' ] . '->' : '' , $ stack [ 'function' ] , isset ( $ stack [ 'file' ] ) ? 'in' . $ stack [ 'file' ] : '' , isset ( $ stack [ 'line' ] ) ? ':' . $ stack [ 'line' ] : '' ) ; } } return $ message ; } , $ logs ) ; error_log ( implode ( PHP_EOL , $ messages ) ) ; } $ this -> inShutdown = true ; $ this -> sendCurrentFiles ( ) ; if ( $ this -> server ) { @ $ this -> server -> close ( ) ; } if ( $ this -> loop ) { $ this -> loop -> stop ( ) ; } return true ; }
|
Shuts down the event loop . This basically exits the process .
|
3,432
|
protected function bootstrap ( $ appBootstrap , $ appenv , $ debug ) { if ( $ bridge = $ this -> getBridge ( ) ) { $ bridge -> bootstrap ( $ appBootstrap , $ appenv , $ debug ) ; $ this -> sendMessage ( $ this -> controller , 'ready' ) ; } }
|
Bootstraps the actual application .
|
3,433
|
protected function sendCurrentFiles ( ) { if ( ! $ this -> isDebug ( ) ) { return ; } $ files = array_merge ( $ this -> watchedFiles , get_included_files ( ) ) ; $ flipped = array_flip ( $ files ) ; if ( ! $ this -> lastSentFiles || array_diff_key ( $ flipped , $ this -> lastSentFiles ) ) { $ this -> lastSentFiles = $ flipped ; $ this -> sendMessage ( $ this -> controller , 'files' , [ 'files' => $ files ] ) ; } $ this -> watchedFiles = [ ] ; }
|
Sends to the master a snapshot of current known php files so it can track those files and restart slaves if necessary .
|
3,434
|
private function doConnect ( ) { $ connector = new UnixConnector ( $ this -> loop ) ; $ unixSocket = $ this -> getControllerSocketPath ( false ) ; $ connector -> connect ( $ unixSocket ) -> done ( function ( $ controller ) { $ this -> controller = $ controller ; $ this -> loop -> addSignal ( SIGTERM , [ $ this , 'shutdown' ] ) ; $ this -> loop -> addSignal ( SIGINT , [ $ this , 'shutdown' ] ) ; register_shutdown_function ( [ $ this , 'prepareShutdown' ] ) ; $ this -> bindProcessMessage ( $ this -> controller ) ; $ this -> controller -> on ( 'close' , [ $ this , 'shutdown' ] ) ; $ port = $ this -> config [ 'port' ] ; $ socketPath = $ this -> getSlaveSocketPath ( $ port , true ) ; $ this -> server = new UnixServer ( $ socketPath , $ this -> loop ) ; $ httpServer = new HttpServer ( [ $ this , 'onRequest' ] ) ; $ httpServer -> listen ( $ this -> server ) ; $ this -> sendMessage ( $ this -> controller , 'register' , [ 'pid' => getmypid ( ) , 'port' => $ port ] ) ; } ) ; }
|
Attempt a connection to the unix socket .
|
3,435
|
public function run ( ) { $ this -> loop = Factory :: create ( ) ; $ this -> errorLogger = BufferingLogger :: create ( ) ; ErrorHandler :: register ( new ErrorHandler ( $ this -> errorLogger ) ) ; $ this -> tryConnect ( ) ; $ this -> loop -> run ( ) ; }
|
Connects to ProcessManager master process .
|
3,436
|
protected function handleRequest ( ServerRequestInterface $ request ) { if ( $ this -> getStaticDirectory ( ) ) { $ staticResponse = $ this -> serveStatic ( $ request ) ; if ( $ staticResponse instanceof ResponseInterface ) { return $ staticResponse ; } } if ( $ bridge = $ this -> getBridge ( ) ) { try { $ response = $ bridge -> handle ( $ request ) ; } catch ( \ Throwable $ t ) { error_log ( 'An exception was thrown by the bridge. Forcing restart of the worker. The exception was: ' . ( string ) $ t ) ; $ response = new Response ( 500 , [ ] , 'Unexpected error' ) ; @ ob_end_clean ( ) ; $ this -> shutdown ( ) ; } $ this -> sendCurrentFiles ( ) ; } else { $ response = new Response ( 404 , [ ] , 'No Bridge defined' ) ; } if ( headers_sent ( ) ) { error_log ( 'Headers have been sent, but not redirected to client. Forcing restart of the worker. ' . 'Make sure your application does not send headers on its own.' ) ; $ this -> shutdown ( ) ; } $ this -> sendMessage ( $ this -> controller , 'stats' , [ 'memory_usage' => round ( memory_get_peak_usage ( true ) / 1048576 , 2 ) ] ) ; return $ response ; }
|
Handle a redirected request from master .
|
3,437
|
public function shutdown ( $ graceful = true ) { if ( $ this -> status === self :: STATE_SHUTDOWN ) { return ; } $ this -> output -> writeln ( "<info>Server is shutting down.</info>" ) ; $ this -> status = self :: STATE_SHUTDOWN ; $ remainingSlaves = count ( $ this -> slaves -> getByStatus ( Slave :: READY ) ) ; if ( $ remainingSlaves === 0 ) { $ this -> quit ( ) ; } else { $ this -> closeSlaves ( $ graceful , function ( $ slave ) use ( & $ remainingSlaves ) { $ this -> terminateSlave ( $ slave ) ; $ remainingSlaves -- ; if ( $ this -> output -> isVeryVerbose ( ) ) { $ this -> output -> writeln ( sprintf ( 'Worker #%d terminated, %d more worker(s) to close.' , $ slave -> getPort ( ) , $ remainingSlaves ) ) ; } if ( $ remainingSlaves === 0 ) { $ this -> quit ( ) ; } } ) ; } }
|
Handles termination signals so we can gracefully stop all servers .
|
3,438
|
private function quit ( ) { $ this -> output -> writeln ( 'Stopping the process manager.' ) ; if ( $ this -> controller ) { @ $ this -> controller -> close ( ) ; } if ( $ this -> web ) { @ $ this -> web -> close ( ) ; } if ( $ this -> loop ) { $ this -> loop -> stop ( ) ; } unlink ( $ this -> pidfile ) ; exit ; }
|
To be called after all workers have been terminated and the event loop is no longer in use .
|
3,439
|
public function run ( ) { Debug :: enable ( ) ; ini_set ( 'zlib.output_compression' , 0 ) ; ini_set ( 'output_buffering' , 0 ) ; ini_set ( 'implicit_flush' , 1 ) ; ob_implicit_flush ( 1 ) ; $ this -> loop = Factory :: create ( ) ; $ this -> controller = new UnixServer ( $ this -> getControllerSocketPath ( ) , $ this -> loop ) ; $ this -> controller -> on ( 'connection' , [ $ this , 'onSlaveConnection' ] ) ; $ this -> web = new Server ( sprintf ( '%s:%d' , $ this -> host , $ this -> port ) , $ this -> loop ) ; $ this -> web -> on ( 'connection' , [ $ this , 'onRequest' ] ) ; $ this -> loop -> addSignal ( SIGTERM , [ $ this , 'shutdown' ] ) ; $ this -> loop -> addSignal ( SIGINT , [ $ this , 'shutdown' ] ) ; $ this -> loop -> addSignal ( SIGCHLD , [ $ this , 'handleSigchld' ] ) ; $ this -> loop -> addSignal ( SIGUSR1 , [ $ this , 'restartSlaves' ] ) ; $ this -> loop -> addSignal ( SIGUSR2 , [ $ this , 'reloadSlaves' ] ) ; if ( $ this -> isDebug ( ) ) { $ this -> loop -> addPeriodicTimer ( 0.5 , function ( ) { $ this -> checkChangedFiles ( ) ; } ) ; } $ loopClass = ( new \ ReflectionClass ( $ this -> loop ) ) -> getShortName ( ) ; $ this -> output -> writeln ( "<info>Starting PHP-PM with {$this->slaveCount} workers, using {$loopClass} ...</info>" ) ; $ this -> writePid ( ) ; $ this -> createSlaves ( ) ; $ this -> loop -> run ( ) ; }
|
Starts the main loop . Blocks .
|
3,440
|
public function onSlaveConnection ( ConnectionInterface $ connection ) { $ this -> bindProcessMessage ( $ connection ) ; $ connection -> on ( 'close' , function ( ) use ( $ connection ) { $ this -> onSlaveClosed ( $ connection ) ; } ) ; }
|
Handles data communication from slave - > master
|
3,441
|
public function onSlaveClosed ( ConnectionInterface $ connection ) { if ( $ this -> status === self :: STATE_SHUTDOWN ) { return ; } try { $ slave = $ this -> slaves -> getByConnection ( $ connection ) ; } catch ( \ Exception $ e ) { $ this -> output -> writeln ( '<error>Worker permanently closed during PHP-PM bootstrap. Not so cool. ' . 'Not your fault, please create a ticket at github.com/php-pm/php-pm with ' . 'the output of `ppm start -vv`.</error>' ) ; return ; } unset ( $ this -> slavesToReload [ $ slave -> getPort ( ) ] ) ; $ status = $ slave -> getStatus ( ) ; $ port = $ slave -> getPort ( ) ; if ( $ this -> output -> isVeryVerbose ( ) ) { $ this -> output -> writeln ( sprintf ( 'Worker #%d closed after %d handled requests' , $ port , $ slave -> getHandledRequests ( ) ) ) ; } $ this -> terminateSlave ( $ slave ) ; if ( $ status === Slave :: REGISTERED ) { $ this -> bootstrapFailed ( $ port ) ; } else { $ this -> newSlaveInstance ( $ port ) ; } }
|
Handle slave closed
|
3,442
|
protected function commandStatus ( array $ data , ConnectionInterface $ conn ) { $ conn -> removeAllListeners ( 'close' ) ; if ( $ this -> output -> isVeryVerbose ( ) ) { $ conn -> on ( 'close' , function ( ) { $ this -> output -> writeln ( 'Status command requested' ) ; } ) ; } $ requests = array_reduce ( $ this -> slaves -> getByStatus ( Slave :: ANY ) , function ( $ carry , Slave $ slave ) { $ carry [ $ slave -> getPort ( ) ] = 0 + $ slave -> getHandledRequests ( ) ; return $ carry ; } , [ ] ) ; switch ( $ this -> status ) { case self :: STATE_STARTING : $ status = 'starting' ; break ; case self :: STATE_RUNNING : $ status = 'healthy' ; break ; case self :: STATE_EMERGENCY : $ status = 'offline' ; break ; default : $ status = 'unknown' ; } $ conn -> end ( json_encode ( [ 'status' => $ status , 'workers' => $ this -> slaves -> getStatusSummary ( ) , 'handled_requests' => $ this -> handledRequests , 'handled_requests_per_worker' => $ requests ] ) ) ; }
|
A slave sent a status command .
|
3,443
|
protected function commandStop ( array $ data , ConnectionInterface $ conn ) { if ( $ this -> output -> isVeryVerbose ( ) ) { $ conn -> on ( 'close' , function ( ) { $ this -> output -> writeln ( 'Stop command requested' ) ; } ) ; } $ conn -> end ( json_encode ( [ ] ) ) ; $ this -> shutdown ( ) ; }
|
A slave sent a stop command .
|
3,444
|
protected function commandReload ( array $ data , ConnectionInterface $ conn ) { $ conn -> removeAllListeners ( 'close' ) ; if ( $ this -> output -> isVeryVerbose ( ) ) { $ conn -> on ( 'close' , function ( ) { $ this -> output -> writeln ( 'Reload command requested' ) ; } ) ; } $ conn -> end ( json_encode ( [ ] ) ) ; $ this -> reloadSlaves ( ) ; }
|
A slave sent a reload command .
|
3,445
|
protected function commandRegister ( array $ data , ConnectionInterface $ conn ) { $ pid = ( int ) $ data [ 'pid' ] ; $ port = ( int ) $ data [ 'port' ] ; try { $ slave = $ this -> slaves -> getByPort ( $ port ) ; $ slave -> register ( $ pid , $ conn ) ; } catch ( \ Exception $ e ) { $ this -> output -> writeln ( sprintf ( '<error>Worker #%d wanted to register on master which was not expected.</error>' , $ port ) ) ; $ conn -> close ( ) ; return ; } if ( $ this -> output -> isVeryVerbose ( ) ) { $ this -> output -> writeln ( sprintf ( 'Worker #%d registered. Waiting for application bootstrap ... ' , $ port ) ) ; } $ this -> sendMessage ( $ conn , 'bootstrap' ) ; }
|
A slave sent a register command .
|
3,446
|
protected function commandReady ( array $ data , ConnectionInterface $ conn ) { try { $ slave = $ this -> slaves -> getByConnection ( $ conn ) ; } catch ( \ Exception $ e ) { $ this -> output -> writeln ( '<error>A ready command was sent by a worker with no connection. This was unexpected. ' . 'Not your fault, please create a ticket at github.com/php-pm/php-pm with ' . 'the output of `ppm start -vv`.</error>' ) ; return ; } $ slave -> ready ( ) ; if ( $ this -> output -> isVeryVerbose ( ) ) { $ this -> output -> writeln ( sprintf ( 'Worker #%d ready.' , $ slave -> getPort ( ) ) ) ; } if ( $ this -> allSlavesReady ( ) ) { if ( $ this -> status === self :: STATE_EMERGENCY ) { $ this -> output -> writeln ( "<info>Emergency survived. Workers up and running again.</info>" ) ; } else { $ this -> output -> writeln ( sprintf ( "<info>%d workers (starting at %d) up and ready. Application is ready at http://%s:%s/</info>" , $ this -> slaveCount , self :: CONTROLLER_PORT + 1 , $ this -> host , $ this -> port ) ) ; } $ this -> status = self :: STATE_RUNNING ; } }
|
A slave sent a ready commands which basically says that the slave bootstrapped successfully the application and is ready to accept connections .
|
3,447
|
protected function commandFiles ( array $ data , ConnectionInterface $ conn ) { try { $ slave = $ this -> slaves -> getByConnection ( $ conn ) ; $ start = microtime ( true ) ; clearstatcache ( ) ; $ newFilesCount = 0 ; $ knownFiles = array_keys ( $ this -> filesLastMTime ) ; $ recentlyIncludedFiles = array_diff ( $ data [ 'files' ] , $ knownFiles ) ; foreach ( $ recentlyIncludedFiles as $ filePath ) { if ( file_exists ( $ filePath ) ) { $ this -> filesLastMTime [ $ filePath ] = filemtime ( $ filePath ) ; $ this -> filesLastMd5 [ $ filePath ] = md5_file ( $ filePath , true ) ; $ newFilesCount ++ ; } } if ( $ this -> output -> isVeryVerbose ( ) ) { $ this -> output -> writeln ( sprintf ( 'Received %d new files from %d. Stats collection cycle: %u files, %.3f ms' , $ newFilesCount , $ slave -> getPort ( ) , count ( $ this -> filesLastMTime ) , ( microtime ( true ) - $ start ) * 1000 ) ) ; } } catch ( \ Exception $ e ) { } }
|
Register client files for change tracking
|
3,448
|
protected function commandStats ( array $ data , ConnectionInterface $ conn ) { try { $ slave = $ this -> slaves -> getByConnection ( $ conn ) ; $ slave -> setUsedMemory ( $ data [ 'memory_usage' ] ) ; if ( $ this -> output -> isVeryVerbose ( ) ) { $ this -> output -> writeln ( sprintf ( 'Current memory usage for worker %d: %.2f MB' , $ slave -> getPort ( ) , $ data [ 'memory_usage' ] ) ) ; } } catch ( \ Exception $ e ) { } }
|
Receive stats from the worker such as current memory use
|
3,449
|
protected function bootstrapFailed ( $ port ) { if ( $ this -> isDebug ( ) ) { $ this -> output -> writeln ( '' ) ; if ( $ this -> status !== self :: STATE_EMERGENCY ) { $ this -> status = self :: STATE_EMERGENCY ; $ this -> output -> writeln ( sprintf ( '<error>Application bootstrap failed. We are entering emergency mode now. All offline. ' . 'Waiting for file changes ...</error>' ) ) ; } else { $ this -> output -> writeln ( sprintf ( '<error>Application bootstrap failed. We are still in emergency mode. All offline. ' . 'Waiting for file changes ...</error>' ) ) ; } $ this -> reloadSlaves ( false ) ; } else { $ this -> output -> writeln ( sprintf ( '<error>Application bootstrap failed. Restarting worker #%d ...</error>' , $ port ) ) ; $ this -> newSlaveInstance ( $ port ) ; } }
|
Handles failed application bootstraps .
|
3,450
|
protected function checkChangedFiles ( $ restartSlaves = true ) { if ( $ this -> inChangesDetectionCycle ) { return false ; } $ start = microtime ( true ) ; $ hasChanged = false ; $ this -> inChangesDetectionCycle = true ; clearstatcache ( ) ; foreach ( $ this -> filesLastMTime as $ filePath => $ knownMTime ) { if ( ! file_exists ( $ filePath ) ) { continue ; } $ actualFileTime = filemtime ( $ filePath ) ; $ actualFileHash = md5_file ( $ filePath ) ; if ( $ knownMTime !== $ actualFileTime && $ this -> filesLastMd5 [ $ filePath ] !== $ actualFileHash ) { $ this -> filesLastMd5 [ $ filePath ] = $ actualFileHash ; $ this -> filesLastMTime [ $ filePath ] = $ actualFileTime ; $ this -> output -> writeln ( sprintf ( "<info>[%s] File %s has changed.</info>" , date ( 'd/M/Y:H:i:s O' ) , $ filePath ) ) ; $ hasChanged = true ; break ; } } if ( $ hasChanged ) { $ this -> output -> writeln ( sprintf ( "<info>[%s] At least one of %u known files was changed. Reloading workers.</info>" , date ( 'd/M/Y:H:i:s O' ) , count ( $ this -> filesLastMTime ) ) ) ; if ( $ this -> output -> isVeryVerbose ( ) ) { $ this -> output -> writeln ( sprintf ( "Changes detection cycle length = %.3f ms" , ( microtime ( true ) - $ start ) * 1000 ) ) ; } if ( $ restartSlaves ) { $ this -> restartSlaves ( ) ; } } $ this -> inChangesDetectionCycle = false ; return $ hasChanged ; }
|
Checks if tracked files have changed . If so restart all slaves .
|
3,451
|
public function createSlaves ( ) { for ( $ i = 1 ; $ i <= $ this -> slaveCount ; $ i ++ ) { $ this -> newSlaveInstance ( self :: CONTROLLER_PORT + $ i ) ; } }
|
Populate slave pool
|
3,452
|
protected function closeSlave ( $ slave ) { $ slave -> close ( ) ; $ this -> slaves -> remove ( $ slave ) ; if ( ! empty ( $ slave -> getConnection ( ) ) ) { $ connection = $ slave -> getConnection ( ) ; $ connection -> removeAllListeners ( 'close' ) ; $ connection -> close ( ) ; } }
|
Close a slave
|
3,453
|
public function reloadSlaves ( $ graceful = true ) { $ this -> output -> writeln ( '<info>Reloading all workers gracefully</info>' ) ; $ this -> closeSlaves ( $ graceful , function ( $ slave ) { if ( $ this -> output -> isVeryVerbose ( ) ) { $ this -> output -> writeln ( sprintf ( 'Worker #%d has been closed, reloading.' , $ slave -> getPort ( ) ) ) ; } $ this -> newSlaveInstance ( $ slave -> getPort ( ) ) ; } ) ; }
|
Reload slaves in - place allowing busy workers to finish what they are doing .
|
3,454
|
public function closeSlaves ( $ graceful = false , $ onSlaveClosed = null ) { if ( ! $ onSlaveClosed ) { $ onSlaveClosed = function ( $ slave ) { } ; } $ this -> slavesToReload = [ ] ; foreach ( $ this -> slaves -> getByStatus ( Slave :: ANY ) as $ slave ) { $ connection = $ slave -> getConnection ( ) ; if ( $ connection ) { $ connection -> on ( 'close' , function ( ) use ( $ onSlaveClosed , $ slave ) { $ onSlaveClosed ( $ slave ) ; } ) ; } if ( $ graceful && $ slave -> getStatus ( ) === Slave :: BUSY ) { if ( $ this -> output -> isVeryVerbose ( ) ) { $ this -> output -> writeln ( sprintf ( 'Waiting for worker #%d to finish' , $ slave -> getPort ( ) ) ) ; } $ slave -> lock ( ) ; $ this -> slavesToReload [ $ slave -> getPort ( ) ] = $ slave ; } elseif ( $ graceful && $ slave -> getStatus ( ) === Slave :: LOCKED ) { if ( $ this -> output -> isVeryVerbose ( ) ) { $ this -> output -> writeln ( sprintf ( 'Still waiting for worker #%d to finish from an earlier reload' , $ slave -> getPort ( ) ) ) ; } $ this -> slavesToReload [ $ slave -> getPort ( ) ] = $ slave ; } else { $ this -> closeSlave ( $ slave ) ; $ onSlaveClosed ( $ slave ) ; } } if ( $ this -> reloadTimeoutTimer !== null ) { $ this -> loop -> cancelTimer ( $ this -> reloadTimeoutTimer ) ; } $ this -> reloadTimeoutTimer = $ this -> loop -> addTimer ( $ this -> reloadTimeout , function ( ) use ( $ onSlaveClosed ) { if ( $ this -> slavesToReload && $ this -> output -> isVeryVerbose ( ) ) { $ this -> output -> writeln ( 'Cleaning up workers that exceeded the graceful reload timeout.' ) ; } foreach ( $ this -> slavesToReload as $ slave ) { $ this -> output -> writeln ( sprintf ( '<error>Worker #%d exceeded the graceful reload timeout and was killed.</error>' , $ slave -> getPort ( ) ) ) ; $ this -> closeSlave ( $ slave ) ; $ onSlaveClosed ( $ slave ) ; } } ) ; }
|
Closes all slaves and fires a user - defined callback for each slave that is closed .
|
3,455
|
public function restartSlaves ( ) { if ( $ this -> inRestart ) { return ; } $ this -> inRestart = true ; $ this -> closeSlaves ( ) ; $ this -> createSlaves ( ) ; $ this -> inRestart = false ; }
|
Restart all slaves . Necessary when watched files have changed .
|
3,456
|
protected function allSlavesReady ( ) { if ( $ this -> status === self :: STATE_STARTING || $ this -> status === self :: STATE_EMERGENCY ) { $ readySlaves = $ this -> slaves -> getByStatus ( Slave :: READY ) ; $ busySlaves = $ this -> slaves -> getByStatus ( Slave :: BUSY ) ; return count ( $ readySlaves ) + count ( $ busySlaves ) === $ this -> slaveCount ; } return false ; }
|
Check if all slaves have become available
|
3,457
|
protected function newSlaveInstance ( $ port ) { if ( $ this -> status === self :: STATE_SHUTDOWN ) { return ; } if ( $ this -> output -> isVeryVerbose ( ) ) { $ this -> output -> writeln ( sprintf ( "Start new worker #%d" , $ port ) ) ; } $ socketpath = var_export ( $ this -> getSocketPath ( ) , true ) ; $ bridge = var_export ( $ this -> getBridge ( ) , true ) ; $ bootstrap = var_export ( $ this -> getAppBootstrap ( ) , true ) ; $ config = [ 'port' => $ port , 'session_path' => session_save_path ( ) , 'app-env' => $ this -> getAppEnv ( ) , 'debug' => $ this -> isDebug ( ) , 'logging' => $ this -> isLogging ( ) , 'static-directory' => $ this -> getStaticDirectory ( ) , 'populate-server-var' => $ this -> isPopulateServer ( ) ] ; $ config = var_export ( $ config , true ) ; $ dir = var_export ( __DIR__ . '/..' , true ) ; $ script = <<<EOF<?phpnamespace PHPPM;set_time_limit(0);require_once file_exists($dir . '/vendor/autoload.php') ? $dir . '/vendor/autoload.php' : $dir . '/../../autoload.php'; if (!pcntl_installed()) { error_log( sprintf( 'PCNTL is not enabled in the PHP installation at %s. See: http://php.net/manual/en/pcntl.installation.php', PHP_BINARY ) ); exit();}if (!pcntl_enabled()) { error_log('Some required PCNTL functions are disabled. Check `disabled_functions` in `php.ini`.'); exit();}//global for all global functionsProcessSlave::\$slave = new ProcessSlave($socketpath, $bridge, $bootstrap, $config);ProcessSlave::\$slave->run();EOF ; $ file = tempnam ( sys_get_temp_dir ( ) , 'dbg' ) ; file_put_contents ( $ file , $ script ) ; register_shutdown_function ( 'unlink' , $ file ) ; if ( method_exists ( '\Symfony\Component\Process\ProcessUtils' , 'escapeArgument' ) ) { $ commandline = 'exec ' . $ this -> phpCgiExecutable . ' -C ' . ProcessUtils :: escapeArgument ( $ file ) ; } else { $ commandline = [ 'exec' , $ this -> phpCgiExecutable , '-C' , $ file ] ; $ processInstance = new \ Symfony \ Component \ Process \ Process ( $ commandline ) ; $ commandline = $ processInstance -> getCommandLine ( ) ; } $ process = new Process ( $ commandline ) ; $ slave = new Slave ( $ port , $ this -> maxRequests , $ this -> memoryLimit , $ this -> ttl ) ; $ slave -> attach ( $ process ) ; $ this -> slaves -> add ( $ slave ) ; $ process -> start ( $ this -> loop ) ; $ process -> stderr -> on ( 'data' , function ( $ data ) use ( $ port ) { if ( $ this -> lastWorkerErrorPrintBy !== $ port ) { $ this -> output -> writeln ( "<info>--- Worker $port stderr ---</info>" ) ; $ this -> lastWorkerErrorPrintBy = $ port ; } $ this -> output -> write ( "<error>$data</error>" ) ; } ) ; }
|
Creates a new ProcessSlave instance .
|
3,458
|
protected function addLookupsForNestedProperty ( string $ property , Builder $ aggregationBuilder , string $ resourceClass ) : array { $ propertyParts = $ this -> splitPropertyParts ( $ property , $ resourceClass ) ; $ alias = '' ; foreach ( $ propertyParts [ 'associations' ] as $ association ) { $ classMetadata = $ this -> getClassMetadata ( $ resourceClass ) ; if ( ! $ classMetadata instanceof MongoDbOdmClassMetadata ) { break ; } if ( $ classMetadata -> hasReference ( $ association ) ) { $ propertyAlias = "${association}_lkup" ; $ localField = "$alias$association" ; $ alias .= $ propertyAlias ; $ referenceMapping = $ classMetadata -> getFieldMapping ( $ association ) ; if ( ( $ isOwningSide = $ referenceMapping [ 'isOwningSide' ] ) && MongoDbOdmClassMetadata :: REFERENCE_STORE_AS_ID !== $ referenceMapping [ 'storeAs' ] ) { throw MappingException :: cannotLookupDbRefReference ( $ classMetadata -> getReflectionClass ( ) -> getShortName ( ) , $ association ) ; } if ( ! $ isOwningSide ) { if ( isset ( $ referenceMapping [ 'repositoryMethod' ] ) || ! isset ( $ referenceMapping [ 'mappedBy' ] ) ) { throw MappingException :: repositoryMethodLookupNotAllowed ( $ classMetadata -> getReflectionClass ( ) -> getShortName ( ) , $ association ) ; } $ targetClassMetadata = $ this -> getClassMetadata ( $ referenceMapping [ 'targetDocument' ] ) ; if ( $ targetClassMetadata instanceof MongoDbOdmClassMetadata && MongoDbOdmClassMetadata :: REFERENCE_STORE_AS_ID !== $ targetClassMetadata -> getFieldMapping ( $ referenceMapping [ 'mappedBy' ] ) [ 'storeAs' ] ) { throw MappingException :: cannotLookupDbRefReference ( $ classMetadata -> getReflectionClass ( ) -> getShortName ( ) , $ association ) ; } } $ aggregationBuilder -> lookup ( $ classMetadata -> getAssociationTargetClass ( $ association ) ) -> localField ( $ isOwningSide ? $ localField : '_id' ) -> foreignField ( $ isOwningSide ? '_id' : $ referenceMapping [ 'mappedBy' ] ) -> alias ( $ alias ) ; $ aggregationBuilder -> unwind ( "\$$alias" ) ; $ property = substr_replace ( $ property , $ propertyAlias , strpos ( $ property , $ association ) , \ strlen ( $ association ) ) ; $ resourceClass = $ classMetadata -> getAssociationTargetClass ( $ association ) ; $ alias .= '.' ; } elseif ( $ classMetadata -> hasEmbed ( $ association ) ) { $ alias = "$association." ; $ resourceClass = $ classMetadata -> getAssociationTargetClass ( $ association ) ; } } if ( '' === $ alias ) { throw new InvalidArgumentException ( sprintf ( 'Cannot add lookups for property "%s" - property is not nested.' , $ property ) ) ; } return [ $ property , $ propertyParts [ 'field' ] , $ propertyParts [ 'associations' ] ] ; }
|
Adds the necessary lookups for a nested property .
|
3,459
|
private function formatWhitelist ( array $ whitelist ) : array { if ( array_values ( $ whitelist ) === $ whitelist ) { return $ whitelist ; } foreach ( $ whitelist as $ name => $ value ) { if ( null === $ value ) { unset ( $ whitelist [ $ name ] ) ; $ whitelist [ ] = $ name ; } } return $ whitelist ; }
|
Generate an array of whitelist properties to match the format that properties will have in the request .
|
3,460
|
private function populateIdentifier ( array $ data , string $ class ) : array { $ identifier = $ this -> identifierExtractor -> getIdentifierFromResourceClass ( $ class ) ; $ identifier = null === $ this -> nameConverter ? $ identifier : $ this -> nameConverter -> normalize ( $ identifier , $ class , self :: FORMAT ) ; if ( ! isset ( $ data [ '_source' ] [ $ identifier ] ) ) { $ data [ '_source' ] [ $ identifier ] = $ data [ '_id' ] ; } return $ data ; }
|
Populates the resource identifier with the document identifier if not present in the original JSON document .
|
3,461
|
protected function getPaginationConfig ( $ object , array $ context = [ ] ) : array { $ currentPage = $ lastPage = $ itemsPerPage = $ pageTotalItems = $ totalItems = null ; $ paginated = $ paginator = false ; if ( $ object instanceof PartialPaginatorInterface ) { $ paginated = $ paginator = true ; if ( $ object instanceof PaginatorInterface ) { $ paginated = 1. !== $ lastPage = $ object -> getLastPage ( ) ; $ totalItems = $ object -> getTotalItems ( ) ; } else { $ pageTotalItems = ( float ) \ count ( $ object ) ; } $ currentPage = $ object -> getCurrentPage ( ) ; $ itemsPerPage = $ object -> getItemsPerPage ( ) ; } elseif ( \ is_array ( $ object ) || $ object instanceof \ Countable ) { $ totalItems = \ count ( $ object ) ; } return [ $ paginator , $ paginated , $ currentPage , $ itemsPerPage , $ lastPage , $ pageTotalItems , $ totalItems ] ; }
|
Gets the pagination configuration .
|
3,462
|
private function getProperties ( string $ className , int $ specVersion = 2 ) : stdClass { return $ this -> getClassInfo ( $ className , $ specVersion ) -> { 'properties' } ?? new \ stdClass ( ) ; }
|
Gets all operations of a given class .
|
3,463
|
private function getLastJsonResponse ( ) : stdClass { if ( null === ( $ decoded = json_decode ( $ this -> restContext -> getMink ( ) -> getSession ( ) -> getDriver ( ) -> getContent ( ) ) ) ) { throw new \ RuntimeException ( 'JSON response seems to be invalid' ) ; } return $ decoded ; }
|
Gets the last JSON response .
|
3,464
|
public function withIndex ( string $ index ) : self { $ metadata = clone $ this ; $ metadata -> index = $ index ; return $ metadata ; }
|
Gets a new instance with the given index .
|
3,465
|
public function withType ( string $ type ) : self { $ metadata = clone $ this ; $ metadata -> type = $ type ; return $ metadata ; }
|
Gets a new instance with the given type .
|
3,466
|
public function onKernelRequest ( GetResponseEvent $ event ) : void { $ request = $ event -> getRequest ( ) ; if ( ! ( $ attributes = RequestAttributesExtractor :: extractAttributes ( $ request ) ) || ! $ attributes [ 'receive' ] ) { return ; } if ( null === $ filters = $ request -> attributes -> get ( '_api_filters' ) ) { $ queryString = RequestParser :: getQueryString ( $ request ) ; $ filters = $ queryString ? RequestParser :: parseRequestParams ( $ queryString ) : null ; } $ context = null === $ filters ? [ ] : [ 'filters' => $ filters ] ; if ( $ this -> serializerContextBuilder ) { $ context += $ normalizationContext = $ this -> serializerContextBuilder -> createFromRequest ( $ request , true , $ attributes ) ; $ request -> attributes -> set ( '_api_normalization_context' , $ normalizationContext ) ; } if ( isset ( $ attributes [ 'collection_operation_name' ] ) ) { $ request -> attributes -> set ( 'data' , $ request -> isMethod ( 'POST' ) ? null : $ this -> getCollectionData ( $ attributes , $ context ) ) ; return ; } $ data = [ ] ; if ( $ this -> identifierConverter ) { $ context [ IdentifierConverterInterface :: HAS_IDENTIFIER_CONVERTER ] = true ; } try { $ identifiers = $ this -> extractIdentifiers ( $ request -> attributes -> all ( ) , $ attributes ) ; if ( isset ( $ attributes [ 'item_operation_name' ] ) ) { $ data = $ this -> getItemData ( $ identifiers , $ attributes , $ context ) ; } elseif ( isset ( $ attributes [ 'subresource_operation_name' ] ) ) { if ( null === $ this -> subresourceDataProvider ) { throw new RuntimeException ( 'No subresource data provider.' ) ; } $ data = $ this -> getSubresourceData ( $ identifiers , $ attributes , $ context ) ; } } catch ( InvalidIdentifierException $ e ) { throw new NotFoundHttpException ( 'Not found, because of an invalid identifier configuration' , $ e ) ; } if ( null === $ data ) { throw new NotFoundHttpException ( 'Not Found' ) ; } $ request -> attributes -> set ( 'data' , $ data ) ; }
|
Calls the data provider and sets the data attribute .
|
3,467
|
protected function addWhere ( QueryBuilder $ queryBuilder , QueryNameGeneratorInterface $ queryNameGenerator , $ alias , $ field , $ operator , $ value ) { $ valueParameter = $ queryNameGenerator -> generateParameterName ( $ field ) ; switch ( $ operator ) { case self :: PARAMETER_BETWEEN : $ rangeValue = explode ( '..' , $ value ) ; $ rangeValue = $ this -> normalizeBetweenValues ( $ rangeValue ) ; if ( null === $ rangeValue ) { return ; } $ queryBuilder -> andWhere ( sprintf ( '%1$s.%2$s BETWEEN :%3$s_1 AND :%3$s_2' , $ alias , $ field , $ valueParameter ) ) -> setParameter ( sprintf ( '%s_1' , $ valueParameter ) , $ rangeValue [ 0 ] ) -> setParameter ( sprintf ( '%s_2' , $ valueParameter ) , $ rangeValue [ 1 ] ) ; break ; case self :: PARAMETER_GREATER_THAN : $ value = $ this -> normalizeValue ( $ value , $ operator ) ; if ( null === $ value ) { return ; } $ queryBuilder -> andWhere ( sprintf ( '%s.%s > :%s' , $ alias , $ field , $ valueParameter ) ) -> setParameter ( $ valueParameter , $ value ) ; break ; case self :: PARAMETER_GREATER_THAN_OR_EQUAL : $ value = $ this -> normalizeValue ( $ value , $ operator ) ; if ( null === $ value ) { return ; } $ queryBuilder -> andWhere ( sprintf ( '%s.%s >= :%s' , $ alias , $ field , $ valueParameter ) ) -> setParameter ( $ valueParameter , $ value ) ; break ; case self :: PARAMETER_LESS_THAN : $ value = $ this -> normalizeValue ( $ value , $ operator ) ; if ( null === $ value ) { return ; } $ queryBuilder -> andWhere ( sprintf ( '%s.%s < :%s' , $ alias , $ field , $ valueParameter ) ) -> setParameter ( $ valueParameter , $ value ) ; break ; case self :: PARAMETER_LESS_THAN_OR_EQUAL : $ value = $ this -> normalizeValue ( $ value , $ operator ) ; if ( null === $ value ) { return ; } $ queryBuilder -> andWhere ( sprintf ( '%s.%s <= :%s' , $ alias , $ field , $ valueParameter ) ) -> setParameter ( $ valueParameter , $ value ) ; break ; } }
|
Adds the where clause according to the operator .
|
3,468
|
private function getContext ( Request $ request , Documentation $ documentation ) : array { $ context = [ 'title' => $ this -> title , 'description' => $ this -> description , 'formats' => $ this -> formats , 'showWebby' => $ this -> showWebby , 'swaggerUiEnabled' => $ this -> swaggerUiEnabled , 'reDocEnabled' => $ this -> reDocEnabled , 'graphqlEnabled' => $ this -> graphqlEnabled , ] ; $ swaggerContext = [ 'spec_version' => $ request -> query -> getInt ( 'spec_version' , 2 ) ] ; if ( '' !== $ baseUrl = $ request -> getBaseUrl ( ) ) { $ swaggerContext [ 'base_url' ] = $ baseUrl ; } $ swaggerData = [ 'url' => $ this -> urlGenerator -> generate ( 'api_doc' , [ 'format' => 'json' ] ) , 'spec' => $ this -> normalizer -> normalize ( $ documentation , 'json' , $ swaggerContext ) , ] ; $ swaggerData [ 'oauth' ] = [ 'enabled' => $ this -> oauthEnabled , 'clientId' => $ this -> oauthClientId , 'clientSecret' => $ this -> oauthClientSecret , 'type' => $ this -> oauthType , 'flow' => $ this -> oauthFlow , 'tokenUrl' => $ this -> oauthTokenUrl , 'authorizationUrl' => $ this -> oauthAuthorizationUrl , 'scopes' => $ this -> oauthScopes , ] ; if ( $ request -> isMethodSafe ( false ) && null !== $ resourceClass = $ request -> attributes -> get ( '_api_resource_class' ) ) { $ swaggerData [ 'id' ] = $ request -> attributes -> get ( 'id' ) ; $ swaggerData [ 'queryParameters' ] = $ request -> query -> all ( ) ; $ metadata = $ this -> resourceMetadataFactory -> create ( $ resourceClass ) ; $ swaggerData [ 'shortName' ] = $ metadata -> getShortName ( ) ; if ( null !== $ collectionOperationName = $ request -> attributes -> get ( '_api_collection_operation_name' ) ) { $ swaggerData [ 'operationId' ] = sprintf ( '%s%sCollection' , $ collectionOperationName , ucfirst ( $ swaggerData [ 'shortName' ] ) ) ; } elseif ( null !== $ itemOperationName = $ request -> attributes -> get ( '_api_item_operation_name' ) ) { $ swaggerData [ 'operationId' ] = sprintf ( '%s%sItem' , $ itemOperationName , ucfirst ( $ swaggerData [ 'shortName' ] ) ) ; } elseif ( null !== $ subresourceOperationContext = $ request -> attributes -> get ( '_api_subresource_context' ) ) { $ swaggerData [ 'operationId' ] = $ subresourceOperationContext [ 'operationId' ] ; } [ $ swaggerData [ 'path' ] , $ swaggerData [ 'method' ] ] = $ this -> getPathAndMethod ( $ swaggerData ) ; } return $ context + [ 'swagger_data' => $ swaggerData ] ; }
|
Gets the base Twig context .
|
3,469
|
public static function hasRootEntityWithForeignKeyIdentifier ( QueryBuilder $ queryBuilder , ManagerRegistry $ managerRegistry ) : bool { foreach ( $ queryBuilder -> getRootEntities ( ) as $ rootEntity ) { $ rootMetadata = $ managerRegistry -> getManagerForClass ( $ rootEntity ) -> getClassMetadata ( $ rootEntity ) ; if ( $ rootMetadata -> containsForeignIdentifier ) { return true ; } } return false ; }
|
Determines whether the QueryBuilder has any root entity with foreign key identifier .
|
3,470
|
public static function hasRootEntityWithCompositeIdentifier ( QueryBuilder $ queryBuilder , ManagerRegistry $ managerRegistry ) : bool { foreach ( $ queryBuilder -> getRootEntities ( ) as $ rootEntity ) { $ rootMetadata = $ managerRegistry -> getManagerForClass ( $ rootEntity ) -> getClassMetadata ( $ rootEntity ) ; if ( $ rootMetadata -> isIdentifierComposite ) { return true ; } } return false ; }
|
Determines whether the QueryBuilder has any composite identifier .
|
3,471
|
public static function hasLeftJoin ( QueryBuilder $ queryBuilder ) : bool { foreach ( $ queryBuilder -> getDQLPart ( 'join' ) as $ joins ) { foreach ( $ joins as $ join ) { if ( Join :: LEFT_JOIN === $ join -> getJoinType ( ) ) { return true ; } } } return false ; }
|
Determines whether the QueryBuilder already has a left join .
|
3,472
|
public static function hasJoinedToManyAssociation ( QueryBuilder $ queryBuilder , ManagerRegistry $ managerRegistry ) : bool { if ( 0 === \ count ( $ queryBuilder -> getDQLPart ( 'join' ) ) ) { return false ; } $ joinAliases = array_diff ( $ queryBuilder -> getAllAliases ( ) , $ queryBuilder -> getRootAliases ( ) ) ; if ( 0 === \ count ( $ joinAliases ) ) { return false ; } foreach ( $ joinAliases as $ joinAlias ) { foreach ( QueryBuilderHelper :: traverseJoins ( $ joinAlias , $ queryBuilder , $ managerRegistry ) as $ alias => [ $ metadata , $ association ] ) { if ( null !== $ association && $ metadata -> isCollectionValuedAssociation ( $ association ) ) { return true ; } } } return false ; }
|
Determines whether the QueryBuilder has a joined to - many association .
|
3,473
|
public static function guessErrorFormat ( Request $ request , array $ errorFormats ) : array { $ requestFormat = $ request -> getRequestFormat ( '' ) ; if ( '' !== $ requestFormat && isset ( $ errorFormats [ $ requestFormat ] ) ) { return [ 'key' => $ requestFormat , 'value' => $ errorFormats [ $ requestFormat ] ] ; } $ requestMimeTypes = Request :: getMimeTypes ( $ request -> getRequestFormat ( ) ) ; $ defaultFormat = [ ] ; foreach ( $ errorFormats as $ format => $ errorMimeTypes ) { if ( array_intersect ( $ requestMimeTypes , $ errorMimeTypes ) ) { return [ 'key' => $ format , 'value' => $ errorMimeTypes ] ; } if ( ! $ defaultFormat ) { $ defaultFormat = [ 'key' => $ format , 'value' => $ errorMimeTypes ] ; } } return $ defaultFormat ; }
|
Get the error format and its associated MIME type .
|
3,474
|
private function getNormalizationContext ( string $ resourceClass , string $ contextType , array $ options ) : array { if ( null !== $ this -> requestStack && null !== $ this -> serializerContextBuilder && null !== $ request = $ this -> requestStack -> getCurrentRequest ( ) ) { return $ this -> serializerContextBuilder -> createFromRequest ( $ request , 'normalization_context' === $ contextType ) ; } $ resourceMetadata = $ this -> resourceMetadataFactory -> create ( $ resourceClass ) ; if ( isset ( $ options [ 'collection_operation_name' ] ) ) { $ context = $ resourceMetadata -> getCollectionOperationAttribute ( $ options [ 'collection_operation_name' ] , $ contextType , null , true ) ; } elseif ( isset ( $ options [ 'item_operation_name' ] ) ) { $ context = $ resourceMetadata -> getItemOperationAttribute ( $ options [ 'item_operation_name' ] , $ contextType , null , true ) ; } else { $ context = $ resourceMetadata -> getAttribute ( $ contextType ) ; } return $ context ?? [ ] ; }
|
Gets the serializer context .
|
3,475
|
public function onKernelView ( GetResponseForControllerResultEvent $ event ) : void { $ controllerResult = $ event -> getControllerResult ( ) ; $ request = $ event -> getRequest ( ) ; if ( $ controllerResult instanceof Response || ! ( ( $ attributes = RequestAttributesExtractor :: extractAttributes ( $ request ) ) [ 'respond' ] ?? $ request -> attributes -> getBoolean ( '_api_respond' , false ) ) ) { return ; } if ( ! $ attributes ) { $ this -> serializeRawData ( $ event , $ request , $ controllerResult ) ; return ; } $ context = $ this -> serializerContextBuilder -> createFromRequest ( $ request , true , $ attributes ) ; if ( isset ( $ context [ 'output' ] ) && \ array_key_exists ( 'class' , $ context [ 'output' ] ) && null === $ context [ 'output' ] [ 'class' ] ) { $ event -> setControllerResult ( null ) ; return ; } if ( $ included = $ request -> attributes -> get ( '_api_included' ) ) { $ context [ 'api_included' ] = $ included ; } $ resources = new ResourceList ( ) ; $ context [ 'resources' ] = & $ resources ; $ resourcesToPush = new ResourceList ( ) ; $ context [ 'resources_to_push' ] = & $ resourcesToPush ; $ request -> attributes -> set ( '_api_normalization_context' , $ context ) ; $ event -> setControllerResult ( $ this -> serializer -> serialize ( $ controllerResult , $ request -> getRequestFormat ( ) , $ context ) ) ; $ request -> attributes -> set ( '_resources' , $ request -> attributes -> get ( '_resources' , [ ] ) + ( array ) $ resources ) ; if ( ! \ count ( $ resourcesToPush ) ) { return ; } $ linkProvider = $ request -> attributes -> get ( '_links' , new GenericLinkProvider ( ) ) ; foreach ( $ resourcesToPush as $ resourceToPush ) { $ linkProvider = $ linkProvider -> withLink ( new Link ( 'preload' , $ resourceToPush ) ) ; } $ request -> attributes -> set ( '_links' , $ linkProvider ) ; }
|
Serializes the data to the requested format .
|
3,476
|
private function getQueryBuilderWithNewAliases ( QueryBuilder $ queryBuilder , QueryNameGeneratorInterface $ queryNameGenerator , string $ originAlias = 'o' , string $ replacement = 'o_2' ) : QueryBuilder { $ queryBuilderClone = clone $ queryBuilder ; $ joinParts = $ queryBuilder -> getDQLPart ( 'join' ) ; $ wherePart = $ queryBuilder -> getDQLPart ( 'where' ) ; $ queryBuilderClone -> resetDQLPart ( 'join' ) ; $ queryBuilderClone -> resetDQLPart ( 'where' ) ; $ queryBuilderClone -> resetDQLPart ( 'orderBy' ) ; $ queryBuilderClone -> resetDQLPart ( 'groupBy' ) ; $ queryBuilderClone -> resetDQLPart ( 'having' ) ; $ from = $ queryBuilderClone -> getDQLPart ( 'from' ) [ 0 ] ; $ queryBuilderClone -> resetDQLPart ( 'from' ) ; $ queryBuilderClone -> from ( $ from -> getFrom ( ) , $ replacement ) ; $ aliases = [ "$originAlias." ] ; $ replacements = [ "$replacement." ] ; foreach ( $ joinParts [ $ originAlias ] as $ joinPart ) { $ joinString = str_replace ( $ aliases , $ replacements , $ joinPart -> getJoin ( ) ) ; $ pos = strpos ( $ joinString , '.' ) ; if ( false === $ pos ) { if ( null !== $ joinPart -> getCondition ( ) && null !== $ this -> resourceClassResolver && $ this -> resourceClassResolver -> isResourceClass ( $ joinString ) ) { $ newAlias = $ queryNameGenerator -> generateJoinAlias ( $ joinPart -> getAlias ( ) ) ; $ aliases [ ] = "{$joinPart->getAlias()}." ; $ replacements [ ] = "$newAlias." ; $ condition = str_replace ( $ aliases , $ replacements , $ joinPart -> getCondition ( ) ) ; $ join = new Join ( $ joinPart -> getJoinType ( ) , $ joinPart -> getJoin ( ) , $ newAlias , $ joinPart -> getConditionType ( ) , $ condition ) ; $ queryBuilderClone -> add ( 'join' , [ $ replacement => $ join ] , true ) ; } continue ; } $ alias = substr ( $ joinString , 0 , $ pos ) ; $ association = substr ( $ joinString , $ pos + 1 ) ; $ condition = str_replace ( $ aliases , $ replacements , $ joinPart -> getCondition ( ) ) ; $ newAlias = QueryBuilderHelper :: addJoinOnce ( $ queryBuilderClone , $ queryNameGenerator , $ alias , $ association , $ joinPart -> getJoinType ( ) , $ joinPart -> getConditionType ( ) , $ condition , $ originAlias ) ; $ aliases [ ] = "{$joinPart->getAlias()}." ; $ replacements [ ] = "$newAlias." ; } $ queryBuilderClone -> add ( 'where' , str_replace ( $ aliases , $ replacements , ( string ) $ wherePart ) ) ; return $ queryBuilderClone ; }
|
Returns a clone of the given query builder where everything gets re - aliased .
|
3,477
|
private function getOperationRoute ( string $ resourceClass , string $ operationName , string $ operationType ) : Route { $ routeName = $ this -> getRouteName ( $ this -> resourceMetadataFactory -> create ( $ resourceClass ) , $ operationName , $ operationType ) ; if ( null !== $ routeName ) { return $ this -> getRoute ( $ routeName ) ; } $ operationNameKey = sprintf ( '_api_%s_operation_name' , $ operationType ) ; foreach ( $ this -> router -> getRouteCollection ( ) -> all ( ) as $ routeName => $ route ) { $ currentResourceClass = $ route -> getDefault ( '_api_resource_class' ) ; $ currentOperationName = $ route -> getDefault ( $ operationNameKey ) ; if ( $ resourceClass === $ currentResourceClass && $ operationName === $ currentOperationName ) { return $ route ; } } throw new RuntimeException ( sprintf ( 'No route found for operation "%s" for type "%s".' , $ operationName , $ resourceClass ) ) ; }
|
Gets the route related to the given operation .
|
3,478
|
private function getRouteName ( ResourceMetadata $ resourceMetadata , string $ operationName , string $ operationType ) : ? string { if ( OperationType :: ITEM === $ operationType ) { return $ resourceMetadata -> getItemOperationAttribute ( $ operationName , 'route_name' ) ; } return $ resourceMetadata -> getCollectionOperationAttribute ( $ operationName , 'route_name' ) ; }
|
Gets the route name or null if not defined .
|
3,479
|
private function getRoute ( string $ routeName ) : Route { foreach ( $ this -> router -> getRouteCollection ( ) as $ name => $ route ) { if ( $ routeName === $ name ) { return $ route ; } } throw new RuntimeException ( sprintf ( 'The route "%s" does not exist.' , $ routeName ) ) ; }
|
Gets the route with the given name .
|
3,480
|
private function getOperations ( \ SimpleXMLElement $ resource , string $ operationType ) : ? array { $ graphql = 'operation' === $ operationType ; if ( ! $ graphql && $ legacyOperations = $ this -> getAttributes ( $ resource , $ operationType ) ) { @ trigger_error ( sprintf ( 'Configuring "%1$s" tags without using a parent "%1$ss" tag is deprecated since API Platform 2.1 and will not be possible anymore in API Platform 3' , $ operationType ) , E_USER_DEPRECATED ) ; return $ legacyOperations ; } $ operationsParent = $ graphql ? 'graphql' : "{$operationType}s" ; if ( ! isset ( $ resource -> { $ operationsParent } ) ) { return null ; } return $ this -> getAttributes ( $ resource -> { $ operationsParent } , $ operationType , true ) ; }
|
Returns the array containing configured operations . Returns NULL if there is no operation configuration .
|
3,481
|
private function getAttributes ( \ SimpleXMLElement $ resource , string $ elementName , bool $ topLevel = false ) : array { $ attributes = [ ] ; foreach ( $ resource -> { $ elementName } as $ attribute ) { $ value = isset ( $ attribute -> attribute [ 0 ] ) ? $ this -> getAttributes ( $ attribute , 'attribute' ) : XmlUtils :: phpize ( $ attribute ) ; if ( $ topLevel && '' === $ value ) { $ value = [ ] ; } if ( isset ( $ attribute [ 'name' ] ) ) { $ attributes [ ( string ) $ attribute [ 'name' ] ] = $ value ; } else { $ attributes [ ] = $ value ; } } return $ attributes ; }
|
Recursively transforms an attribute structure into an associative array .
|
3,482
|
private function getProperties ( \ SimpleXMLElement $ resource ) : array { $ properties = [ ] ; foreach ( $ resource -> property as $ property ) { $ properties [ ( string ) $ property [ 'name' ] ] = [ 'description' => $ this -> phpize ( $ property , 'description' , 'string' ) , 'readable' => $ this -> phpize ( $ property , 'readable' , 'bool' ) , 'writable' => $ this -> phpize ( $ property , 'writable' , 'bool' ) , 'readableLink' => $ this -> phpize ( $ property , 'readableLink' , 'bool' ) , 'writableLink' => $ this -> phpize ( $ property , 'writableLink' , 'bool' ) , 'required' => $ this -> phpize ( $ property , 'required' , 'bool' ) , 'identifier' => $ this -> phpize ( $ property , 'identifier' , 'bool' ) , 'iri' => $ this -> phpize ( $ property , 'iri' , 'string' ) , 'attributes' => $ this -> getAttributes ( $ property , 'attribute' ) , 'subresource' => $ property -> subresource ? [ 'collection' => $ this -> phpize ( $ property -> subresource , 'collection' , 'bool' ) , 'resourceClass' => $ this -> phpize ( $ property -> subresource , 'resourceClass' , 'string' ) , 'maxDepth' => $ this -> phpize ( $ property -> subresource , 'maxDepth' , 'integer' ) , ] : null , ] ; } return $ properties ; }
|
Gets metadata of a property .
|
3,483
|
private function phpize ( \ SimpleXMLElement $ array , string $ key , string $ type ) { if ( ! isset ( $ array [ $ key ] ) ) { return null ; } switch ( $ type ) { case 'string' : return ( string ) $ array [ $ key ] ; case 'integer' : return ( int ) $ array [ $ key ] ; case 'bool' : return ( bool ) XmlUtils :: phpize ( $ array [ $ key ] ) ; } return null ; }
|
Transforms an XML attribute s value in a PHP value .
|
3,484
|
public function onKernelRequest ( GetResponseEvent $ event ) : void { $ request = $ event -> getRequest ( ) ; $ method = $ request -> getMethod ( ) ; if ( 'DELETE' === $ method || $ request -> isMethodSafe ( false ) || ! ( $ attributes = RequestAttributesExtractor :: extractAttributes ( $ request ) ) || ! $ attributes [ 'receive' ] || ( '' === ( $ requestContent = $ request -> getContent ( ) ) && ( 'POST' === $ method || 'PUT' === $ method ) ) ) { return ; } $ context = $ this -> serializerContextBuilder -> createFromRequest ( $ request , false , $ attributes ) ; if ( isset ( $ context [ 'input' ] ) && \ array_key_exists ( 'class' , $ context [ 'input' ] ) && null === $ context [ 'input' ] [ 'class' ] ) { return ; } if ( null !== $ this -> formatsProvider ) { $ this -> formats = $ this -> formatsProvider -> getFormatsFromAttributes ( $ attributes ) ; } $ this -> formatMatcher = new FormatMatcher ( $ this -> formats ) ; $ format = $ this -> getFormat ( $ request ) ; $ data = $ request -> attributes -> get ( 'data' ) ; if ( null !== $ data ) { $ context [ AbstractNormalizer :: OBJECT_TO_POPULATE ] = $ data ; } $ request -> attributes -> set ( 'data' , $ this -> serializer -> deserialize ( $ requestContent , $ context [ 'resource_class' ] , $ format , $ context ) ) ; }
|
Deserializes the data sent in the requested format .
|
3,485
|
private function getFormat ( Request $ request ) : string { $ contentType = $ request -> headers -> get ( 'CONTENT_TYPE' ) ; if ( null === $ contentType ) { throw new NotAcceptableHttpException ( 'The "Content-Type" header must exist.' ) ; } $ format = $ this -> formatMatcher -> getFormat ( $ contentType ) ; if ( null === $ format || ! isset ( $ this -> formats [ $ format ] ) ) { $ supportedMimeTypes = [ ] ; foreach ( $ this -> formats as $ mimeTypes ) { foreach ( $ mimeTypes as $ mimeType ) { $ supportedMimeTypes [ ] = $ mimeType ; } } throw new NotAcceptableHttpException ( sprintf ( 'The content-type "%s" is not supported. Supported MIME types are "%s".' , $ contentType , implode ( '", "' , $ supportedMimeTypes ) ) ) ; } return $ format ; }
|
Extracts the format from the Content - Type header and check that it is supported .
|
3,486
|
private function getRealClassName ( string $ className ) : string { if ( ( false === $ positionCg = strrpos ( $ className , '\\__CG__\\' ) ) && ( false === $ positionPm = strrpos ( $ className , '\\__PM__\\' ) ) ) { return $ className ; } if ( false !== $ positionCg ) { return substr ( $ className , $ positionCg + 8 ) ; } $ className = ltrim ( $ className , '\\' ) ; return substr ( $ className , 8 + $ positionPm , strrpos ( $ className , '\\' ) - ( $ positionPm + 8 ) ) ; }
|
Get the real class name of a class name that could be a proxy .
|
3,487
|
private function getItemData ( $ identifiers , array $ attributes , array $ context ) { return $ this -> itemDataProvider -> getItem ( $ attributes [ 'resource_class' ] , $ identifiers , $ attributes [ 'item_operation_name' ] , $ context ) ; }
|
Gets data for an item operation .
|
3,488
|
private function getSubresourceData ( $ identifiers , array $ attributes , array $ context ) { if ( null === $ this -> subresourceDataProvider ) { throw new RuntimeException ( 'Subresources not supported' ) ; } return $ this -> subresourceDataProvider -> getSubresource ( $ attributes [ 'resource_class' ] , $ identifiers , $ attributes [ 'subresource_context' ] + $ context , $ attributes [ 'subresource_operation_name' ] ) ; }
|
Gets data for a nested operation .
|
3,489
|
private function registerSwaggerConfiguration ( ContainerBuilder $ container , array $ config , XmlFileLoader $ loader ) : void { if ( ! $ config [ 'enable_swagger' ] ) { return ; } $ loader -> load ( 'swagger.xml' ) ; if ( $ config [ 'enable_swagger_ui' ] || $ config [ 'enable_re_doc' ] ) { $ loader -> load ( 'swagger-ui.xml' ) ; $ container -> setParameter ( 'api_platform.enable_swagger_ui' , $ config [ 'enable_swagger_ui' ] ) ; $ container -> setParameter ( 'api_platform.enable_re_doc' , $ config [ 'enable_re_doc' ] ) ; } $ container -> setParameter ( 'api_platform.enable_swagger' , $ config [ 'enable_swagger' ] ) ; $ container -> setParameter ( 'api_platform.swagger.api_keys' , $ config [ 'swagger' ] [ 'api_keys' ] ) ; }
|
Registers the Swagger ReDoc and Swagger UI configuration .
|
3,490
|
private function getFormats ( array $ configFormats ) : array { $ formats = [ ] ; foreach ( $ configFormats as $ format => $ value ) { foreach ( $ value [ 'mime_types' ] as $ mimeType ) { $ formats [ $ format ] [ ] = $ mimeType ; } } return $ formats ; }
|
Normalizes the format from config to the one accepted by Symfony HttpFoundation .
|
3,491
|
private function addJsonLdContext ( ContextBuilderInterface $ contextBuilder , string $ resourceClass , array & $ context , array $ data = [ ] ) : array { if ( isset ( $ context [ 'jsonld_has_context' ] ) ) { return $ data ; } $ context [ 'jsonld_has_context' ] = true ; if ( isset ( $ context [ 'jsonld_embed_context' ] ) ) { $ data [ '@context' ] = $ contextBuilder -> getResourceContext ( $ resourceClass ) ; return $ data ; } $ data [ '@context' ] = $ contextBuilder -> getResourceContextUri ( $ resourceClass ) ; return $ data ; }
|
Updates the given JSON - LD document to add its
|
3,492
|
private function addRequestFormats ( Request $ request , array $ formats ) : void { foreach ( $ formats as $ format => $ mimeTypes ) { $ request -> setFormat ( $ format , ( array ) $ mimeTypes ) ; } }
|
Adds the supported formats to the request .
|
3,493
|
private function getNotAcceptableHttpException ( string $ accept , array $ mimeTypes = null ) : NotAcceptableHttpException { if ( null === $ mimeTypes ) { $ mimeTypes = array_keys ( $ this -> mimeTypes ) ; } return new NotAcceptableHttpException ( sprintf ( 'Requested format "%s" is not supported. Supported MIME types are "%s".' , $ accept , implode ( '", "' , $ mimeTypes ) ) ) ; }
|
Retrieves an instance of NotAcceptableHttpException .
|
3,494
|
public function getProperty ( string $ methodName ) : ? string { $ pattern = implode ( '|' , array_merge ( self :: ACCESSOR_PREFIXES , self :: MUTATOR_PREFIXES ) ) ; if ( preg_match ( '/^(' . $ pattern . ')(.+)$/i' , $ methodName , $ matches ) ) { return $ matches [ 2 ] ; } return null ; }
|
Gets the property name associated with an accessor method .
|
3,495
|
public function getOffset ( string $ resourceClass = null , string $ operationName = null , array $ context = [ ] ) : int { $ graphql = $ context [ 'graphql' ] ?? false ; $ limit = $ this -> getLimit ( $ resourceClass , $ operationName , $ context ) ; if ( $ graphql && null !== ( $ after = $ this -> getParameterFromContext ( $ context , 'after' ) ) ) { return false === ( $ after = base64_decode ( $ after , true ) ) ? 0 : ( int ) $ after + 1 ; } if ( $ graphql && null !== ( $ before = $ this -> getParameterFromContext ( $ context , 'before' ) ) ) { return ( $ offset = ( false === ( $ before = base64_decode ( $ before , true ) ) ? 0 : ( int ) $ before - $ limit ) ) < 0 ? 0 : $ offset ; } if ( $ graphql && null !== ( $ last = $ this -> getParameterFromContext ( $ context , 'last' ) ) ) { return ( $ offset = ( $ context [ 'count' ] ?? 0 ) - $ last ) < 0 ? 0 : $ offset ; } return ( $ this -> getPage ( $ context ) - 1 ) * $ limit ; }
|
Gets the current offset .
|
3,496
|
public function getLimit ( string $ resourceClass = null , string $ operationName = null , array $ context = [ ] ) : int { $ graphql = $ context [ 'graphql' ] ?? false ; $ limit = $ this -> options [ 'items_per_page' ] ; $ clientLimit = $ this -> options [ 'client_items_per_page' ] ; if ( null !== $ resourceClass ) { $ resourceMetadata = $ this -> resourceMetadataFactory -> create ( $ resourceClass ) ; $ limit = $ resourceMetadata -> getCollectionOperationAttribute ( $ operationName , 'pagination_items_per_page' , $ limit , true ) ; $ clientLimit = $ resourceMetadata -> getCollectionOperationAttribute ( $ operationName , 'pagination_client_items_per_page' , $ clientLimit , true ) ; } if ( $ graphql && null !== ( $ first = $ this -> getParameterFromContext ( $ context , 'first' ) ) ) { $ limit = $ first ; } if ( $ graphql && null !== ( $ last = $ this -> getParameterFromContext ( $ context , 'last' ) ) ) { $ limit = $ last ; } if ( $ graphql && null !== ( $ before = $ this -> getParameterFromContext ( $ context , 'before' ) ) && ( false === ( $ before = base64_decode ( $ before , true ) ) ? 0 : ( int ) $ before - $ limit ) < 0 ) { $ limit = ( int ) $ before ; } if ( $ clientLimit ) { $ limit = ( int ) $ this -> getParameterFromContext ( $ context , $ this -> options [ 'items_per_page_parameter_name' ] , $ limit ) ; $ maxItemsPerPage = $ this -> options [ 'maximum_items_per_page' ] ; if ( null !== $ resourceClass ) { $ resourceMetadata = $ this -> resourceMetadataFactory -> create ( $ resourceClass ) ; $ maxItemsPerPage = $ resourceMetadata -> getCollectionOperationAttribute ( $ operationName , 'maximum_items_per_page' , $ maxItemsPerPage , true ) ; } if ( null !== $ maxItemsPerPage && $ limit > $ maxItemsPerPage ) { $ limit = $ maxItemsPerPage ; } } if ( 0 > $ limit ) { throw new InvalidArgumentException ( 'Limit should not be less than 0' ) ; } return $ limit ; }
|
Gets the current limit .
|
3,497
|
public function getPagination ( string $ resourceClass = null , string $ operationName = null , array $ context = [ ] ) : array { $ page = $ this -> getPage ( $ context ) ; $ limit = $ this -> getLimit ( $ resourceClass , $ operationName , $ context ) ; if ( 0 === $ limit && 1 < $ page ) { throw new InvalidArgumentException ( 'Page should not be greater than 1 if limit is equal to 0' ) ; } return [ $ page , $ this -> getOffset ( $ resourceClass , $ operationName , $ context ) , $ limit ] ; }
|
Gets info about the pagination .
|
3,498
|
public function isEnabled ( string $ resourceClass = null , string $ operationName = null , array $ context = [ ] ) : bool { return $ this -> getEnabled ( $ context , $ resourceClass , $ operationName ) ; }
|
Is the pagination enabled?
|
3,499
|
public function isPartialEnabled ( string $ resourceClass = null , string $ operationName = null , array $ context = [ ] ) : bool { return $ this -> getEnabled ( $ context , $ resourceClass , $ operationName , true ) ; }
|
Is the partial pagination enabled?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.