Reads a single line of data from the stream.

@param  string $token
@throws Exception
@return Str
769977
public function readLine($token = "\n")
  {
    $this->connect();

    $line = Str::factory("");

    while(!$line->endsWith($token))
    {
      $this->waitForReadyRead();

      $data = @fgets($this->stream, 4096);

      Signal::getInstance()->emit(strtolower($this->getAdapterType()) . "DataRead", $data);

      if($data === FALSE)
      {
        if($line->count())
        {
          $line->append($token);
        }
        else
        {
          throw new Exception("connection to server '" . $this->config["host"] . ":" . $this->config["port"] . "' lost");
        }
      }
      else
      {
        $line->append($data);
      }
    }

    return $line->trim();
  }
1175962
public function decode($token)
    {
        try {
            $data = JWT::decode($token, $this->secretKey, $this->allowed_algs);
        } catch (\UnexpectedValueException $e) {
            throw new \UnexpectedValueException($e->getMessage());
        } catch (\DomainException $e) {
            throw new \UnexpectedValueException($e->getMessage());
        }

        if ($data->exp < time()) {
            throw new \UnexpectedValueException('token not allowed');
        }

        return $data;
    }
116694
public function read($length = 4096)
  {
    $this->connect();
    $this->waitForReadyRead();

    $data = @stream_get_contents($this->stream, $length);

    Signal::getInstance()->emit(strtolower($this->getAdapterType()) . "DataRead", $data);

    if($data === FALSE)
    {
      throw new Exception("connection to server '" . $this->config["host"] . ":" . $this->config["port"] . "' lost");
    }

    return new Str($data);
  }
559188
public function decode(Token $token)
    {
        $payloadArray = $this->jwt->decode($token->get());

        $payload = $this->payloadFactory->setRefreshFlow($this->refreshFlow)->make($payloadArray);

        if ($this->blacklistEnabled && $this->blacklist->has($payload)) {
            throw new TokenBlacklistedException('The token has been blacklisted');
        }

        return $payload;
    }
1275442
public function parse(Token $token): string
    {
        $value = $token->getValue();
        if ('' === $value) {
            throw ExpressionLanguageExceptionFactory::createForUnparsableToken($token);
        }

        return $this->tokenizer->detokenize(substr($value, 1));
    }
995022
public function parse(Token $token)
    {
        $lineno = $token->getLine();
        $stream = $this->parser->getStream();

        $count = null;
        $vars = new ArrayExpression([], $lineno);
        $domain = null;
        $locale = null;
        if (!$stream->test(Token::BLOCK_END_TYPE)) {
            if ($stream->test('count')) {
                // {% trans count 5 %}
                $stream->next();
                $count = $this->parser->getExpressionParser()->parseExpression();
            }

            if ($stream->test('with')) {
                // {% trans with vars %}
                $stream->next();
                $vars = $this->parser->getExpressionParser()->parseExpression();
            }

            if ($stream->test('from')) {
                // {% trans from "messages" %}
                $stream->next();
                $domain = $this->parser->getExpressionParser()->parseExpression();
            }

            if ($stream->test('into')) {
                // {% trans into "fr" %}
                $stream->next();
                $locale = $this->parser->getExpressionParser()->parseExpression();
            } elseif (!$stream->test(Token::BLOCK_END_TYPE)) {
                throw new SyntaxError('Unexpected token. Twig was looking for the "with", "from", or "into" keyword.', $stream->getCurrent()->getLine(), $stream->getSourceContext());
            }
        }

        // {% trans %}message{% endtrans %}
        $stream->expect(Token::BLOCK_END_TYPE);
        $body = $this->parser->subparse([$this, 'decideTransFork'], true);

        if (!$body instanceof TextNode && !$body instanceof AbstractExpression) {
            throw new SyntaxError('A message inside a trans tag must be a simple text.', $body->getTemplateLine(), $stream->getSourceContext());
        }

        $stream->expect(Token::BLOCK_END_TYPE);

        return new TransNode($body, $domain, $count, $vars, $locale, $lineno, $this->getTag());
    }
535252
private function decrypt(string $token): string
    {
        $serializer = new JWECompactSerializer(new StandardConverter());
        $jwe = $serializer->unserialize($token);
        $this->encryptionHeaderCheckerManager->check($jwe, 0);
        if (false === $this->jweLoader->decryptUsingKeySet($jwe, $this->encryptionKeyset, 0)) {
            throw new JWTDecodeFailureException('decoding_error', 'An error occurred while trying to decrypt the JWT token.');
        }

        return $jwe->getPayload();
    }
343418
public function decode($token)
    {
        $jwt = new JWT();

        try {
            $decoded = Codec::decode($token, $this->secret, ['HS256']);
        } catch (\Firebase\JWT\SignatureInvalidException $e) {
            $jwt->setSignatureValid(false);
        } catch (\Exception $e) {
        }

        list($header, $payload, $signature) = explode(".", $token);
        $header    = base64_decode($header);
        $payload   = json_decode(base64_decode($payload));
        $signature = base64_decode($signature);

        // Retrieves start and end public claims other claims are going to be ignored
        $jwt->setStart(new \DateTime('@'.$payload->nbf));
        $jwt->setEnd(new \Datetime('@'.$payload->exp));

        // Retrieves private claims
        foreach ($payload->data as $key => $value) {
            $jwt->set($key, $value);
        }

        return $jwt;
    }
