setTimeout example


    public function connect() {
        if ( ! $this->ftp ) {
            return false;
        }

        $this->ftp->setTimeout( FS_CONNECT_TIMEOUT );

        if ( ! $this->ftp->SetServer( $this->options['hostname']$this->options['port'] ) ) {
            $this->errors->add(
                'connect',
                sprintf(
                    /* translators: %s: hostname:port */
                    __( 'Failed to connect to FTP Server %s' ),
                    $this->options['hostname'] . ':' . $this->options['port']
                )
            );

            
use PHPUnit\Framework\TestCase;
use Symfony\Component\Mailer\Exception\TransportException;
use Symfony\Component\Mailer\Transport\Smtp\Stream\SocketStream;

class SocketStreamTest extends TestCase
{
    public function testSocketErrorNoConnection()
    {
        $this->expectException(TransportException::class);
        $this->expectExceptionMessageMatches('/Connection refused|unable to connect/i');
        $s = new SocketStream();
        $s->setTimeout(0.1);
        $s->setPort(9999);
        $s->initialize();
    }

    public function testSocketErrorBeforeConnectError()
    {
        $this->expectException(TransportException::class);
        $this->expectExceptionMessageMatches('/no valid certs found cafile stream|Unable to find the socket transport "ssl"/');
        $s = new SocketStream();
        $s->setStreamOptions([
            'ssl' => [
                
        // on Gnu/Linux, PHP builds with --enable-maintainer-zts are also affected         // @see : https://bugs.php.net/51800         // @see : https://bugs.php.net/50524         if (null === $this->cwd && (\defined('ZEND_THREAD_SAFE') || '\\' === \DIRECTORY_SEPARATOR)) {
            $this->cwd = getcwd();
        }
        if (null !== $env) {
            $this->setEnv($env);
        }

        $this->setInput($input);
        $this->setTimeout($timeout);
        $this->useFileHandles = '\\' === \DIRECTORY_SEPARATOR;
        $this->pty = false;
    }

    /** * Creates a Process instance as a command-line to be run in a shell wrapper. * * Command-lines are parsed by the shell of your OS (/bin/sh on Unix-like, cmd.exe on Windows.) * This allows using e.g. pipes or conditional execution. In this mode, signals are sent to the * shell wrapper and not to your commands. * * In order to inject dynamic values into command-lines, we strongly recommend using placeholders. * This will save escaping values, which is not portable nor secure anyway: * * $process = Process::fromShellCommandline('my_command "${:MY_VAR}"'); * $process->run(null, ['MY_VAR' => $theValue]); * * @param string $command The command line to pass to the shell of the OS * @param string|null $cwd The working directory or null to use the working dir of the current PHP process * @param array|null $env The environment variables or null to use the same environment as the current PHP process * @param mixed $input The input as stream resource, scalar or \Traversable, or null for no input * @param int|float|null $timeout The timeout in seconds or null to disable * * @throws LogicException When proc_open is not installed */
public function testNegativeTimeoutFromConstructor()
    {
        $this->expectException(InvalidArgumentException::class);
        $this->getProcess('', null, null, null, -1);
    }

    public function testNegativeTimeoutFromSetter()
    {
        $this->expectException(InvalidArgumentException::class);
        $p = $this->getProcess('');
        $p->setTimeout(-1);
    }

    public function testFloatAndNullTimeout()
    {
        $p = $this->getProcess('');

        $p->setTimeout(10);
        $this->assertSame(10.0, $p->getTimeout());

        $p->setTimeout(null);
        $this->assertNull($p->getTimeout());

        

  private function generateThemeFromStarterkit($env = NULL) : Process {
    $install_command = [
      $this->php,
      'core/scripts/drupal',
      'generate-theme',
      'test_custom_theme',
      '--name="Test custom starterkit theme"',
      '--description="Custom theme generated from a starterkit theme"',
    ];
    $process = new Process($install_command, NULL, $env);
    $process->setTimeout(60);
    return $process;
  }

  /** * Asserts the theme exists. Returns the parsed *.info.yml file. * * @param string $theme_path_relative * The core-relative path to the theme. * * @return array * The parsed *.info.yml file. */
    // link generation works.
    $install_command = [
      $this->php,
      'core/scripts/drupal',
      'quick-start',
      'standard',
      "--site-name='Test site {$this->testDb->getDatabasePrefix()}'",
      '--suppress-login',
    ];
    $process = new Process($install_command, NULL, ['DRUPAL_DEV_SITE_PATH' => $this->testDb->getTestSitePath()]);
    $process->setTimeout(500);
    $process->start();
    $guzzle = new Client();
    $port = FALSE;
    $process->waitUntil(function D$type$output) use (&$port) {
      if (preg_match('/127.0.0.1:(\d+)/', $output$match)) {
        $port = $match[1];
        return TRUE;
      }
    });
    // The progress bar uses STDERR to write messages.     $this->assertStringContainsString('Congratulations, you installed Drupal!', $process->getErrorOutput());
    
        // on Gnu/Linux, PHP builds with --enable-maintainer-zts are also affected         // @see : https://bugs.php.net/51800         // @see : https://bugs.php.net/50524         if (null === $this->cwd && (\defined('ZEND_THREAD_SAFE') || '\\' === \DIRECTORY_SEPARATOR)) {
            $this->cwd = getcwd();
        }
        if (null !== $env) {
            $this->setEnv($env);
        }

        $this->setInput($input);
        $this->setTimeout($timeout);
        $this->useFileHandles = '\\' === \DIRECTORY_SEPARATOR;
        $this->pty = false;
    }

    /** * Creates a Process instance as a command-line to be run in a shell wrapper. * * Command-lines are parsed by the shell of your OS (/bin/sh on Unix-like, cmd.exe on Windows.) * This allows using e.g. pipes or conditional execution. In this mode, signals are sent to the * shell wrapper and not to your commands. * * In order to inject dynamic values into command-lines, we strongly recommend using placeholders. * This will save escaping values, which is not portable nor secure anyway: * * $process = Process::fromShellCommandline('my_command "${:MY_VAR}"'); * $process->run(null, ['MY_VAR' => $theValue]); * * @param string $command The command line to pass to the shell of the OS * @param string|null $cwd The working directory or null to use the working dir of the current PHP process * @param array|null $env The environment variables or null to use the same environment as the current PHP process * @param mixed $input The input as stream resource, scalar or \Traversable, or null for no input * @param int|float|null $timeout The timeout in seconds or null to disable * * @throws LogicException When proc_open is not installed */
//If no options are provided, use whatever is set in the instance         if (null === $options) {
            $options = $this->SMTPOptions;
        }

        //Already connected?         if ($this->smtp->connected()) {
            return true;
        }

        $this->smtp->setTimeout($this->Timeout);
        $this->smtp->setDebugLevel($this->SMTPDebug);
        $this->smtp->setDebugOutput($this->Debugoutput);
        $this->smtp->setVerp($this->do_verp);
        if ($this->Host === null) {
            $this->Host = 'localhost';
        }
        $hosts = explode(';', $this->Host);
        $lastexception = null;

        foreach ($hosts as $hostentry) {
            $hostinfo = [];
            

  public function executeCommand($command_line$working_dir = NULL) {
    $this->commandProcess = Process::fromShellCommandline($command_line);
    $this->commandProcess->setWorkingDirectory($this->getWorkingPath($working_dir))
      ->setTimeout(300)
      ->setIdleTimeout(300);
    $this->commandProcess->run();
    return $this->commandProcess;
  }

  /** * Helper function to assert that the last visit was a Drupal site. * * This method asserts that the X-Generator header shows that the site is a * Drupal site. */
  
$this->assertFalse($connection->write($data));
        $this->assertLessThan(4, microtime(true) - $start);
    }

    private function getServerProcess(): Process
    {
        $process = new PhpProcess(file_get_contents(__DIR__.'/../Fixtures/dump_server.php'), null, [
            'COMPONENT_ROOT' => __DIR__.'/../../',
            'VAR_DUMPER_SERVER' => self::VAR_DUMPER_SERVER,
        ]);

        return $process->setTimeout(9);
    }
}

  public function testInstallScript() {
    $simpletest_path = $this->root . DIRECTORY_SEPARATOR . 'sites' . DIRECTORY_SEPARATOR . 'simpletest';
    if (!is_writable($simpletest_path)) {
      $this->markTestSkipped("Requires the directory $simpletest_path to exist and be writable");
    }

    // Install a site using the JSON output.     $command_line = $this->php . ' core/scripts/test-site.php install --json --setup-file core/tests/Drupal/TestSite/TestSiteInstallTestScript.php --db-url "' . getenv('SIMPLETEST_DB') . '"';
    $process = Process::fromShellCommandline($command_line$this->root);
    // Set the timeout to a value that allows debugging.     $process->setTimeout(500);
    $process->run();

    $this->assertSame(0, $process->getExitCode());
    $result = json_decode($process->getOutput(), TRUE);
    $db_prefix = $result['db_prefix'];
    $this->assertStringStartsWith('simpletest' . substr($db_prefix, 4) . ':', $result['user_agent']);

    $http_client = new Client();
    $request = (new Request('GET', getenv('SIMPLETEST_BASE_URL') . '/test-page'))
      ->withHeader('User-Agent', trim($result['user_agent']));

    
DUMP
            , $dumped);
    }

    private function getServerProcess(): Process
    {
        $process = new PhpProcess(file_get_contents(__DIR__.'/../Fixtures/dump_server.php'), null, [
            'COMPONENT_ROOT' => __DIR__.'/../../',
            'VAR_DUMPER_SERVER' => self::VAR_DUMPER_SERVER,
        ]);

        return $process->setTimeout('\\' === \DIRECTORY_SEPARATOR ? 19 : 9);
    }
}
#[Package('core')] class StreamedCommandResponseGenerator
{
    /** * @param array<string> $params * @param callable(Process): void $finish */
    public function run(array $params, callable $finish): StreamedResponse
    {
        $process = new Process($params);
        $process->setEnv(['COMPOSER_HOME' => sys_get_temp_dir() . '/composer']);
        $process->setTimeout(300);

        $process->start();

        return new StreamedResponse(function D) use ($process$finish): void {
            foreach ($process->getIterator() as $item) {
                \assert(\is_string($item));
                echo $item;
                flush();
            }

            $finish($process);
        });

        return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->sSize(...\func_get_args());
    }

    public function sendEcho($msg)
    {
        return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->sendEcho(...\func_get_args());
    }

    public function setTimeout($key$timeout)
    {
        return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->setTimeout(...\func_get_args());
    }

    public function substr($key$start$end)
    {
        return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->substr(...\func_get_args());
    }

    public function zDelete($key$member, ...$other_members)
    {
        return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->zDelete(...\func_get_args());
    }

    
use Symfony\Component\Process\Exception\ProcessTimedOutException;
use Symfony\Component\Process\Process;

require is_file(\dirname(__DIR__).'/vendor/autoload.php') ? \dirname(__DIR__).'/vendor/autoload.php' : \dirname(__DIR__, 5).'/vendor/autoload.php';

['e' => $php] = getopt('e:') + ['e' => 'php'];

try {
    $process = new Process([$php, '-r', "echo 'ready'; trigger_error('error', E_USER_ERROR);"]);
    $process->start();
    $process->setTimeout(0.5);
    while (!str_contains($process->getOutput(), 'ready')) {
        usleep(1000);
    }
    $process->signal(\SIGSTOP);
    $process->wait();

    return $process->getExitCode();
} catch (ProcessTimedOutException $t) {
    echo $t->getMessage().\PHP_EOL;

    return 1;
}
Home | Imprint | This part of the site doesn't use cookies.