Batch action.

@throws NotFoundHttpException If the HTTP method is not POST
@throws \RuntimeException     If the batch action is not defined

@return Response|RedirectResponse
777058
public function batchAction()
    {
        $request = $this->getRequest();
        $restMethod = $this->getRestMethod();

        if ('POST' !== $restMethod) {
            throw $this->createNotFoundException(sprintf('Invalid request type "%s", POST expected', $restMethod));
        }

        // check the csrf token
        $this->validateCsrfToken('sonata.batch');

        $confirmation = $request->get('confirmation', false);

        if ($data = json_decode((string) $request->get('data'), true)) {
            $action = $data['action'];
            $idx = $data['idx'];
            $allElements = $data['all_elements'];
            $request->request->replace(array_merge($request->request->all(), $data));
        } else {
            $request->request->set('idx', $request->get('idx', []));
            $request->request->set('all_elements', $request->get('all_elements', false));

            $action = $request->get('action');
            $idx = $request->get('idx');
            $allElements = $request->get('all_elements');
            $data = $request->request->all();

            unset($data['_sonata_csrf_token']);
        }

        // NEXT_MAJOR: Remove reflection check.
        $reflector = new \ReflectionMethod($this->admin, 'getBatchActions');
        if ($reflector->getDeclaringClass()->getName() === \get_class($this->admin)) {
            @trigger_error('Override Sonata\AdminBundle\Admin\AbstractAdmin::getBatchActions method'
                .' is deprecated since version 3.2.'
                .' Use Sonata\AdminBundle\Admin\AbstractAdmin::configureBatchActions instead.'
                .' The method will be final in 4.0.', E_USER_DEPRECATED
            );
        }
        $batchActions = $this->admin->getBatchActions();
        if (!\array_key_exists($action, $batchActions)) {
            throw new \RuntimeException(sprintf('The `%s` batch action is not defined', $action));
        }

        $camelizedAction = Inflector::classify($action);
        $isRelevantAction = sprintf('batchAction%sIsRelevant', $camelizedAction);

        if (method_exists($this, $isRelevantAction)) {
            $nonRelevantMessage = \call_user_func([$this, $isRelevantAction], $idx, $allElements, $request);
        } else {
            $nonRelevantMessage = 0 !== \count($idx) || $allElements; // at least one item is selected
        }

        if (!$nonRelevantMessage) { // default non relevant message (if false of null)
            $nonRelevantMessage = 'flash_batch_empty';
        }

        $datagrid = $this->admin->getDatagrid();
        $datagrid->buildPager();

        if (true !== $nonRelevantMessage) {
            $this->addFlash(
                'sonata_flash_info',
                $this->trans($nonRelevantMessage, [], 'SonataAdminBundle')
            );

            return $this->redirectToList();
        }

        $askConfirmation = $batchActions[$action]['ask_confirmation'] ??
            true;

        if ($askConfirmation && 'ok' !== $confirmation) {
            $actionLabel = $batchActions[$action]['label'];
            $batchTranslationDomain = $batchActions[$action]['translation_domain'] ??
                $this->admin->getTranslationDomain();

            $formView = $datagrid->getForm()->createView();
            $this->setFormTheme($formView, $this->admin->getFilterTheme());

            // NEXT_MAJOR: Remove these lines and use commented lines below them instead
            $template = !empty($batchActions[$action]['template']) ?
                $batchActions[$action]['template'] :
                $this->admin->getTemplate('batch_confirmation');
            // $template = !empty($batchActions[$action]['template']) ?
            //     $batchActions[$action]['template'] :
            //     $this->templateRegistry->getTemplate('batch_confirmation');

            return $this->renderWithExtraParams($template, [
                'action' => 'list',
                'action_label' => $actionLabel,
                'batch_translation_domain' => $batchTranslationDomain,
                'datagrid' => $datagrid,
                'form' => $formView,
                'data' => $data,
                'csrf_token' => $this->getCsrfToken('sonata.batch'),
            ], null);
        }

        // execute the action, batchActionXxxxx
        $finalAction = sprintf('batchAction%s', $camelizedAction);
        if (!method_exists($this, $finalAction)) {
            throw new \RuntimeException(sprintf('A `%s::%s` method must be callable', \get_class($this), $finalAction));
        }

        $query = $datagrid->getQuery();

        $query->setFirstResult(null);
        $query->setMaxResults(null);

        $this->admin->preBatchAction($action, $query, $idx, $allElements);

        if (\count($idx) > 0) {
            $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx);
        } elseif (!$allElements) {
            $this->addFlash(
                'sonata_flash_info',
                $this->trans('flash_batch_no_elements_processed', [], 'SonataAdminBundle')
            );

            return $this->redirectToList();
        }

        return \call_user_func([$this, $finalAction], $query, $request);
    }
