运行代码
@param Closure $runFunc
@return string
170571
private function run(\Closure &$runFunc)
    {
        $__out = new Outer($this->sdopx);
        $_sdopx = $this->sdopx;
        try {
            call_user_func($runFunc, $_sdopx, $__out);
        } catch (\ErrorException $exception) {
            $__out->throw($exception);
        }
        return $__out->getCode();
    }
204466
private static function createProxyCode(\ReflectionFunction $function): string
    {
        $param = paramsOf($function);
        $return = true;
        $returnType = determineReturnTypeOf($function);
        if ($returnType === ': void') {
            $return = false;
        }

        $code  = sprintf(
                    "class %sCallMapProxy extends \bovigo\callmap\FunctionProxy{\n"
                    . "    protected \$paramNames = %s;\n"
                    . "    public function preventParentCalls(): self\n"
                    . "    {\n"
                    . "        \$this->parentCallsAllowed = false;\n"
                    . "        return \$this;\n"
                    . "    }\n"
                    . "    public function __invoke(%s)%s {\n"
                    . "        %s\$this->handleFunctionCall(func_get_args());\n"
                    . "    }\n"
                    . "    protected \$returnVoid = %s;"
                    . "}\n",
                    ucfirst($function->getShortName()),
                    var_export($param['names'], true),
                    $param['string'],
                    determineReturnTypeOf($function),
                    $return ? 'return ' : '',
                    $return ? 'false' : 'true'
        );
        if ($function->inNamespace()) {
            return sprintf(
                    "namespace %s {\n%s}\n",
                    $function->getNamespaceName(),
                    $code
            );
        }

        return $code;
    }
504608
public function run($commands, Closure $callback = null)
    {
        $commands = (array) $commands;
        $commands = implode(' && ', $commands);

        $this->previousStatus = 0;
        $process = new Process($commands);
        $process->setIdleTimeout(60 * 60);
        $process->run(function ($type, $line) use ($callback) {
            $callback($line);
        });

        $this->previousStatus = $process->getExitCode();
    }
1073252
public function runDelayed($jobId, \Closure $runCallback)
    {
        $job = $this->jobProcessor->findJobById($jobId);
        if (! $job) {
            throw JobNotFoundException::create($jobId);
        }
        $this->throwIfJobIsStale($job);

        if ($job->getRootJob()->isInterrupted()) {
            if (! $job->getStoppedAt()) {
                $this->jobProcessor->cancelChildJob($job);
            }

            return null;
        }

        $this->jobExtension->onPreRunDelayed($job);

        if ($this->isReadyForStart($job)) {
            $this->jobProcessor->startChildJob($job);
        }

        $result = $this->callbackResult($runCallback, $job);

        if (! $job->getStoppedAt()) {
            $result
                ? $this->jobProcessor->successChildJob($job)
                : $this->jobProcessor->failChildJob($job);
        }

        $this->jobExtension->onPostRunDelayed($job, $result);

        return $result;
    }
598069
public function get_run($run_id, $type, &$run_desc) {
        global $DB;

        $rec = $DB->get_record('profiling', array('runid' => $run_id), '*', MUST_EXIST);

        $this->runid = $rec->runid;
        $this->url = $rec->url;
        $this->totalexecutiontime = $rec->totalexecutiontime;
        $this->totalcputime = $rec->totalcputime;
        $this->totalcalls = $rec->totalcalls;
        $this->totalmemory = $rec->totalmemory;
        $this->timecreated = $rec->timecreated;

        $run_desc = $this->url . ($rec->runreference ? ' (R) ' : ' ') . ' - ' . s($rec->runcomment);

        // Handle historical runs that aren't compressed.
        if (@gzuncompress(base64_decode($rec->data)) === false) {
            return unserialize(base64_decode($rec->data));
        } else {
            return unserialize(gzuncompress(base64_decode($rec->data)));
        }
    }
669657
public function run()
    {
        if ($this->is_route == true) {
            if ($this->segments instanceof \Closure) {
                echo call_user_func($this->segments);
                die();
            } else {
                $class = $this->getBundleUrl();
            }
        } else {
            $class = $this->getUnBundleUrl();

            if (!class_exists($class)) {

                $this->initDefaultRoute();

                $class = $this->getBundleUrl();
            }
        }

        if (!class_exists($class)) {
            $message = sprintf('No route found for "%s %s"', Zilf::$container['request']->getMethod(), Zilf::$container['request']->getPathInfo());

            if ($referer = Zilf::$container['request']->headers->get('referer')) {
                $message .= sprintf(' (from "%s")', $referer);
            }
            throw new NotFoundHttpException($message);
        }

        unset($this->segments);

        //将参数追加到GET里面
        if (!empty($this->params)) {
            foreach ($this->params as $key => $row) {
                if (is_string($key)) {
                    $_GET[$key] = $row;
                } else {
                    $_GET['zget' . $key] = $row;
                }
            }
            Zilf::$container->getShare('request')->query->add($_GET);
        }

        $object = Zilf::$container->build($class, []);
        if (method_exists($object, $this->action)) {

            $response = call_user_func_array(array($object, $this->action), $this->params);
            if (!$response instanceof Response) {
                $msg = sprintf('The controller must return a response (%s given).', $this->varToString($response));

                // the user may have forgotten to return something
                if (null === $response) {
                    $msg .= ' Did you forget to add a return statement somewhere in your controller?';
                }
                throw new \LogicException($msg);
            }
            $response->send();

        } else {
            throw new \Exception('类: ' . $class . ' 调用的方法：' . $this->action . ' 不存在！');
        }
    }
