直接出力された内容を握りつぶす

デフォだと zend-stratigility の Emitter が Content-Length を吐くため、
直接出力していると Response オブジェクトのサイズと実際の出力サイズに齟齬が生じて、
出力が途中で切れてしまう。

このミドルウェアは出力バッファリングを用いて直接出力を握りつぶす。

@return \Closure
768665
private function outputBufferingHandlerMiddleware()
    {
        return function (ServerRequestInterface $request, DelegateInterface $delegate) {
            ob_start();
            try {
                $response = $delegate->process($request);
            } finally {
                ob_end_clean();
            }
            return $response;
        };
    }
763152
public function log() : \Closure
    {
        $logger    = $this->logger;
        $formatter = $this->formatter;

        return function (callable $handler) use ($logger, $formatter) {

            return function ($request, array $options) use ($handler, $logger, $formatter) {
                // generate id that will be used to supplement the log with information
                $requestId = uniqid('eight_points_guzzle_');

                // initial registration of log
                $logger->info('', compact('request', 'requestId'));

                // this id will be used by RequestTimeMiddleware
                $options['request_id'] = $requestId;

                return $handler($request, $options)->then(

                    function ($response) use ($logger, $request, $formatter, $requestId) {

                        $message = $formatter->format($request, $response);
                        $context = compact('request', 'response', 'requestId');

                        $logger->info($message, $context);

                        return $response;
                    },

                    function ($reason) use ($logger, $request, $formatter, $requestId) {

                        $response = $reason instanceof RequestException ? $reason->getResponse() : null;
                        $message  = $formatter->format($request, $response, $reason);
                        $context  = compact('request', 'response', 'requestId');

                        $logger->notice($message, $context);

                        return \GuzzleHttp\Promise\rejection_for($reason);
                    }
                );
            };
        };
    }
1035617
public function getDefaultMessage()
    {
        switch ($this->type) {
            case self::WIDTH:
                return sprintf(
                    _t(
                        'ZenValidator.DIMWIDTH',
                        'Image width must be %s pixels'
                    ),
                    $this->val1
                );
                break;
            case self::HEIGHT:
                return sprintf(
                    _t(
                        'ZenValidator.DIMHEIGHT',
                        'Image height must be %s pixels'
                    ),
                    $this->val1
                );
                break;
            case self::WIDTH_HEIGHT:
                return sprintf(
                    _t(
                        'ZenValidator.DIMWIDTHHEIGHT',
                        'Image width must be %s pixels and Image height must be %s pixels'
                    ),
                    $this->val1,
                    $this->val2
                );
                break;
            case self::RATIO:
                return sprintf(
                    _t(
                        'ZenValidator.DIMRATIO',
                        'Image aspect ratio (shape) must be %s:%s'
                    ),
                    $this->val1,
                    $this->val2
                );
                break;
            case self::MIN_WIDTH:
                return sprintf(
                    _t(
                        'ZenValidator.DIMMINWIDTH',
                        'Image width must be greater than or equal to %s pixels'
                    ),
                    $this->val1
                );
                break;
            case self::MIN_HEIGHT:
                return sprintf(
                    _t(
                        'ZenValidator.DIMMINHEIGHT',
                        'Image height must be greater than or equal to %s pixels'
                    ),
                    $this->val1
                );
                break;
            case self::MIN_WIDTH_HEIGHT:
                return sprintf(
                    _t(
                        'ZenValidator.DIMMINWIDTHHEIGHT',
                        'Image width must be greater than or equal to %s pixels and Image height must be greater than or equal to %s pixels'
                    ),
                    $this->val1,
                    $this->val2
                );
                break;
            case self::MAX_WIDTH:
                return sprintf(
                    _t(
                        'ZenValidator.DIMMAXWIDTH',
                        'Image width must be less than or equal to %s pixels'
                    ),
                    $this->val1
                );
                break;
            case self::MAX_HEIGHT:
                return sprintf(
                    _t(
                        'ZenValidator.DIMMAXHEIGHT',
                        'Image height must be less than or equal to %s pixels'
                    ),
                    $this->val1
                );
                break;
            case self::MAX_WIDTH_HEIGHT:
                return sprintf(
                    _t(
                        'ZenValidator.DIMMAXWIDTHHEIGHT',
                        'Image width must be less than or equal to %s pixels and Image height must be less than or equal to %s pixels'
                    ),
                    $this->val1,
                    $this->val2
                );
                break;
        }
    }
950
protected function dispatchToRouter() : Closure
    {
        return function ($request) {
            return $this->router->setContainer($this->container)->dispatch($request);
        };
    }
901163
public function getAction()
	{
		$cntl = $this->createAdmin();

		if( ( $html = $cntl->get() ) == '' ) {
			return $this->setPsrResponse( $cntl->getView()->response() );
		}

		$this->view->assign( 'content', $html );
	}