704802
public function flushAllAction()
    {
        try {
            $this->getWorker()->execute('flushAll');
            
            $this->get('session')->getFlashBag()->add('success', 'Flush ALL executed successfully');
        }catch(\Exception $e) {
            $this->get('session')->getFlashBag()->add('error', 'We have encountered an error : '.$e->getMessage());
        }
        
        return new RedirectResponse($this->generateUrl('ringo_php_redmon'));
    }
1037406
public function route()
    {
        $batch = array();
                
        foreach ($this->request->getCalls() as $call) {
            $batch[] = $this->dispatch($call);
        }

        return $this->response->encode($batch);
    }
213491
public function batch($page, Request $request)
    {
        $this->authorize($action = $request->get('batch_action'), $model = app('scaffold.module')->model());

        $response = app('scaffold.actions')->exec('batch::'.$action, [$model, $request]);

        if ($response instanceof Response || $response instanceof Renderable) {
            return $response;
        }

        return back()->with(
            'messages',
            [trans('administrator::messages.action_success')]
        );
    }
306731
public function run()
    {
        $request  = clone $this->request;
        $response = new Response(404, new Stream(null));

        $this->container->callHook('app.response.before', [ &$request, &$response ]);

        if (($route = $this->router->parse($request)) && $response->getStatusCode() == 404) {
            $this->container->callHook($route[ 'key' ] . '.response.before', [
                &$request,
                &$response
            ]);

            $exec     = $this->router->execute($route, $request);
            $response = $this->parseResponse($exec);

            $this->container->callHook($route[ 'key' ] . '.response.after', [
                $this->request,
                &$response
            ]);
        }
        $this->container->callHook('app.' . $response->getStatusCode(), [
            $this->request,
            &$response
        ]);

        $this->container->callHook('app.response.after', [ $this->request, &$response ]);

        return $response;
    }
148457
public function run()
    {
        switch ($this->status) {
            case self::STATUS_ENDED:
                // We've already ended, lets just return
                return;

            case self::STATUS_INACTIVE:
                throw new \RuntimeException('Runtime has not yet booted.');
        }

        $runner = $this->getRunner();
        $response = $runner->run();

        if ($response) {
            $this->sendResponse($response);
        }

        return $response;
    }
1168740
public function execute()
    {
        $controller = $this->getController();

        if (!$controller) {
            $controller = $this->factoryController();
            $this->setController($controller);
        }

        $this->prepareController($controller);

        $action = $this->getAction();

        if (!$controller->respondTo($action)) {
            throw new Exceptions\ActionNotFoundException(sprintf(
                "Action '%s::%s' was not defined",
                $controller->getClass(),
                $action
            ));
        }

        $controller->beforeAction();
        $controller->send($action);
        $controller->afterAction();

        return $controller->getResponse();
    }
450774
private function RunRequest()
    {
        $result = curl_exec($this->_curlHandle);
        if ($result === false && curl_errno($this->_curlHandle) != 0) {
            $this->logger->error("cURL error: " . curl_error($this->_curlHandle));
            throw new Exception('cURL error: ' . curl_error($this->_curlHandle));
        }

        $response = new HttpResponse();
        $response->ResponseCode = (int) curl_getinfo($this->_curlHandle, CURLINFO_HTTP_CODE);

        curl_close($this->_curlHandle);

        $explode = explode("\r\n\r\n", $result);

        // multiple query (follow redirect) take only the last request
        $explode = array_slice($explode, sizeof($explode) - 2, 2);

        $response->Headers = explode("\n", implode($explode));
        $response->Body = array_pop($explode);

        return $response;
    }