15633
public function traceRuntimeCalls($files, $productLine) {
        $runtimeCalls = array();
        
        foreach ($files as $file) {            
            $content = $file->getContent();
            if ($content instanceof fphp\File\StoredFileContent) {
                $fileSource = $content->getFileSource();
                $content = file_get_contents($fileSource);
            } else {
                $fileSource = "(text file)";
                $content = $content->getSummary();
            }
            
            foreach (explode("\n", $content) as $idx => $line)
                if (strstr($line, "$this->class::$this->getter")) {
                    preg_match("/$this->class::$this->getter\(.*?[\"'](.*?)[\"'].*?\)/", $line, $matches);
                    try {
                        $feature = $productLine->getFeature($matches[1]);
                    } catch (fphp\Model\ModelException $e) {
                        throw new RuntimeGeneratorException("invalid runtime feature \"$matches[1]\"");
                    }
                    $runtimeCalls[] = new fphp\Artifact\TracingLink(
                        "runtime",
                        $productLine->getArtifact($feature),
                        new fphp\Artifact\LinePlace($fileSource, $idx + 1),
                        new fphp\Artifact\LinePlace($file->getTarget(), $idx + 1));
                }
        }
        
        return $runtimeCalls;
    }
745636
public function run()
    {
        $documentRoot = realpath($_SERVER['DOCUMENT_ROOT']);
        $getCwd = realpath(getcwd());

        $base = str_replace('\\', '/', str_replace($documentRoot, '', $getCwd) . '/');
        $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

        if (($base !== $uri) && (substr($uri, -1) === '/')) {
            $uri = substr($uri, 0, (strlen($uri)-1));
        }

        if ($uri === '') {
            $uri = '/';
        }

        $method = RouterRequest::getRequestMethod();
        $searches = array_keys($this->patterns);
        $replaces = array_values($this->patterns);
        $foundRoute = false;

        $routes = [];
        foreach ($this->routes as $data) {
            array_push($routes, $data['route']);
        }

        // check if route is defined without regex
        if (in_array($uri, array_values($routes))) {
            foreach ($this->routes as $data) {
                if (RouterRequest::validMethod($data['method'], $method) && ($data['route'] === $uri)) {
                    $foundRoute = true;
                    $this->runRouteMiddleware($data, 'before');
                    $this->runRouteCommand($data['callback']);
                    $this->runRouteMiddleware($data, 'after');
                    break;
                }
            }
        } else {
            foreach ($this->routes as $data) {
                $route = $data['route'];

                if (strpos($route, '{') !== false) {
                    $route = str_replace($searches, $replaces, $route);
                }

                if (preg_match('#^' . $route . '$#', $uri, $matched)) {
                    if (RouterRequest::validMethod($data['method'], $method)) {
                        $foundRoute = true;

                        $this->runRouteMiddleware($data, 'before');

                        array_shift($matched);
                        $newMatched = [];
                        foreach ($matched as $key => $value) {
                            if (strstr($value, '/')) {
                                foreach (explode('/', $value) as $k => $v) {
                                    $newMatched[] = trim(urldecode($v));
                                }
                            } else {
                                $newMatched[] = trim(urldecode($value));
                            }
                        }
                        $matched = $newMatched;

                        $this->runRouteCommand($data['callback'], $matched);
                        $this->runRouteMiddleware($data, 'after');
                        break;
                    }
                }
            }
        }

        // If it originally was a HEAD request, clean up after ourselves by emptying the output buffer
        if (strtoupper($_SERVER['REQUEST_METHOD']) === 'HEAD') {
            ob_end_clean();
        }

        if ($foundRoute === false) {
            if (! $this->errorCallback) {
                $this->errorCallback = function() {
                    header($_SERVER['SERVER_PROTOCOL']." 404 Not Found");
                    return $this->exception('Route not found. Looks like something went wrong. Please try again.');
                };
            }
            call_user_func($this->errorCallback);
        }
    }