530485
function getTranslate(): \Closure {
    return function($value, \Mustache_LambdaHelper $helper) {
      $defaultArgs = [
        'category' => $this->defaultCategory,
        'language' => null,
        'params' => []
      ];

      $output = trim($value);
      $isJSON = mb_substr($output, 0, 1) == '{' && mb_substr($output, mb_strlen($output) - 1) == '}';

      if ($isJSON) $args = $this->parseArguments($helper->render($value), 'message', $defaultArgs);
      else {
        /** @var string[] $parts */
        $parts = explode($this->argumentSeparator, $output, 2);
        $length = count($parts);
        if (!$length) throw new InvalidCallException('Invalid translation format.');

        $args = ArrayHelper::merge($defaultArgs, [
          'category' => $length == 1 ? $this->defaultCategory : rtrim($parts[0]),
          'message' => ltrim($parts[$length - 1])
        ]);
      }

      return \Yii::t($args['category'], $args['message'], $args['params'], $args['language']);
    };
  }
901075
public function uploadAction()
    {
        $authenticationService = $this->getServiceLocator()->get('zfcuser_auth_service');
        if (!$authenticationService->hasIdentity()) {
            return $this->redirect()->toRoute('zfcuser');
        }

        $user = $this->getUser();
        if (!$user) {
            return $this->notFoundAction();
        }
        $options = $this->getOptions();
        $form = $this->getServiceLocator()->get('HtProfileImage\ProfileImageForm');
        /** @var \Zend\Http\Request $request */
        $request = $this->getRequest();
        $imageUploaded = false;
        if ($request->isPost()) {
            $negotiator   = new FormatNegotiator();
            $format = $negotiator->getBest(
                $request->getHeader('Accept')->getFieldValue(),
                ['application/json', 'text/html']
            );
            if ($this->profileImageService->storeImage($user, $request->getFiles()->toArray())) {
                if ($format->getValue() === 'application/json') {
                    return new Model\JsonModel([
                        'uploaded' => true
                    ]);
                } elseif ($options->getPostUploadRoute()) {
                        return call_user_func_array([$this->redirect(), 'toRoute'], (array) $options->getPostUploadRoute());
                }
                $imageUploaded = true;
            } else {
                $response = $this->getResponse();
                /** @var \Zend\Http\Response $response */
                $response->setStatusCode(400);
                if ($format->getValue() === 'application/json') {
                    return new Model\JsonModel([
                        'error' => true,
                        'messages' => $form->getMessages()
                    ]);
                }

            }
        }

        return new Model\ViewModel([
            'form' => $form,
            'imageUploaded' => $imageUploaded,
            'user' => $user
        ]);
    }
455569
public function logoutAction()
    {
        $return = $this->getReturnUri();
        $auth   = $this->getServiceLocator()
                       ->get( 'Zend\Authentication\AuthenticationService' );

        if ( ! $auth->hasIdentity() )
        {
            $returnUri = $this->getValidReturnUri( $return );

            if ( empty( $returnUri ) ||
                 static::DEFAULT_RETURN_URI == $returnUri )
            {
                return $this->redirect()
                            ->toRoute( 'Grid\User\Authentication\Login', array(
                                'locale' => (string) $this->locale(),
                            ) );
            }
            else
            {
                return $this->redirect()
                            ->toUrl( $returnUri );
            }
        }

        /* @var $form \Zend\Form\Form */
        $request    = $this->getRequest();
        $params     = $this->params();
        $immediate  = $params->fromRoute( 'immediate', false );
        $data       = $request->getPost();
        $form       = $this->getServiceLocator()
                           ->get( 'Form' )
                           ->create( 'Grid\User\Logout', array(
                               'returnUri' => $return,
                           ) );

        $form->setData( $data );

        if ( $immediate || ( $request->isPost() && $form->isValid() ) )
        {
            /* @var $logger \Zork\Log\LoggerManager */
            $logger = $this->getServiceLocator()
                           ->get( 'Zork\Log\LoggerManager' );

            if ( $logger->hasLogger( 'application' ) )
            {
                $logger->getLogger( 'application' )
                       ->notice( 'user-logout' );
            }

            if ( $immediate )
            {
                $data = $return ? array( 'returnUri' => $return ) : array();
            }
            else
            {
                $data = $form->getData();
            }

            /* @var $sessm \Zend\Session\SessionManager */
            $sessm  = $this->getSessionManager();
            $result = $this->getServiceLocator()
                           ->get( 'Grid\User\Authentication\Service' )
                           ->logout( $data, $sessm, $auth );

            $sessm->regenerateId( false );

            if ( empty( $result['returnUri'] ) )
            {
                $returnUri = $return;
            }
            else
            {
                $returnUri = $result['returnUri'];
            }

            return $this->redirect()
                        ->toUrl( $this->getValidReturnUri( $returnUri ) );
        }

        $this->plugin( 'layout' )
             ->setMiddleLayout( 'layout/middle/center' );

        return array(
            'form'      => $form,
            'display'   => $this->getServiceLocator()
                                ->get( 'Config' )
                                     [ 'modules' ]
                                     [ 'Grid\User' ]
                                     [ 'display' ]
        );
    }