898194
public function apiAction() {
        /**
         * Prepare the server. Zend_Json_Server cannot work with batched requests natively,
         * so that's taken care of customly here. Therefore, autoEmitResponse is set to false
         * so the server doesn't print the response directly.
         */
        $server = new Zend_Json_Server();
        $server->setClass('Garp_Content_Manager_Proxy');
        $server->setAutoEmitResponse(false);

        if ($this->getRequest()->isPost()) {
            $post = $this->_getJsonRpcRequest();
            $batch = false;
            $responses = array();
            $requests = Zend_Json::decode($post, Zend_Json::TYPE_ARRAY);
            /**
             * Check if this was a batch request. In that case the array is a plain array of
             * arrays. If not, there will be a 'jsonrpc' key in the root of the array.
             */
            $batch = !array_key_exists('jsonrpc', $requests);
            if (!$batch) {
                $requests = array($requests);
            }
            foreach ($requests as $i => $request) {
                $request = $this->_reformJsonRpcRequest($request);
                $requestJson = Zend_Json::encode($request);
                $requestObj = new Zend_Json_Server_Request();
                $requestObj->loadJson($requestJson);
                $server->setRequest($requestObj);
                /**
                 * Note; response gets returned by reference, resulting in a $responses array
                 * containing all the same items.
                 * That's why clone is used here.
                 */
                $response = clone $server->handle();
                $responses[] = $response;
            }
            $response = $batch ? '[' . implode(',', $responses) . ']' : $responses[0];
        } else {
            $response = $server->getServiceMap();
        }
        $this->_helper->layout->setLayout('json');
        //  filter out escaped slashes, because they're annoying and not necessary.
        $response = str_replace('\/', '/', $response);
        $this->view->response = $response;
    }
242029
function run()
    {
        $res = $this->resolve();

        $ctrl = isset($res['controller']) && $res['controller'] !== null ? $res['controller'] : $this->defaultController;
        $action = isset($res['action']) && $res['action'] !== null ? $res['action'] : $this->defaultAction;

        //Name format to Controller namespace
        $tmp = explode('\\', str_replace('/', '\\', $ctrl));
        $ctrl = '\\Controller';
        foreach($tmp as $tmp1){
            $ctrl .= '\\'.ucfirst($tmp1);
        }

        //instantiate the controller
        $controller = new $ctrl(['params' => $res['params'], 'request' => $this->request]);

        $this->params = $res['params'];

        if (method_exists($controller, $action))
            return $controller->$action();
        else
            return $controller->{static::$defaultAction}();
    }
915664
public function run()
	{
		if ( $this->description )
			touch( $this->mutexPath() );

		try
		{
			UniversalBuilder::call( $this->callback, $this->parameters )
		}
		finally
		{
			$this->removeMutex();
		}

		parent::callAfterCallbacks();

		return $response;
	}
5796
public function execute()
    {
        $data = [
            self::ENTRY_FLUSH => $this->_flush,
            self::ENTRY_COUNT => true
        ];

        if ($this->_batchSize > 0) {
            $data[self::ENTRY_BATCHSIZE] = $this->_batchSize;
        }

        if ($this->_limit > 0) {
            $data[self::ENTRY_LIMIT] = $this->_limit;
        }

        if (is_array($this->_restrictions)) {
            $data[self::ENTRY_RESTRICT] = $this->_restrictions;
        }

        $collection = $this->_collection;
        if ($collection instanceof Collection) {
            $collection = $collection->getName();
        }

        $url      = UrlHelper::appendParamsUrl(Urls::URL_EXPORT, ['collection' => $collection]);
        $response = $this->_connection->post($url, $this->getConnection()->json_encode_wrapper($data));

        return new ExportCursor($this->_connection, $response->getJson(), $this->getCursorOptions());
    }