400911
public static function runInTrans(\Closure $closure) {
        /* @var $connection Connection */
        $connection = Pool::get(Connection::class);
        $pool = ResourcePool::instance();
        //加锁保证事物内使用的是同一连接
        $pool->lock($connection);
        try {
            $value = $connection->runInTrans($closure);
            //释放锁
            $pool->unLock($connection);
            //释放连接
            $pool->release($connection);
            return $value;
        } catch (\RuntimeException $e) {
            $pool->unLock($connection);
            $pool->release($connection);
            throw $e;
        } catch (\Error $e) {
            $pool->unLock($connection);
            $pool->release($connection);
            throw $e;
        }
    }
129977
public function runScriptCommand(): void
    {
        /*$script = '<?php echo "foo"; ?>';*/
        $script = '<?php print_r($_SERVER); ?>';

        // $tmpDir = CliUtil::getTempDir();
        // $tmpFile = $tmpDir . '/' . md5($script) . '.php';
        // file_put_contents($tmpFile, $script);

        $descriptorSpec = [
            0 => ['pipe', 'r'],  // 标准输入，子进程从此管道中读取数据
            1 => ['pipe', 'w'],  // 标准输出，子进程向此管道中写入数据
            2 => ['file', $this->app->getRootPath() . '/examples/tmp/error-output.log', 'a'] // 标准错误，写入到一个文件
        ];

        $process = proc_open('php', $descriptorSpec, $pipes);

        if (\is_resource($process)) {
            // $pipes 现在看起来是这样的：
            // 0 => 可以向子进程标准输入写入的句柄
            // 1 => 可以从子进程标准输出读取的句柄
            // 错误输出将被追加到文件 error-output.txt

            fwrite($pipes[0], $script);
            fclose($pipes[0]);

            $result = stream_get_contents($pipes[1]);

            fclose($pipes[1]);

            $this->write("RESULT:\n" . $result);

            // 切记：在调用 proc_close 之前关闭所有的管道以避免死锁。
            $retVal = proc_close($process);

            echo "command returned $retVal\n";
        }

    }
1270931
protected function withCustomCanonicalUrl(callable $run)
    {
        $customCanonicalUrl = $this->getCustomSiteCanonicalUrl();
        if ($customCanonicalUrl !== '') {
            $siteConfig = $this->getPageListGenerator()->getSite()->getConfigRepository();
            $originalSiteCanonicalUrl = $siteConfig->get('seo.canonical_url');
            $siteConfig->set('seo.canonical_url', $customCanonicalUrl);
        }
        try {
            return $run();
        } finally {
            if ($customCanonicalUrl !== '') {
                $siteConfig->set('seo.canonical_url', $originalSiteCanonicalUrl);
            }
        }
    }
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']);
    };
  }
366157
private function getRunTags(RunInterface $run)
    {
        return [
            'run' => [
                'type'         => get_class($run),
                'id'           => spl_object_hash($run),
                'tags'         => $run->getTags(),
                'hasStarted'   => $run->hasStarted(),
                'isRunning'    => $run->isRunning(),
                'isSuccessful' => $run->isSuccessful(),
                'duration'     => $run->getDuration(),
                'priority'     => $run->getPriority(),
                'progress'     => $run->getProgress() ? $run->getProgress()[0] : null,
            ],
        ];
    }
403283
private function exec(callable $fn)
    {
        ob_start();

        try {
            $returnData = call_user_func_array($fn, $this->args);
        } catch (Exception $e) {
            ob_end_clean();
            throw $e;
        }

        $outputBuffer = ob_get_clean();

        foreach ($this->outputTo as $filename) {
            if ($outputBuffer) {
                file_put_contents($filename, $outputBuffer, $this->outputMode === 'a' ? FILE_APPEND : 0);
            }

            if ($returnData) {
                file_put_contents($filename, $returnData, FILE_APPEND);
            }
        }

        $this->removeLockFile();

        return $outputBuffer . (is_string($returnData) ? $returnData : '');
    }
745233
public static function mapCommand(callable $f)
    {
        return function (callable $handler) use ($f) {
            return function (
                CommandInterface $command,
                RequestInterface $request = null
            ) use ($handler, $f) {
                return $handler($f($command), $request);
            };
        };
    }
723971
def func_runtime(callback):
    
    now = time.time()
    print('%s - start: %f' % (callback, now))
    callback()
    now = time.time() - now
    print('%s - spent: %f Second' % (callback, now))
977989
public static function make($cache, \Closure $callback)
    {
        // Return Closure callback
        if (array_key_exists($cache, static::$drivers)) {
            return static::getCacheDriver($callback, $cache);
        }

        throw new \RuntimeException('Cache driver not found!');
    }