421318
public function prepareShutdown()
    {
        if ($this->inShutdown) {
            return false;
        }

        if ($this->errorLogger && $logs = $this->errorLogger->cleanLogs()) {
            $messages = array_map(
                function ($item) {
                    //array($level, $message, $context);
                    $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();

        // $this->controller->close() is no longer called here, because it prevented
        // shutdown functions from triggering (see https://github.com/php-pm/php-pm/pull/432)

        if ($this->server) {
            @$this->server->close();
        }

        if ($this->loop) {
            $this->loop->stop();
        }

        return true;
    }
301918
public function cliRegister() : Closure
  {
    return function($exception, $inspector, $run) {
      Output::error($exception);
      die($exception . PHP_EOL);
      exit;
    };
  }
11546
public function phpTravisCi()
    {
        $this->executeCommandHook(__FUNCTION__, 'before');
        $this->getProjectInstance()
            ->setupTravisCi();
        $this->executeCommandHook(__FUNCTION__, 'after');

        return $this;
    }
223497
public function finalise_content() : string {
        $this->write_html_data();

        $exportfile = make_request_directory() . '/export.zip';

        $fp = get_file_packer();
        $fp->archive_to_pathname($this->files, $exportfile);

        // Reset the writer to prevent any further writes.
        writer::reset();

        return $exportfile;
    }
1338697
public function getContent() {
        $cmd = Factory::config('php_path', 'php').' -dvld.active=1 '.$this->srcFile;  // 替换为你要执行的shell脚本
        $process = Process::factory($cmd);
        $status = $process->start()->join()->stop();
        extract($process->getOutput());
        return $stderr;
    }
822162
public function prevElement ()
	{
		if (($arrTypes = $GLOBALS['templateTypes'][$this->ptable.'.'.$this->pid]) === null)
		{
			$objCte = \ContentModel::findPublishedByPidAndTable($this->pid, $this->ptable);
			
			if ($objCte === null)
			{
				return;
			}
			
			$arrTypes = $GLOBALS['templateTypes'][$this->ptable.'.'.$this->pid] = $objCte->fetchEach('type');
		}

		return $arrTypes[array_keys($arrTypes)[array_search($this->id, array_keys($arrTypes)) - 1]];
	}
720068
public function contentUriAction()
    {
        $actual = $this->getSubDomainModel()
                       ->findActual();

        if ( empty( $actual ) )
        {
            $this->getResponse()
                 ->setStatusCode( 404 );

            return;
        }

        $uri = $this->params()
                    ->fromRoute( 'uri' );

        // prevent "Invalid Encoding Attack"
        if ( ! mb_check_encoding( $uri, 'UTF-8' ) )
        {
            $this->getResponse()
                 ->setStatusCode( 404 );

            return;
        }

        $structure = $this->getUriModel()
                          ->findBySubdomainUri( $actual->id, $uri );

        if ( empty( $structure ) )
        {
            $this->paragraphLayout();

            $this->getResponse()
                 ->setStatusCode( 404 );

            return;
        }

        if ( ! $structure->default )
        {
            $default = $this->getUriModel()
                            ->findDefaultByContentSubdomain(
                                $structure->contentId,
                                $actual->id,
                                $structure->locale
                            );

            if ( $default->uri != $structure->uri ) // Avoid infinite redirect circles
            {
                $response = $this->getResponse();

                $response->getHeaders()
                         ->addHeaderLine( 'Location',
                                          '/' . $default->safeUri );

                // Permanent redirect: for "old" uris
                return $response->setStatusCode( 301 );
            }
        }

        if ( ! empty( $structure->locale ) )
        {
            $this->getServiceLocator()
                 ->get( 'Locale' )
                 ->setCurrent( $structure->locale );
        }

        return $this->forward()
                    ->dispatch( 'Grid\Paragraph\Controller\Render', array(
                        'controller'    => 'Grid\Paragraph\Controller\Render',
                        'action'        => 'paragraph',
                        'locale'        => (string) $this->locale(),
                        'paragraphId'   => $structure->contentId
                    ) );
    }
468909
private function swishAfter()
  {
    $events = $this;
    return function($route) use ($events) {
      $events->handleResponse($route->response);
      return Events::trigger('routes.handle', [$route]);
    };
  }
825365
public function getVolumeId()
    {
        $fullId = $this->getId()->getText();
        $position = strrpos($fullId, '/');
        if ($position === false) {
            require_once 'Zend/Gdata/App/Exception.php';
            throw new Zend_Gdata_App_Exception('Slash not found in atom:id');
        } else {
            return substr($fullId, strrpos($fullId,'/') + 1);
        }
    }