429547
public function parse(Token $token)
    {
        $lineno = $token->getLine();
        $stream = $this->parser->getStream();

        $stream->expect(Token::BLOCK_END_TYPE);
        $try = $this->parser->subparse([$this, 'decideCatch']);
        $stream->next();
        $stream->expect(Token::BLOCK_END_TYPE);
        $catch = $this->parser->subparse([$this, 'decideEnd']);
        $stream->next();
        $stream->expect(Token::BLOCK_END_TYPE);

        return new TwigNodeTryCatch($try, $catch, $lineno, $this->getTag());
    }
480922
public function getPayload($token = false)
    {
        $this->requireToken($token);

        return $this->manager->decode($this->token);
    }
1253632
private function _parseOption($token)
    {
        $matches = array();

        if (substr($token, 0, 1) === '-' && !preg_match('/(?P<hyphen>\-{1,2})(?P<name>[a-z][a-z0-9_-]*)/i', $token, $matches)) {
            throw new \Exception(sprintf('Unable to parse option %s: Invalid syntax', $token));
        }

        if (!empty($matches['hyphen'])) {
            $type = (strlen($matches['hyphen']) === 1) ?
                self::OPTION_TYPE_SHORT:
                self::OPTION_TYPE_VERBOSE;
            return array($matches['name'], $type);
        }

        return array($token, self::OPTION_TYPE_ARGUMENT);
    }
411458
protected static function readFile($file)
    {
        $length = filesize($file);

        if (!($fd = fopen($file, 'rb'))) {
            throw new Exception("Cannot read the file '$file', probably permissions");
        }

        $content = $length ? fread($fd, $length) : '';
        fclose($fd);

        return $content;
    }
530865
public function decode($token)
    {
        $decoded = json_decode($token, true);

        if (is_array($decoded) === true &&
            array_key_exists(self::KEY_USER_ID, $decoded) === true &&
            array_key_exists(self::KEY_SECRET, $decoded) === true
        ) {
            $token  = $decoded[self::KEY_SECRET];
            $userId = intval($decoded[self::KEY_USER_ID]);
            /** @var User $user */
            $user   = (new User())->query()->find($userId);

            if ($user !== null && $user->{User::FIELD_API_TOKEN} === $token) {
                $account = new Account($user, [Account::ATTR_ID => $userId]);

                $this->getLogger()->debug('Account authenticated.', [User::FIELD_ID => $userId]);

                return $account;
            }
        }

        return new Anonymous();
    }
1236456
protected function getTextAction(Token $token)
    {
        // action to use for each line of the content of a <pre> Tag
        $tagPreBr = new Node('br', array('style' => array(), 'num' => 0), false);

        $actions = array();

        // if we are not in a <pre> tag
        if (!$this->tagPreIn) {
            // save the action
            $actions[] = new Node('write', array('txt' => $this->textParser->prepareTxt($token->getData())), false);
        } else { // else (if we are in a <pre> tag)
            // prepare the text
            $data = str_replace("\r", '', $token->getData());
            $lines = explode("\n", $data);

            // foreach line of the text
            foreach ($lines as $k => $txt) {
                // transform the line
                $txt = str_replace("\t", self::HTML_TAB, $txt);
                $txt = str_replace(' ', '&nbsp;', $txt);

                // add a break line
                if ($k > 0) {
                    $actions[] = clone $tagPreBr;
                }

                // save the action
                $actions[] = new Node('write', array('txt' => $this->textParser->prepareTxt($txt, false)), false);
            }
        }
        return $actions;
    }
1019751
private void parseToken(String token) {
        int len = token.length();

        for (int i = 0; i < len; i++) {
            int chr = sr.read();
            if (chr == -1) {
                throw new IllegalArgumentException("EOF reached while reading token: " + token);
            }
            chr = Character.toLowerCase((char)chr);
            int loTokenChar = token.charAt(i);

            if (loTokenChar != chr) {
                throw new IllegalArgumentException("Expected token: " + token + " at position " + sr.getPosition());
            }
        }
    }
307773
final public static function fromString(string $token): self
    {
        if (Binary::safeStrlen($token) < self::TOKEN_CHAR_LENGTH) {
            // Don't zero memory as the value is invalid.
            throw new \RuntimeException('Invalid token provided.');
        }

        $instance = new static();
        $instance->token = new HiddenString($token);
        $instance->selector = Binary::safeSubstr($token, 0, 32);
        $instance->verifier = Binary::safeSubstr($token, 32);

        // Don't (re)generate as this needs the salt of the stored hash.
        $instance->verifierHash = null;

        \sodium_memzero($token);

        return $instance;
    }
853812
public function read($count)
    {
        $contentLength = strlen($this->data);
        if ($this->position > $contentLength || $count > $contentLength - $this->position) {
            throw new EndOfStreamException(
                sprintf(
                    'End of stream reached when trying to read %d bytes. content length=%d, position=%d',
                    $count,
                    $contentLength,
                    $this->position
                )
            );
        }

        $chunk = substr($this->data, $this->position, $count);
        if ($chunk === false) {
            $chunk = '';
        }

        $readBytes = strlen($chunk);
        $this->position += $readBytes;

        return $chunk;
    }