1337898
public function onRun()
    {
        if (!$this->checkUserSecurity()) {
            if (empty($this->property('redirect'))) {
                throw new \InvalidArgumentException('Redirect property is empty');
            }
            
            $redirectUrl = $this->controller->pageUrl($this->property('redirect'));
            return Redirect::guest($redirectUrl);
        }

        $this->page['user'] = $this->user();
    }
911094
public function run()
    {
        if ($this->layout !== null) {
            $this->controller->layout = $this->layout;
        }

        $this->app->getResponse()->setStatusCodeByException($this->getException());

        if ($this->app->getRequest()->getIsAjax()) {
            return $this->renderAjaxResponse();
        }

        return $this->renderHtmlResponse();
    }
1253107
public function handler(): Response
    {
        $data = $this->validate([
            'role' => []
        ]);
        $member = Member::search($this->getParameter('username'));
        if (!$member) {
            throw new HttpNotFoundException();
        }
        $data['role'] = Role::findBy(['slug' => $data['role']]);
        if (!$data['role']) {
            throw new HttpForbiddenException();
        }
        $member->update($data);
        $this->log('info', 'Update member [' . $member->getUsername() . ']\'s role to [' . $data['role']->getSlug() . ']');
        return response();
    }
1223633
public function run(): SendableResponse
    {
        $request  = WebRequest::fromRawSource();
        $response = new WebResponse($request);
        if ($response->isFixed()) {
            return $response; // http version of request not supported
        }

        try {
            $requestUri = $request->uri();
        } catch (MalformedUri $mue) {
            $response->status()->badRequest();
            return $response;
        }

        $this->configureRouting($this->routing);
        $uriResource = $this->routing->findResource($requestUri, $request->method());
        if ($this->switchToHttps($request, $uriResource)) {
            $response->redirect($uriResource->httpsUri());
            return $response;
        }

        try {
            if (!$uriResource->negotiateMimeType($request, $response)) {
                return $response;
            }

            $this->sessionHandshake($request, $response);
            if ($uriResource->applyPreInterceptors($request, $response)) {
                $response->write($uriResource->resolve($request, $response));
                $uriResource->applyPostInterceptors($request, $response);
            }
        } catch (\Exception $e) {
            $this->injector->getInstance(ExceptionLogger::class)->log($e);
            $response->write($response->internalServerError($e->getMessage()));
        }

        return $response;
    }
550389
public function Process ()
	{

		// Work out which HTTP method were using and set as controller action
		// Default to get

		$this->action	= isset ($_SERVER['REQUEST_METHOD'])? strtolower ($_SERVER['REQUEST_METHOD']) : 'get';

		// HTTP_X_HTTP_METHOD override

		if ($this->action == 'post' && array_key_exists ('HTTP_X_HTTP_METHOD', $_SERVER))
		{
			if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'DELETE' ||
				$_SERVER['HTTP_X_HTTP_METHOD'] == 'PUT')
			{
				$this->action = strtolower ($_SERVER['HTTP_X_HTTP_METHOD']);
			}
			else
			{
				throw new \Sonic\Exception ('Unexpected HTTP_X_HTTP_METHOD header');
			}
		}

		// Check method is valid

		if (!in_array ($this->action, ['get','put','post','delete']))
		{
			throw new \Sonic\Exception ('Invalid Method', 405);
		}

		// Get redirect path

		$redirect	= isset ($_SERVER['REQUEST_URI'])? strtok ($_SERVER['REQUEST_URI'], '?') : '';

		// Get the position of the last / in the URL

		$pos		= strrpos ($redirect, '/');

		// If there is no / besides the first one then there is no ID

		if ($pos < 1)
		{
			$controller = substr ($redirect, $pos+1);
		}
		else
		{

			// Set the object ID and controller

			$this->id	= substr ($redirect, $pos+1);
			$controller	= substr ($redirect, 1, $pos-1);

		}

		// If there is a controller
		// Split controller by module and uppercase first character of each module
		// to keep in fitting with the rest of the framework

		if ($controller)
		{

			$arrController	= explode ('/', $controller);

			foreach ($arrController as &$controllerModule)
			{
				$controllerModule	= ucfirst ($controllerModule);
			}

			// Replace / in controller with \ for correct path and set controller

			$this->controller	= join ('\\', $arrController);

		}

	}