idx int64 0 60.3k | question stringlengths 64 4.24k | target stringlengths 5 618 |
|---|---|---|
22,400 | public static function lcm ( $ a , $ b ) { return ( abs ( $ a * $ b ) / self :: gcd ( $ a , $ b ) ) ; } | Computes the least common multiple . |
22,401 | public function isPenultimate ( $ identifier ) { $ this -> getLast ( ) ; $ iterator = $ this -> getIterator ( ) ; $ iterator -> seek ( $ iterator -> count ( ) - 2 ) ; $ penultimate = $ iterator -> current ( ) ; if ( $ identifier instanceof StepController ) { $ identifierName = $ identifier -> getName ( ) ; if ( $ identifierName == $ penultimate -> getName ( ) ) return true ; else return false ; } return false ; } | return true if IdentifierStep is the penultimate Step |
22,402 | public function beforePrepare ( Event $ event ) { $ command = $ event [ 'command' ] ; $ operation = $ command -> getOperation ( ) ; if ( $ command -> getName ( ) !== 'updateEntity' && $ command -> offsetExists ( '_id' ) === true ) return ; $ operation -> addParam ( new Parameter ( array ( 'name' => 'body_id' , 'location' => 'json' , 'type' => 'string' , 'default' => $ command -> offsetGet ( '_id' ) , 'static' => true , 'sentAs' => '_id' ) ) ) ; } | Add the entity s _id to the request body . |
22,403 | public static function multisort ( $ array , $ params ) { static :: $ _cache = array ( ) ; $ isNumeric = is_numeric ( implode ( '' , array_keys ( $ array ) ) ) ; if ( is_array ( $ params ) ) { static :: _normalizeParams ( $ params ) ; $ callback = function ( $ a , $ b ) use ( $ params ) { $ result = 0 ; foreach ( $ params as $ param ) { $ valA = static :: _getValue ( $ param [ 'field' ] , $ a ) ; $ valB = static :: _getValue ( $ param [ 'field' ] , $ b ) ; if ( $ valA > $ valB ) { $ result = 1 ; } elseif ( $ valA < $ valB ) { $ result = - 1 ; } if ( $ result !== 0 ) { if ( strtolower ( $ param [ 'direction' ] ) === 'desc' ) { $ result *= - 1 ; } break ; } } return $ result ; } ; if ( $ isNumeric ) { usort ( $ array , $ callback ) ; } else { uasort ( $ array , $ callback ) ; } } elseif ( is_string ( $ params ) ) { if ( $ isNumeric ) { ( strtolower ( $ params ) === 'desc' ) ? rsort ( $ array ) : sort ( $ array ) ; } else { ( strtolower ( $ params ) === 'desc' ) ? arsort ( $ array ) : asort ( $ array ) ; } } return $ array ; } | Sort array by multiple fields |
22,404 | public function enabledFalse ( $ emailID , $ listID ) { $ this -> model -> where ( 'list_id' , $ listID ) -> where ( 'email_id' , $ emailID ) -> update ( [ 'enabled' => false ] ) ; } | UPDATE a list_email record so that enabled is false |
22,405 | public function getList_emailByEmailIdAndListId ( $ emailID , $ listID ) { return $ this -> model -> where ( 'email_id' , $ emailID ) -> where ( 'list_id' , $ listID ) -> first ( ) ; } | Does the email AND list already exist in the list_email db table? |
22,406 | public function createNewRecord ( $ data ) { $ list_email = new $ this -> model ; $ list_email -> title = $ data [ 'list_id' ] . " " . $ data [ 'email_id' ] ; $ list_email -> list_id = $ data [ 'list_id' ] ; $ list_email -> email_id = $ data [ 'email_id' ] ; $ list_email -> comments = $ data [ 'comments' ] ; $ list_email -> enabled = $ data [ 'enabled' ] ; $ list_email -> created_at = $ data [ 'created_at' ] ; $ list_email -> created_by = $ data [ 'created_by' ] ; $ list_email -> updated_at = $ data [ 'updated_at' ] ; $ list_email -> updated_by = $ data [ 'updated_by' ] ; $ list_email -> locked_at = null ; $ list_email -> locked_by = null ; if ( $ list_email -> save ( ) ) { return $ list_email -> id ; } return false ; } | INSERT INTO list_email |
22,407 | final public function process ( BuildInterface $ build ) { if ( ( $ status = $ this -> build ( $ build ) ) === true ) { $ build -> setStatus ( BuildInterface :: PASSED ) ; } elseif ( $ status == - 1 ) { $ build -> setStatus ( BuildInterface :: STOPPED ) ; } else { $ build -> setStatus ( BuildInterface :: FAILED ) ; } } | abstract process for a builder . |
22,408 | public static function generator ( $ length = 32 ) { $ out = Hash :: base64 ( Route :: HTTP_HOST ( ) . random_bytes ( $ length ) , 1 ) ; return $ out ; } | Random token generator . |
22,409 | protected function hasKeyLikeType ( Data $ data ) : bool { return $ data -> isScalar ( ) || $ data -> isConvertibleToString ( ) || $ data -> isHashable ( ) ; } | Indica si se debe usar el nombre de tipo como clave |
22,410 | public function register ( ) { $ this -> container -> bind ( 'config' , new Repository ( new FileLoader ( new Filesystem , $ this -> container -> appPath ( ) . '/config' ) , new Resolver , $ this -> container -> os ( ) ) ) ; } | Register the config loader into the container . |
22,411 | public function newAction ( ) { $ stocklevel = new StockLevel ( ) ; $ form = $ this -> createForm ( new StockLevelType ( ) , $ stocklevel ) ; return array ( 'stocklevel' => $ stocklevel , 'form' => $ form -> createView ( ) , ) ; } | Displays a form to create a new StockLevel entity . |
22,412 | public function createAction ( Request $ request ) { $ stocklevel = new StockLevel ( ) ; $ form = $ this -> createForm ( new StockLevelType ( ) , $ stocklevel ) ; if ( $ form -> handleRequest ( $ request ) -> isValid ( ) ) { $ em = $ this -> getDoctrine ( ) -> getManager ( ) ; $ em -> persist ( $ stocklevel ) ; $ em -> flush ( ) ; return $ this -> redirect ( $ this -> generateUrl ( 'stock_stocklevel_show' , array ( 'id' => $ stocklevel -> getId ( ) ) ) ) ; } return array ( 'stocklevel' => $ stocklevel , 'form' => $ form -> createView ( ) , ) ; } | Creates a new StockLevel entity . |
22,413 | public function editAction ( StockLevel $ stocklevel ) { $ editForm = $ this -> createForm ( new StockLevelType ( ) , $ stocklevel , array ( 'action' => $ this -> generateUrl ( 'stock_stocklevel_update' , array ( 'id' => $ stocklevel -> getid ( ) ) ) , 'method' => 'PUT' , ) ) ; $ deleteForm = $ this -> createDeleteForm ( $ stocklevel -> getId ( ) , 'stock_stocklevel_delete' ) ; return array ( 'stocklevel' => $ stocklevel , 'edit_form' => $ editForm -> createView ( ) , 'delete_form' => $ deleteForm -> createView ( ) , ) ; } | Displays a form to edit an existing StockLevel entity . |
22,414 | public function updateAction ( StockLevel $ stocklevel , Request $ request ) { $ editForm = $ this -> createForm ( new StockLevelType ( ) , $ stocklevel , array ( 'action' => $ this -> generateUrl ( 'stock_stocklevel_update' , array ( 'id' => $ stocklevel -> getid ( ) ) ) , 'method' => 'PUT' , ) ) ; if ( $ editForm -> handleRequest ( $ request ) -> isValid ( ) ) { $ this -> getDoctrine ( ) -> getManager ( ) -> flush ( ) ; return $ this -> redirect ( $ this -> generateUrl ( 'stock_stocklevel_show' , array ( 'id' => $ stocklevel -> getId ( ) ) ) ) ; } $ deleteForm = $ this -> createDeleteForm ( $ stocklevel -> getId ( ) , 'stock_stocklevel_delete' ) ; return array ( 'stocklevel' => $ stocklevel , 'edit_form' => $ editForm -> createView ( ) , 'delete_form' => $ deleteForm -> createView ( ) , ) ; } | Edits an existing StockLevel entity . |
22,415 | protected function CleanAndBuildConstantKeyValue ( $ rawValue , $ valueToTrim ) { $ valueCleaned = $ this -> RemoveExtensionFileName ( $ rawValue , $ valueToTrim ) ; return $ this -> BuildConstantKeyValue ( $ valueCleaned ) ; } | Cleans a file name from its extension and build the key string value to find its value in the array of constants . |
22,416 | public function WriteConstant ( $ value ) { $ constantName = strtoupper ( $ value ) ; $ lineOfCode = PhpCodeSnippets :: TAB2 . "const " . $ constantName . " = '" . $ value . "';" . PhpCodeSnippets :: LF ; return $ lineOfCode ; } | Builds a line of code that declare a constant . |
22,417 | public function listAction ( Request $ request ) { $ objects = $ this -> get ( 'doctrine.orm.default_entity_manager' ) -> getRepository ( $ request -> get ( 'class' ) ) -> findAll ( ) ; if ( $ this -> container -> has ( 'jms_serializer' ) ) { return new Response ( $ this -> get ( 'jms_serializer' ) -> serialize ( $ objects , 'json' , SerializationContext :: create ( ) -> setGroups ( array ( 'Default' ) ) ) ) ; } return new JsonResponse ( $ objects ) ; } | List objects for geolocation |
22,418 | private function checkUserInfo ( ) : void { foreach ( $ this -> user -> getAttributes ( ) as $ key => $ value ) { $ this -> { $ key } = $ value ; } } | Init user info . |
22,419 | public static function json ( $ src , $ encode = 0 ) { $ options = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT ; $ out = $ encode ? json_encode ( $ src , $ options ) : json_decode ( $ src , true ) ; return $ out ; } | Decode JSON data . |
22,420 | public function custom ( $ name ) { if ( $ this -> _exist ) { $ class = 'Controller\Request\Custom\\' . ucfirst ( $ name ) ; if ( class_exists ( $ class ) ) { array_push ( $ this -> _constraints , [ 'type' => self :: CUSTOM , 'value' => new $ class ( $ this -> _field , $ this -> _label , $ this -> _data [ $ this -> _field ] ) ] ) ; } else { throw new MissingClassException ( 'The custom validation class "' . $ class . '" was not found' ) ; } } return $ this ; } | custom filter made by the user |
22,421 | public static function generateFromEnvironment ( ) { global $ argc , $ argv ; $ stdin = defined ( 'STDIN' ) ? STDIN : fopen ( 'php://stdin' , 'r' ) ; $ data = stream_get_meta_data ( $ stdin ) ; $ input = null ; if ( empty ( $ data [ 'seekable' ] ) ) { $ input = trim ( stream_get_contents ( $ stdin ) ) ; } $ path = $ argv [ 1 ] ; $ parameters = array_slice ( $ argv , 2 ) ; $ request = new static ( $ path , $ parameters , $ input ) ; return $ request ; } | Generate CLIRequest from environment |
22,422 | public static function handleCurrentRequest ( ) { try { CLIRoute :: initialize ( ) ; static :: $ mainRequest = static :: generateFromEnvironment ( ) ; $ response = static :: $ mainRequest -> process ( ) ; } catch ( \ Exception $ e ) { $ response = CLIResponse :: generateFromException ( $ e ) ; } $ response -> process ( ) ; exit ( $ response -> getCode ( ) ) ; } | Handle the current request as a CLIRequest one This method ends the script |
22,423 | public function execute ( Framework $ framework , WebRequest $ request , Response $ response ) { if ( ! $ request -> hasSession ( ) || $ request -> getRouteParam ( 'token' ) == '' ) { $ response -> redirectTo ( '/' ) ; return ; } $ token = $ request -> getRouteParam ( 'token' ) ; if ( ! $ this -> hasValidSessionData ( $ request , $ token ) ) { $ response -> redirectTo ( '/' ) ; return ; } $ class = $ request -> getSessionData ( 'dt-class-' . $ token ) ; $ time = $ request -> getSessionData ( 'dt-time-' . $ token ) ; $ options = json_decode ( $ request -> getSessionData ( 'dt-options-' . $ token ) , true ) ; if ( ! is_array ( $ options ) ) { $ options = array ( ) ; } if ( $ time > time ( ) + 600 ) { $ response -> redirectTo ( '/' ) ; return ; } $ table = new $ class ( $ framework , false ) ; $ table -> setOptions ( $ options ) ; $ generator = $ this -> getTableRenderer ( ) ; $ preparedTable = $ generator -> prepareTable ( $ request , $ table , '' ) ; $ data = array ( 'data' => array ( ) ) ; foreach ( $ preparedTable -> getBody ( ) -> getRows ( ) as $ row ) { $ data [ 'data' ] [ ] = $ row -> toArray ( ) ; } $ response -> setOutput ( json_encode ( $ data ) ) ; } | Loads the data from the server |
22,424 | protected function hasValidSessionData ( WebRequest $ request , $ token ) { return ( $ request -> getSessionData ( 'dt-class-' . $ token ) !== false && $ request -> getSessionData ( 'dt-time-' . $ token ) !== false ) ; } | Returns true if the session data has the needed token data |
22,425 | public function all ( ) { $ data = $ this -> attributes -> all ( ) ; $ data = $ data + $ this -> query -> all ( ) ; $ data = $ data + $ this -> request -> all ( ) ; return $ data ; } | Returns all parameters from request query or post |
22,426 | public function param ( $ key = NULL , $ default = NULL ) { if ( ! $ key ) { return $ this -> attributes -> all ( ) ; } $ path = '' ; $ key = explode ( '.' , $ key ) ; foreach ( $ key as $ item ) { if ( ! $ path ) { $ path .= $ item ; continue ; } $ path .= '[' . $ item . ']' ; } return $ this -> attributes -> get ( $ path , $ default , TRUE ) ; } | Returns a certain parameter from Route Params If key is NULL returns all the data in the Route Params |
22,427 | public function any ( $ key , $ default = NULL ) { $ item = $ this -> param ( $ key , NULL ) ; if ( $ item ) { return $ item ; } $ item = $ this -> post ( $ key , NULL ) ; if ( $ item ) { return $ item ; } $ item = $ this -> query ( $ key , NULL ) ; if ( $ item ) { return $ item ; } return $ default ; } | Returns any parameter from request query or post |
22,428 | public function setList ( $ list = [ ] ) { if ( ! is_array ( $ list ) ) { $ list = ArrayUtils :: iteratorToArray ( $ list ) ; } $ this -> list = $ list ; } | Set the list of items to white - list . |
22,429 | public function getQueryParam ( string $ key , $ default = null ) { $ getParams = $ this -> getQueryParams ( ) ; $ result = $ default ; if ( isset ( $ getParams [ $ key ] ) ) { $ result = $ getParams [ $ key ] ; } return $ result ; } | Fetch parameter value from query string . |
22,430 | public function addGroup ( $ user_id , $ group_id ) { try { $ group = Group :: findOrFail ( $ group_id ) ; $ user = User :: findOrFail ( $ user_id ) ; $ user -> addGroup ( $ group ) ; } catch ( ModelNotFoundException $ e ) { throw new NotFoundException ; } } | Add a group to the user |
22,431 | public function findFromGroupName ( $ group_name ) { $ group = $ this -> sentry -> findGroupByName ( $ group_name ) ; if ( ! $ group ) { throw new UserNotFoundException ; } return $ group -> users ; } | Obtain a list of user from a given group |
22,432 | public function getOptions ( ) { if ( $ this -> options ) { return $ this -> options ; } return $ this -> options = ( new \ FloatingPoint \ Stylist \ Theme \ Json ( $ this -> theme -> getPath ( ) ) ) -> getJsonAttribute ( 'options' ) ; } | Get the options defined in the themes json file . |
22,433 | public function newWpDb ( $ dbuser , $ dbpassword , $ dbname , $ dbhost ) { $ wpDbClass = '\wpdb' ; return new $ wpDbClass ( $ dbuser , $ dbpassword , $ dbname , $ dbhost ) ; } | Return new wpdb instance |
22,434 | public function addAction ( string $ tag , callable $ callback , ? int $ priority = null ) { $ args = [ $ tag , $ callback ] ; if ( ! is_null ( $ priority ) ) $ args [ ] = $ priority ; return $ this -> callGlobalFunction ( 'add_action' , $ args ) ; } | Add action hook |
22,435 | public function doAction ( string $ tag , ... $ params ) { $ args = [ $ tag ] ; if ( ! empty ( $ params ) ) $ args [ ] = $ params ; return $ this -> callGlobalFunction ( 'do_action' , $ args ) ; } | Call the hook |
22,436 | public function wpRegisterStyle ( $ handle , $ src , $ deps = [ ] , $ ver = false , $ media = 'all' ) { return $ this -> callGlobalFunction ( 'wp_register_style' , [ $ handle , $ src , $ deps , $ ver , $ media ] ) ; } | Register a CSS stylesheet |
22,437 | public function wpEnqueueScript ( $ handle , $ src = '' , $ deps = [ ] , $ ver = false , $ inFooter = false ) { return $ this -> callGlobalFunction ( 'wp_enqueue_script' , [ $ handle , $ src , $ deps , $ ver , $ inFooter ] ) ; } | Enqueue a script |
22,438 | public function registerRestRoute ( $ namespace , $ route , $ args = [ ] , $ override = false ) { return $ this -> callGlobalFunction ( 'register_rest_route' , [ $ namespace , $ route , $ args , $ override ] ) ; } | Registers a REST API route |
22,439 | protected function getFromGlobal ( string $ name ) { if ( isset ( $ GLOBALS [ $ name ] ) ) { return $ GLOBALS [ $ name ] ; } throw new \ ErrorException ( sprintf ( "Undefined global variable (%s) called!" , $ name ) ) ; } | Get global namespace variable |
22,440 | protected function callGlobalFunction ( string $ name , ? array $ arguments = null ) { if ( function_exists ( $ name ) ) { return call_user_func_array ( $ name , $ arguments ?? [ ] ) ; } throw new \ ErrorException ( sprintf ( "Undefined global function (%s) called!" , $ name ) ) ; } | Call global namespace function |
22,441 | public final function decode ( ehough_shortstop_api_HttpResponse $ response ) { $ context = new ehough_chaingang_impl_StandardContext ( ) ; $ context -> put ( 'response' , $ response ) ; $ status = $ this -> _chain -> execute ( $ context ) ; if ( $ status === false ) { return ; } $ entity = $ response -> getEntity ( ) ; $ decoded = $ context -> get ( 'response' ) ; $ entity -> setContent ( $ decoded ) ; $ entity -> setContentLength ( strlen ( $ decoded ) ) ; $ contentType = $ response -> getHeaderValue ( ehough_shortstop_api_HttpMessage :: HTTP_HEADER_CONTENT_TYPE ) ; if ( $ contentType !== null ) { $ entity -> setContentType ( $ contentType ) ; } $ response -> setEntity ( $ entity ) ; } | Decodes an HTTP response . |
22,442 | public final function needsToBeDecoded ( ehough_shortstop_api_HttpResponse $ response ) { $ entity = $ response -> getEntity ( ) ; $ isDebugEnabled = $ this -> _logger -> isHandling ( ehough_epilog_Logger :: DEBUG ) ; if ( $ entity === null ) { if ( $ isDebugEnabled ) { $ this -> _logger -> debug ( 'Response contains no entity' ) ; } return false ; } $ content = $ entity -> getContent ( ) ; if ( $ content == '' || $ content == null ) { if ( $ isDebugEnabled ) { $ this -> _logger -> debug ( 'Response entity contains no content' ) ; } return false ; } $ expectedHeaderName = $ this -> getHeaderName ( ) ; $ actualHeaderValue = $ response -> getHeaderValue ( $ expectedHeaderName ) ; if ( $ actualHeaderValue === null ) { if ( $ isDebugEnabled ) { $ this -> _logger -> debug ( sprintf ( 'Response does not contain %s header. No need to decode.' , $ expectedHeaderName ) ) ; } return false ; } if ( $ isDebugEnabled ) { $ this -> _logger -> debug ( sprintf ( 'Response contains %s header. Will attempt decode.' , $ expectedHeaderName ) ) ; } return true ; } | Determines if this response needs to be decoded . |
22,443 | protected static function mergeRoutes ( & $ routes , $ added ) { foreach ( $ added as $ type => $ typeRoutes ) { if ( isset ( $ routes [ $ type ] ) ) { $ routes [ $ type ] = array_merge ( $ typeRoutes , $ routes [ $ type ] ) ; } else { $ routes [ $ type ] = $ typeRoutes ; } } } | Merge routes array with routes logic |
22,444 | public function instanciateController ( ) { $ class = $ this -> controllerClass ; $ controller = new $ class ( ) ; if ( ! ( $ controller instanceof Controller ) ) { throw new NotFoundException ( 'The controller "' . $ this -> controllerClass . '" is not a valid controller, the class must inherit from "' . get_class ( ) . '"' ) ; } $ controller -> setRoute ( $ this ) ; return $ controller ; } | Instanciate the controller and return it |
22,445 | private function useAssoc ( $ params ) { $ assoc = true ; if ( isset ( $ params [ 'assoc' ] ) && is_bool ( $ params [ 'assoc' ] ) ) { $ assoc = $ params [ 'assoc' ] ; } return $ assoc ; } | Decides whether to use assoc or stdClass . |
22,446 | private function forceObject ( $ params ) { $ forceObject = false ; if ( isset ( $ params [ 'force_object' ] ) && is_bool ( $ params [ 'force_object' ] ) && true === $ params [ 'force_object' ] ) { $ forceObject = JSON_FORCE_OBJECT ; } return $ forceObject ; } | Decides whether to force objects . |
22,447 | private function createGateway ( $ assoc , $ decodedJson ) { if ( $ assoc === true ) { $ instance = new NativeArrayGateway ( $ decodedJson ) ; } else { $ instance = new NativeObjectGateway ( $ decodedJson ) ; } return $ instance ; } | Creates the correct gateway based on assoc being true or false . |
22,448 | public function getSQLAdapter ( ) { return $ this -> sqlAdapter ? $ this -> sqlAdapter : ( $ this -> transactionOperationSet ? $ this -> transactionOperationSet -> getSQLAdapter ( ) : null ) ; } | Get the SQL Adapter |
22,449 | public function getTasksAction ( ) { $ tasks = [ ] ; $ list = $ this -> getTensideTasks ( ) ; foreach ( $ list -> getIds ( ) as $ taskId ) { $ tasks [ $ taskId ] = $ this -> convertTaskToArray ( $ list -> getTask ( $ taskId ) ) ; } return $ this -> createJsonResponse ( $ tasks , true ) ; } | Retrieve the task list . |
22,450 | public function getTaskAction ( $ taskId , Request $ request ) { $ task = $ this -> getTensideTasks ( ) -> getTask ( $ taskId ) ; $ offset = null ; if ( ! $ task ) { throw new NotFoundHttpException ( 'No such task.' ) ; } if ( $ request -> query -> has ( 'offset' ) ) { $ offset = ( int ) $ request -> query -> get ( 'offset' ) ; } return $ this -> createJsonResponse ( [ $ this -> convertTaskToArray ( $ task , true , $ offset ) ] ) ; } | Retrieve the given task task . |
22,451 | public function addTaskAction ( Request $ request ) { $ metaData = null ; $ content = $ request -> getContent ( ) ; if ( empty ( $ content ) ) { throw new NotAcceptableHttpException ( 'Invalid payload' ) ; } $ metaData = new JsonArray ( $ content ) ; if ( ! $ metaData -> has ( 'type' ) ) { throw new NotAcceptableHttpException ( 'Invalid payload' ) ; } try { $ taskId = $ this -> getTensideTasks ( ) -> queue ( $ metaData -> get ( 'type' ) , $ metaData ) ; } catch ( \ InvalidArgumentException $ exception ) { throw new NotAcceptableHttpException ( $ exception -> getMessage ( ) ) ; } return $ this -> createJsonResponse ( [ $ this -> convertTaskToArray ( $ this -> getTensideTasks ( ) -> getTask ( $ taskId ) ) ] , false , 'OK' , JsonResponse :: HTTP_CREATED ) ; } | Queue a task in the list . |
22,452 | public function deleteTaskAction ( $ taskId ) { $ list = $ this -> getTensideTasks ( ) ; $ task = $ list -> getTask ( $ taskId ) ; if ( ! $ task ) { throw new NotFoundHttpException ( 'Task id ' . $ taskId . ' not found' ) ; } if ( $ task -> getStatus ( ) === Task :: STATE_RUNNING ) { throw new NotAcceptableHttpException ( 'Task id ' . $ taskId . ' is running and can not be deleted' ) ; } $ task -> removeAssets ( ) ; $ list -> remove ( $ task -> getId ( ) ) ; return JsonResponse :: create ( [ 'status' => 'OK' ] ) ; } | Remove a task from the list . |
22,453 | public function runAction ( ) { $ lock = $ this -> container -> get ( 'tenside.taskrun_lock' ) ; if ( $ this -> getTensideConfig ( ) -> isForkingAvailable ( ) && ! $ lock -> lock ( ) ) { throw new NotAcceptableHttpException ( 'Task already running' ) ; } $ task = $ this -> getTensideTasks ( ) -> getNext ( ) ; if ( ! $ task ) { throw new NotFoundHttpException ( 'Task not found' ) ; } if ( $ task :: STATE_PENDING !== $ task -> getStatus ( ) ) { return $ this -> createJsonResponse ( [ $ this -> convertTaskToArray ( $ task ) ] ) ; } try { $ this -> spawn ( $ task ) ; } finally { if ( $ this -> getTensideConfig ( ) -> isForkingAvailable ( ) ) { $ lock -> release ( ) ; } } return $ this -> createJsonResponse ( [ $ this -> convertTaskToArray ( $ task ) ] ) ; } | Starts the next pending task if any . |
22,454 | private function spawn ( Task $ task ) { $ config = $ this -> getTensideConfig ( ) ; $ home = $ this -> getTensideHome ( ) ; $ commandline = PhpProcessSpawner :: create ( $ config , $ home ) -> spawn ( [ $ this -> get ( 'tenside.cli_script' ) -> cliExecutable ( ) , 'tenside:runtask' , $ task -> getId ( ) , '-v' , '--no-interaction' ] ) ; $ this -> get ( 'logger' ) -> debug ( 'SPAWN CLI: ' . $ commandline -> getCommandLine ( ) ) ; $ commandline -> setTimeout ( 0 ) ; $ commandline -> start ( ) ; if ( ! $ commandline -> isRunning ( ) ) { if ( $ exitCode = $ commandline -> getExitCode ( ) ) { $ logger = $ this -> get ( 'logger' ) ; $ logger -> error ( 'Failed to execute "' . $ commandline -> getCommandLine ( ) . '"' ) ; $ logger -> error ( 'Exit code: ' . $ commandline -> getExitCode ( ) ) ; $ logger -> error ( 'Output: ' . $ commandline -> getOutput ( ) ) ; $ logger -> error ( 'Error output: ' . $ commandline -> getErrorOutput ( ) ) ; throw new \ RuntimeException ( sprintf ( 'Spawning process task %s resulted in exit code %s' , $ task -> getId ( ) , $ exitCode ) ) ; } } $ commandline -> wait ( ) ; } | Spawn a detached process for a task . |
22,455 | private function convertTaskToArray ( Task $ task , $ addOutput = false , $ outputOffset = null ) { $ data = [ 'id' => $ task -> getId ( ) , 'status' => $ task -> getStatus ( ) , 'type' => $ task -> getType ( ) , 'created_at' => $ task -> getCreatedAt ( ) -> format ( \ DateTime :: ISO8601 ) , 'user_data' => $ task -> getUserData ( ) ] ; if ( true === $ addOutput ) { $ data [ 'output' ] = $ task -> getOutput ( $ outputOffset ) ; } return $ data ; } | Convert a task to an array . |
22,456 | private function createJsonResponse ( array $ tasks , $ isCollection = false , $ status = 'OK' , $ httpStatus = JsonResponse :: HTTP_OK ) { $ data = [ 'status' => $ status ] ; $ key = $ isCollection ? 'tasks' : 'task' ; $ data [ $ key ] = $ isCollection ? $ tasks : $ tasks [ 0 ] ; return JsonResponse :: create ( $ data , $ httpStatus ) -> setEncodingOptions ( ( JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_FORCE_OBJECT ) ) ; } | Create a JsonResponse based on an array of tasks . |
22,457 | public function listAction ( ) { $ siterootManager = $ this -> get ( 'phlexible_siteroot.siteroot_manager' ) ; $ siteroots = [ ] ; foreach ( $ siterootManager -> findAll ( ) as $ siteroot ) { $ siteroots [ ] = [ 'id' => $ siteroot -> getId ( ) , 'title' => $ siteroot -> getTitle ( ) , ] ; } return new JsonResponse ( [ 'siteroots' => $ siteroots , 'count' => count ( $ siteroots ) , ] ) ; } | List siteroots . |
22,458 | public function createAction ( Request $ request ) { $ title = $ request -> get ( 'title' , null ) ; $ siterootManager = $ this -> get ( 'phlexible_siteroot.siteroot_manager' ) ; $ siteroot = new Siteroot ( ) ; foreach ( explode ( ',' , $ this -> container -> getParameter ( 'phlexible_gui.languages.available' ) ) as $ language ) { $ siteroot -> setTitle ( $ language , $ title ) ; } $ siteroot -> setCreateUserId ( $ this -> getUser ( ) -> getId ( ) ) -> setCreatedAt ( new \ DateTime ( ) ) -> setModifyUserId ( $ siteroot -> getCreateUserId ( ) ) -> setModifiedAt ( $ siteroot -> getCreatedAt ( ) ) ; $ siterootManager -> updateSiteroot ( $ siteroot ) ; return new ResultResponse ( true , 'New Siteroot created.' ) ; } | Create siteroot . |
22,459 | public function deleteAction ( Request $ request ) { $ siterootId = $ request -> get ( 'id' ) ; $ siterootManager = $ this -> get ( 'phlexible_siteroot.siteroot_manager' ) ; $ siteroot = $ siterootManager -> find ( $ siterootId ) ; $ siterootManager -> deleteSiteroot ( $ siteroot ) ; return new ResultResponse ( true , 'Siteroot deleted.' ) ; } | Delete siteroot . |
22,460 | public function onKernelException ( GetResponseForExceptionEvent $ event ) : void { $ this -> originListener -> onKernelException ( $ event ) ; if ( ! $ event -> hasResponse ( ) ) { return ; } $ this -> logException ( $ event -> getException ( ) ) ; } | Handle the exception and log message . |
22,461 | public function moduleLoad ( $ author , $ name , $ locale ) { if ( $ this -> isModuleLoaded ( $ author , $ name , $ locale ) ) { return ; } $ lines = $ this -> loader -> loadModule ( $ locale , $ name , $ author ) ; $ this -> loaded [ 'Modules' ] [ $ author ] [ $ name ] [ $ locale ] = $ lines ; } | Load the specified language group for modules . |
22,462 | protected function isModuleLoaded ( $ author , $ name , $ locale ) { return isset ( $ this -> loaded [ 'Modules' ] [ $ author ] [ $ name ] [ $ locale ] ) ; } | Determine if the given module has been loaded . |
22,463 | public function validateAttribute ( $ model , $ attribute ) { $ value = $ model -> $ attribute ; $ captcha = $ this -> createCaptchaAction ( $ model ) ; $ valid = ! is_array ( $ value ) && $ captcha -> validate ( $ value ) ; $ isExpired = $ captcha -> isExpired ( ) ; $ result = $ isExpired ? [ $ this -> getMessageForExpiredCaptcha ( ) , [ ] ] : ( $ valid ? null : [ $ this -> message , [ ] ] ) ; if ( ! empty ( $ result ) ) { $ this -> addError ( $ model , $ attribute , $ result [ 0 ] , $ result [ 1 ] ) ; } } | Validates a single attribute . Child classes must implement this method to provide the actual validation logic . |
22,464 | private function getCountriesCountFromSessions ( Carbon $ start , Carbon $ end ) { return $ this -> getVisitorsFilteredByDateRange ( $ start , $ end ) -> transform ( function ( Visitor $ visitor ) { return $ visitor -> hasGeoip ( ) ? [ 'code' => $ visitor -> geoip -> iso_code , 'geoip' => $ visitor -> geoip , ] : [ 'code' => 'undefined' , 'geoip' => null , ] ; } ) -> groupBy ( 'code' ) -> transform ( function ( Collection $ items , $ key ) { return ( $ key === 'undefined' ) ? [ 'code' => null , 'name' => trans ( 'tracker::generals.undefined' ) , 'count' => $ items -> count ( ) , ] : [ 'code' => $ key , 'name' => $ items -> first ( ) [ 'geoip' ] -> country , 'count' => $ items -> count ( ) , ] ; } ) ; } | Get the countries count from sessions . |
22,465 | private function calculateCountriesPercentage ( Collection $ countries ) { $ total = $ countries -> sum ( 'count' ) ; return $ countries -> transform ( function ( $ item ) use ( $ total ) { return $ item + [ 'percentage' => round ( ( $ item [ 'count' ] / $ total ) * 100 , 2 ) ] ; } ) ; } | Calculate countries percentage . |
22,466 | public function request ( $ serviceName , $ payload = [ ] , $ method = 'GET' ) { $ this -> setup ( ) ; $ path = $ this -> settings -> getPath ( $ serviceName ) ; switch ( $ method ) { case 'GET' : $ response = $ this -> client -> get ( $ path , [ 'headers' => [ 'Authentication' => $ this -> accessToken -> getToken ( ) ] , 'query' => $ payload , ] ) ; break ; case 'POST' : $ response = $ this -> client -> post ( $ path , [ 'headers' => [ 'Authentication' => $ this -> accessToken -> getToken ( ) ] , 'json' => $ payload , ] ) ; break ; } $ json = json_decode ( $ response -> getBody ( ) ) ; $ body = $ json -> { 'nl.divide.iq' } ; if ( $ this -> settings -> isOutdated ( $ body -> settings_updated ) ) { unset ( $ this -> settings ) ; } if ( ! isset ( $ body -> response -> content ) ) { $ message = $ body -> response -> answer ; $ message .= isset ( $ body -> response -> message ) ? ": {$body->response->message}" : '' ; throw new \ Exception ( $ message ) ; } return $ body -> response -> content ; } | Accesses a service provided by Divide . IQ using the stored access token . |
22,467 | public function download ( $ uri , $ destination ) { $ this -> setup ( ) ; $ this -> client -> get ( $ uri , [ 'headers' => [ 'Content-Type' => null , 'Authentication' => $ this -> accessToken -> getToken ( ) , ] , 'sink' => $ destination , ] ) ; } | Downloads a file using current client configuration and saves it at the specified destination . |
22,468 | public static function fromFile ( \ SplFileObject $ file ) { $ file -> rewind ( ) ; $ object = static :: fromJson ( $ file -> fread ( $ file -> getSize ( ) ) ) ; $ object -> file = $ file ; return $ object ; } | Unserializes the object from JSON contained in the given file . |
22,469 | protected function setup ( ) { if ( ! $ this -> accessToken || $ this -> accessToken -> expired ( ) ) { $ refreshSuccess = true ; if ( $ this -> refreshToken && $ this -> refreshToken -> getToken ( ) ) { try { $ this -> refresh ( ) ; } catch ( RequestException $ e ) { if ( $ e -> getCode ( ) == 403 ) { $ response = $ e -> getResponse ( ) ; $ json = json_decode ( $ response -> getBody ( ) ) ; $ body = $ json -> { 'nl.divide.iq' } ; if ( $ body -> answer == 'TokenExpired' ) { $ refreshSuccess = false ; } else { throw $ e ; } } else { throw $ e ; } } } else { $ refreshSuccess = false ; } if ( ! $ refreshSuccess ) { $ this -> login ( ) -> authenticate ( ) ; } } if ( ! $ this -> settings ) { $ response = $ this -> client -> get ( 'settings' , [ 'headers' => [ 'Authentication' => $ this -> accessToken -> getToken ( ) ] , ] ) ; $ json = json_decode ( $ response -> getBody ( ) ) ; $ body = $ json -> { 'nl.divide.iq' } ; $ services = [ ] ; foreach ( $ body -> services as $ service ) { $ services [ ] = $ service -> code ; } $ this -> settings = new Settings ( $ services , $ body -> settings_updated ) ; } } | Sets up a connection with the Divide . IQ server . |
22,470 | protected function login ( ) { $ response = $ this -> client -> get ( 'services/login' , [ 'headers' => [ 'username' => $ this -> username , 'password' => $ this -> password ] , ] ) ; $ json = json_decode ( $ response -> getBody ( ) ) ; $ body = $ json -> { 'nl.divide.iq' } ; $ expire = new \ DateTime ( $ body -> expiration_date , new \ DateTimezone ( 'UTC' ) ) ; $ this -> authToken = new Token ( $ body -> authentication_token , $ expire ) ; return $ this ; } | Logs in using the provided credentials . |
22,471 | protected function authenticate ( $ refresh = false ) { $ token = $ refresh ? $ this -> refreshToken : $ this -> authToken ; $ response = $ this -> client -> get ( 'authenticate' , [ 'headers' => [ 'Authentication' => $ token -> getToken ( ) ] , ] ) ; $ json = json_decode ( $ response -> getBody ( ) ) ; $ body = $ json -> { 'nl.divide.iq' } ; $ expire = new \ DateTime ( $ body -> expiration_date , new \ DateTimezone ( 'UTC' ) ) ; $ this -> accessToken = new Token ( $ body -> access_token , $ expire ) ; if ( isset ( $ body -> refresh_token ) ) { $ this -> refreshToken = new Token ( $ body -> refresh_token ) ; } return $ this ; } | Authenticates using the stored authentication token . |
22,472 | public function actionAddlocation ( $ module = NULL , $ id = NULL ) { $ model = new WidgetConfig ; if ( $ model -> load ( Yii :: $ app -> request -> post ( ) ) && $ model -> save ( ) ) { $ query = WidgetConfig :: findRelatedRecords ( 'MAPWIDGET' , $ model -> wgt_table , $ model -> wgt_id ) ; $ dpLocations = new ActiveDataProvider ( array ( 'query' => $ query , ) ) ; return $ this -> renderAjax ( '@frenzelgmbh/sblog/widgets/views/_mapwidget' , [ 'dpLocations' => $ dpLocations , 'module' => $ model -> wgt_table , 'id' => $ model -> wgt_id ] ) ; } else { $ model -> wgt_id = $ id ; $ model -> wgt_table = $ module ; $ model -> name = 'MAPWIDGET' ; return $ this -> renderAjax ( '_form_addlocation' , array ( 'model' => $ model , ) ) ; } } | will create a new commment |
22,473 | public static function getSetting ( $ key , $ value = null ) { $ data = ini_get ( $ key ) ; if ( $ data === false ) { throw new \ InvalidArgumentException ( sprintf ( "Invalid PHP setting '%s'" , $ key ) ) ; } if ( $ value === null ) { return $ data ; } else { ini_set ( $ key , $ value ) ; } } | Get PHP setting runtime value with parameter name check |
22,474 | public static function decode ( $ value ) { if ( empty ( $ value ) ) { return null ; } if ( ! is_string ( $ value ) ) { throw new \ InvalidArgumentException ( sprintf ( "Value type '%s' is not a PHP string so it cannot be unserialized." , gettype ( $ value ) ) ) ; } $ data = unserialize ( $ value ) ; return $ data ; } | Unserialize mixed type data |
22,475 | public static function isEncoded ( $ data ) { if ( ! is_string ( $ data ) ) { return false ; } $ data = trim ( $ data ) ; if ( 'N;' == $ data ) { return true ; } $ match = array ( ) ; if ( ! preg_match ( '/^([adObis]):/' , $ data , $ match ) ) { return false ; } switch ( $ match [ 1 ] ) { case 'a' : case 'O' : case 's' : if ( preg_match ( "/^{$match[1]}:[0-9]+:.*[;}]\$/s" , $ data ) ) { return true ; } break ; case 'b' : case 'i' : case 'd' : if ( preg_match ( "/^{$match[1]}:[0-9.E-]+;\$/" , $ data ) ) { return true ; } break ; } return false ; } | Check whether specified string is serialized in PHP format |
22,476 | public function getFromRequest ( $ route = null ) { $ resolvers = [ ] ; foreach ( $ this -> segmentsResolvers as $ key => $ resolverClass ) { if ( $ bindedClass = request ( ) -> route ( $ key ) ) { $ resolvers [ $ key ] = new $ resolverClass ( $ bindedClass ) ; } } if ( ! empty ( $ resolvers ) ) { if ( empty ( $ route ) ) { $ route = \ Route :: getCurrentRoute ( ) -> uri ( ) ; } $ segments = explode ( '/' , $ route ) ; $ sortedResolvers = [ ] ; foreach ( $ segments as $ segment ) { $ segment = trim ( $ segment , "{}" ) ; if ( isset ( $ resolvers [ $ segment ] ) ) { $ sortedResolvers [ $ segment ] = $ resolvers [ $ segment ] ; } } $ resolvers = $ sortedResolvers ; } return empty ( $ resolvers ) ? false : $ resolvers ; } | Test request and dynamically creates classes to resolve properties of binded class |
22,477 | public function resolveRouteItem ( $ uriWithParam = null , $ resolvers = null , $ trailingSlash = false ) { if ( empty ( $ uriWithParam ) ) { $ uriWithParam = \ Route :: getCurrentRoute ( ) -> uri ( ) ; } if ( empty ( $ resolvers ) ) { $ resolvers = \ RouteResolver :: getFromRequest ( $ uriWithParam ) ; } $ resolvedRoute = [ ] ; if ( ! empty ( $ resolvers ) ) { foreach ( $ resolvers as $ parameter => $ resolver ) { if ( $ resolver instanceof ParamResolver ) { if ( $ item = $ resolver -> item ( ) ) { $ urlCurrent = $ uriWithParam ; if ( isset ( $ resolvedRoute [ 'url' ] ) ) { $ urlCurrent = $ resolvedRoute [ 'url' ] ; } $ resolvedRoute = [ 'locale' => $ resolver -> locale ( $ item ) , 'label' => $ resolver -> label ( $ item ) , 'url' => str_replace ( '{' . $ parameter . '}' , $ resolver -> segment ( $ item ) , $ urlCurrent ) ] ; } } else { throw new \ Exception ( "Resolver has to implement of 'Crumby\RouteResolver\Contracts\ParamResolver', " . get_class ( $ resolver ) . " given." ) ; } } } if ( $ trailingSlash && isset ( $ resolvedRoute [ 'url' ] ) ) { $ resolvedRoute [ 'url' ] = '/' . ltrim ( $ resolvedRoute [ 'url' ] , '/' ) ; } return empty ( $ resolvedRoute ) ? false : $ resolvedRoute ; } | Resolves route Locale Label Url |
22,478 | public static function register ( $ id , $ options ) { $ id = ( string ) $ id ; if ( self :: exists ( $ id ) ) { user_error ( Text :: insert ( 'A collection with id ":id" is already registered.' , [ 'id' => $ id ] ) ) ; return ; } $ defaults = [ 'model' => 'Plugin.Model' , 'displayName' => 'Translated Name' ] ; $ options = array_merge ( $ defaults , $ options ) ; self :: _instance ( ) -> _items [ $ id ] = $ options ; } | Register a new collection . |
22,479 | public static function getForSelect ( ) { $ instance = self :: _instance ( ) ; return array_combine ( array_keys ( $ instance -> _items ) , Hash :: extract ( $ instance -> _items , '{s}.displayName' ) ) ; } | Get all collections for a select . |
22,480 | public static function getDisplayName ( $ id ) { $ instance = self :: _instance ( ) ; if ( ! isset ( $ instance -> _items [ $ id ] ) ) { return false ; } return $ instance -> _items [ $ id ] [ 'displayName' ] ; } | Get the display name for a specific item . |
22,481 | public function serialize ( $ data , array $ params = array ( ) ) { return $ this -> jms -> serialize ( $ data , self :: SERIALIZER_FORMAT , $ this -> determineContext ( $ this -> jmsSerializeContext , $ params ) ) ; } | Serializes given data to string |
22,482 | public function deserialize ( $ data , array $ params = array ( ) ) { $ sourceClass = $ this -> getSourceClassFromMapping ( $ params ) ; $ this -> handler -> setSourceDeSerClass ( $ sourceClass ) ; return new NativeObjectGateway ( $ this -> jms -> deserialize ( $ data , $ this -> deserializerClass , self :: SERIALIZER_FORMAT , $ this -> determineContext ( $ this -> jmsDeserializeContext , $ params ) ) ) ; } | Deserializes given data to array or object |
22,483 | private function getSourceClassFromMapping ( array $ params ) { $ index = $ params [ 'index' ] ; $ type = $ params [ 'type' ] ; if ( ! isset ( $ this -> indexTypeClassMap [ $ index ] ) ) { throw new DeserializationFailureException ( 'Cannot find index in source class map: ' . $ index ) ; } if ( ! isset ( $ this -> indexTypeClassMap [ $ index ] [ $ type ] ) ) { throw new DeserializationFailureException ( 'Cannot find type in source class map: ' . $ type . ' in index ' . $ index ) ; } return $ this -> indexTypeClassMap [ $ index ] [ $ type ] ; } | gets the source class . |
22,484 | public function decode ( $ data ) { try { return Yaml :: parse ( $ data ) ; } catch ( ParseException $ e ) { printf ( "Unable to parse the YAML string: %s" , $ e -> getMessage ( ) ) ; return [ ] ; } } | Decodes the data that was loaded with read |
22,485 | protected function runProcess ( Process $ process ) { $ ioHandler = $ this -> getIO ( ) ; $ process -> run ( function ( $ pipe , $ content ) use ( $ ioHandler ) { if ( Process :: ERR === $ pipe ) { $ ioHandler -> writeError ( $ content , false ) ; return ; } $ ioHandler -> write ( $ content , false ) ; } ) ; if ( 0 !== $ process -> getExitCode ( ) ) { throw new ProcessFailedException ( $ process ) ; } } | Run a process and throw exception if it failed . |
22,486 | public function isValid ( ) { $ valid = $ this -> prefix != '' ; $ valid = $ valid && $ this -> startMultiLine != '' ; $ valid = $ valid && $ this -> endMultiLine != '' ; $ valid = $ valid && $ this -> simpleDirective != '' ; return $ valid ; } | Confirms if the server instance has valid parameters . |
22,487 | public function setPrefix ( $ prefix ) { if ( ! $ this -> checker -> setString ( $ prefix ) -> getString ( ) ) { throw ServerException :: forInvalidPrefix ( $ prefix , 'The path is expected to be a string. Got: %s' ) ; } if ( ! $ this -> checker -> isValidAbsolutePath ( ) ) { throw ServerException :: forInvalidPrefix ( $ prefix , 'The path is expected to be absolute and an existing directory. Got: %s' ) ; } $ this -> prefix = $ prefix ; return $ this ; } | Sets the prefix of a server instance . |
22,488 | private function setRegexDirective ( $ directive , $ message1 , $ message2 ) { if ( ! $ this -> checker -> setString ( $ directive ) -> getString ( ) ) { throw ServerException :: forInvalidMatcher ( $ directive , $ message1 ) ; } if ( ! $ this -> checker -> isValidRegex ( ) ) { throw ServerException :: forInvalidMatcher ( $ directive , $ message2 ) ; } return $ directive ; } | Sets the regular expression directive . |
22,489 | private function isValidDirective ( $ directive , $ message1 , $ message2 ) { if ( ! $ this -> checker -> setString ( $ directive ) -> getString ( ) ) { throw ServerException :: forInvalidMatcher ( $ directive , $ message1 ) ; } if ( ! $ this -> checker -> hasKeyAndValueSubPattern ( ) ) { throw ServerException :: forInvalidMatcher ( $ directive , $ message2 ) ; } return true ; } | Confirms if a directive matcher is a valid regex . |
22,490 | protected function getFormatChoices ( $ context = 'prestacms' ) { $ formatChoices = array ( ) ; $ formats = $ this -> getMediaPool ( ) -> getFormatNamesByContext ( $ context ) ; foreach ( $ formats as $ code => $ format ) { $ formatChoices [ $ code ] = $ this -> trans ( 'media.format.' . $ code ) ; } return $ formatChoices ; } | Returns available formats |
22,491 | public function run ( ) { set_error_handler ( array ( '\Diarmuidie\ImageRack\Server' , 'handleErrors' ) ) ; set_exception_handler ( array ( $ this , 'error' ) ) ; if ( ! $ this -> validRequest ( ) ) { $ this -> notFound ( ) ; return $ this -> response ; } $ cachePath = $ this -> getCachePath ( ) ; if ( $ this -> serveFromCache ( $ cachePath ) ) { return $ this -> response ; } $ sourcePath = $ this -> getSourcePath ( ) ; if ( $ this -> serveFromSource ( $ sourcePath ) ) { return $ this -> response ; } $ this -> notFound ( ) ; return $ this -> response ; } | Run the image Server on the curent request . |
22,492 | private function serveFromCache ( $ path ) { if ( $ this -> cache -> has ( $ path ) ) { $ file = $ this -> cache -> get ( $ path ) ; $ lastModified = new \ DateTime ( ) ; $ lastModified -> setTimestamp ( $ file -> getTimestamp ( ) ) ; $ this -> setHttpCacheHeaders ( $ lastModified , md5 ( $ this -> getCachePath ( ) . $ lastModified -> getTimestamp ( ) ) , $ this -> maxAge ) ; if ( $ this -> response -> isNotModified ( $ this -> request ) ) { return true ; } $ this -> response = new StreamedResponse ( ) ; $ this -> response -> headers -> set ( 'Content-Type' , $ file -> getMimetype ( ) ) ; $ this -> response -> headers -> set ( 'Content-Length' , $ file -> getSize ( ) ) ; $ this -> setHttpCacheHeaders ( $ lastModified , md5 ( $ this -> getCachePath ( ) . $ lastModified -> getTimestamp ( ) ) , $ this -> maxAge ) ; $ this -> response -> setCallback ( function ( ) use ( $ file ) { fpassthru ( $ file -> readStream ( ) ) ; } ) ; return true ; } return false ; } | Generate a response object for a cached image . |
22,493 | private function serveFromSource ( $ path ) { if ( $ this -> source -> has ( $ path ) ) { $ file = $ this -> source -> get ( $ path ) ; $ template = $ this -> templates [ $ this -> template ] ( ) ; $ image = $ this -> processImage ( $ file , $ this -> imageManager , $ template ) ; $ this -> response -> headers -> set ( 'Content-Type' , $ image -> mime ) ; $ this -> response -> headers -> set ( 'Content-Length' , strlen ( $ image -> encoded ) ) ; $ lastModified = new \ DateTime ( ) ; $ this -> setHttpCacheHeaders ( $ lastModified , md5 ( $ this -> getCachePath ( ) . $ lastModified -> getTimestamp ( ) ) , $ this -> maxAge ) ; $ this -> response -> setContent ( $ image -> encoded ) ; $ this -> cacheWrite = function ( FilesystemInterface $ cache , $ path ) use ( $ image ) { $ cache -> put ( $ path , $ image -> encoded ) ; } ; return true ; } return false ; } | Process a source image and Generate a response object . |
22,494 | private function setHttpCacheHeaders ( \ DateTime $ lastModified , $ eTag , $ maxAge ) { $ this -> response -> setMaxAge ( $ maxAge ) ; $ this -> response -> setPublic ( ) ; if ( $ this -> maxAge === 0 ) { $ this -> response -> headers -> set ( 'Cache-Control' , 'no-cache' ) ; return ; } $ this -> response -> setLastModified ( $ lastModified ) ; $ this -> response -> setEtag ( $ eTag ) ; } | Set the appripriate HTTP cache headers . |
22,495 | protected function notFound ( ) { $ this -> response -> setContent ( 'File not found' ) ; $ this -> response -> headers -> set ( 'content-type' , 'text/html' ) ; $ this -> response -> setStatusCode ( Response :: HTTP_NOT_FOUND ) ; if ( is_callable ( $ this -> notFound ) ) { $ this -> response = call_user_func ( $ this -> notFound , $ this -> response ) ; } } | Set a not found response . |
22,496 | public function error ( $ exception ) { $ response = new Response ( ) ; $ response -> setContent ( 'There has been a problem serving this request.' ) ; $ response -> headers -> set ( 'content-type' , 'text/html' ) ; $ response -> setStatusCode ( Response :: HTTP_INTERNAL_SERVER_ERROR ) ; if ( is_callable ( $ this -> error ) ) { $ response = call_user_func ( $ this -> error , $ response , $ exception ) ; } $ response -> send ( ) ; } | Set an error response . |
22,497 | public function send ( Response $ response = null ) { if ( $ response ) { $ this -> response = $ response ; } $ this -> response -> prepare ( $ this -> request ) ; $ this -> response -> send ( ) ; if ( is_callable ( $ this -> cacheWrite ) ) { call_user_func_array ( $ this -> cacheWrite , array ( $ this -> cache , $ this -> getCachePath ( ) ) ) ; } } | Send the response to the browser . |
22,498 | private function processImage ( File $ file , ImageManager $ imageManager , TemplateInterface $ template ) { $ image = new \ Diarmuidie \ ImageRack \ Image \ Process ( $ file -> readStream ( ) , $ imageManager ) ; return $ image -> process ( $ template ) ; } | Process an image using the provided template . |
22,499 | private function parsePath ( $ path ) { $ parts = array ( 'template' => null , 'path' => null , ) ; if ( preg_match ( '/^\/?(.*?)\/(.*)/' , $ path , $ matches ) ) { $ parts [ 'template' ] = $ matches [ 1 ] ; $ parts [ 'path' ] = $ matches [ 2 ] ; } return $ parts ; } | Parse the request path to extract the path and template elements . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.