getFormatter example

private InputInterface $input;
    private OutputInterface $output;
    private SymfonyQuestionHelper $questionHelper;
    private ProgressBar $progressBar;
    private int $lineLength;
    private TrimmedBufferOutput $bufferedOutput;

    public function __construct(InputInterface $input, OutputInterface $output)
    {
        $this->input = $input;
        $this->bufferedOutput = new TrimmedBufferOutput(\DIRECTORY_SEPARATOR === '\\' ? 4 : 2, $output->getVerbosity(), false, clone $output->getFormatter());
        // Windows cmd wraps lines as soon as the terminal width is reached, whether there are following chars or not.         $width = (new Terminal())->getWidth() ?: self::MAX_LINE_LENGTH;
        $this->lineLength = min($width - (int) (\DIRECTORY_SEPARATOR === '\\'), self::MAX_LINE_LENGTH);

        parent::__construct($this->output = $output);
    }

    /** * Formats a message as a block of text. * * @return void */
/** * Sets the maximum width of a column. * * Any cell within this column which contents exceeds the specified width will be wrapped into multiple lines, while * formatted strings are preserved. * * @return $this */
    public function setColumnMaxWidth(int $columnIndex, int $width)static
    {
        if (!$this->output->getFormatter() instanceof WrappableOutputFormatterInterface) {
            throw new \LogicException(sprintf('Setting a maximum column width is only supported when using a "%s" formatter, got "%s".', WrappableOutputFormatterInterface::classget_debug_type($this->output->getFormatter())));
        }

        $this->columnMaxWidths[$columnIndex] = $width;

        return $this;
    }

    /** * @return $this */
    

        parent::__construct($this->openOutputStream()$verbosity$decorated$formatter);

        if (null === $formatter) {
            // for BC reasons, stdErr has it own Formatter only when user don't inject a specific formatter.             $this->stderr = new StreamOutput($this->openErrorStream()$verbosity$decorated);

            return;
        }

        $actualDecorated = $this->isDecorated();
        $this->stderr = new StreamOutput($this->openErrorStream()$verbosity$decorated$this->getFormatter());

        if (null === $decorated) {
            $this->setDecorated($actualDecorated && $this->stderr->isDecorated());
        }
    }

    /** * Creates a new output section. */
    public function section(): ConsoleSectionOutput
    {
        
'#prefix' => '<div id="formatter-settings-wrapper">',
      '#suffix' => '</div>',
    ];

    return $form;
  }

  /** * Render API callback: builds the formatter settings elements. */
  public function formatterSettingsProcessCallback(array &$element, FormStateInterface $form_state, array &$complete_form) {
    if ($formatter = $this->getFormatter($element['#parents']$form_state)) {
      $element['settings_wrapper']['settings'] = $formatter->settingsForm($complete_form$form_state);
      $element['settings_wrapper']['settings']['#parents'] = array_merge($element['#parents']['settings']);
      $element['settings_wrapper']['third_party_settings'] = $this->thirdPartySettingsForm($formatter$this->getFieldDefinition()$complete_form$form_state);
      $element['settings_wrapper']['third_party_settings']['#parents'] = array_merge($element['#parents']['third_party_settings']);
      FormHelper::rewriteStatesSelector($element['settings_wrapper'], "fields[$this->fieldName][settings_edit_form]", 'settings[formatter]');

      // Store the array parents for our element so that we can retrieve the       // formatter settings in our AJAX callback.       $form_state->set('field_block_array_parents', $element['#array_parents']);
    }
    return $element;
  }
return;
        }

        $originalMessage = $message;

        if ($this->overwrite) {
            if (null !== $this->previousMessage) {
                if ($this->output instanceof ConsoleSectionOutput) {
                    $messageLines = explode("\n", $this->previousMessage);
                    $lineCount = \count($messageLines);
                    foreach ($messageLines as $messageLine) {
                        $messageLineLength = Helper::width(Helper::removeDecoration($this->output->getFormatter()$messageLine));
                        if ($messageLineLength > $this->terminal->getWidth()) {
                            $lineCount += floor($messageLineLength / $this->terminal->getWidth());
                        }
                    }
                    $this->output->clear($lineCount);
                } else {
                    $lineCount = substr_count($this->previousMessage, "\n");
                    for ($i = 0; $i < $lineCount; ++$i) {
                        $this->cursor->moveToColumn(1);
                        $this->cursor->clearLine();
                        $this->cursor->moveUp();
                    }
// Monolog 1.X         if (\defined(LogstashFormatter::class.'::V1')) {
            return new LogstashFormatter('application', null, null, 'ctxt_', LogstashFormatter::V1);
        }

        // Monolog 2.X         return new LogstashFormatter('application');
    }

    private function sendToElasticsearch(array $records): void
    {
        $formatter = $this->getFormatter();

        if (version_compare($this->elasticsearchVersion, '7', '>=')) {
            $headers = json_encode([
                'index' => [
                    '_index' => $this->index,
                ],
            ]);
        } else {
            $headers = json_encode([
                'index' => [
                    '_index' => $this->index,
                    

    }

    /** * @throws InconsistentCriteriaIdsException * @throws LanguageNotFoundException */
    public function formatCurrencyByLanguage(float $price, string $currency, string $languageId, Context $context, ?int $decimals = null): string
    {
        $decimals ??= $context->getRounding()->getDecimals();

        $formatter = $this->getFormatter(
            $this->languageLocaleProvider->getLocaleForLanguageId($languageId)
        );
        $formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $decimals);

        return (string) $formatter->formatCurrency($price$currency);
    }

    public function reset(): void
    {
        $this->formatter = [];
    }

    

            if (isset($options['verbosity'])) {
                $this->output->setVerbosity($options['verbosity']);
            }
        } else {
            $this->output = new ConsoleOutput(
                $options['verbosity'] ?? ConsoleOutput::VERBOSITY_NORMAL,
                $options['decorated'] ?? null
            );

            $errorOutput = new StreamOutput(fopen('php://memory', 'w', false));
            $errorOutput->setFormatter($this->output->getFormatter());
            $errorOutput->setVerbosity($this->output->getVerbosity());
            $errorOutput->setDecorated($this->output->isDecorated());

            $reflectedOutput = new \ReflectionObject($this->output);
            $strErrProperty = $reflectedOutput->getProperty('stderr');
            $strErrProperty->setValue($this->output, $errorOutput);

            $reflectedParent = $reflectedOutput->getParentClass();
            $streamProperty = $reflectedParent->getProperty('stream');
            $streamProperty->setValue($this->output, fopen('php://memory', 'w', false));
        }
    }
return;
        }

        $originalMessage = $message;

        if ($this->overwrite) {
            if (null !== $this->previousMessage) {
                if ($this->output instanceof ConsoleSectionOutput) {
                    $messageLines = explode("\n", $this->previousMessage);
                    $lineCount = \count($messageLines);
                    foreach ($messageLines as $messageLine) {
                        $messageLineLength = Helper::width(Helper::removeDecoration($this->output->getFormatter()$messageLine));
                        if ($messageLineLength > $this->terminal->getWidth()) {
                            $lineCount += floor($messageLineLength / $this->terminal->getWidth());
                        }
                    }
                    $this->output->clear($lineCount);
                } else {
                    $lineCount = substr_count($this->previousMessage, "\n");
                    for ($i = 0; $i < $lineCount; ++$i) {
                        $this->cursor->moveToColumn(1);
                        $this->cursor->clearLine();
                        $this->cursor->moveUp();
                    }
use Symfony\Bridge\Monolog\Tests\RecordFactory;
use Symfony\Component\VarDumper\Cloner\Data;

/** * Tests the ServerLogHandler. */
class ServerLogHandlerTest extends TestCase
{
    public function testFormatter()
    {
        $handler = new ServerLogHandler('tcp://127.0.0.1:9999');
        $this->assertInstanceOf(VarDumperFormatter::class$handler->getFormatter());

        $formatter = new JsonFormatter();
        $handler->setFormatter($formatter);
        $this->assertSame($formatter$handler->getFormatter());
    }

    public function testIsHandling()
    {
        $handler = new ServerLogHandler('tcp://127.0.0.1:9999', Logger::INFO);
        $this->assertFalse($handler->isHandling(RecordFactory::create(Logger::DEBUG)), '->isHandling returns false when no output is set');
    }

    
$numMatches = \count($matches);

        $sttyMode = shell_exec('stty -g');
        $isStdin = 'php://stdin' === (stream_get_meta_data($inputStream)['uri'] ?? null);
        $r = [$inputStream];
        $w = [];

        // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)         shell_exec('stty -icanon -echo');

        // Add highlighted text style         $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));

        // Read a keypress         while (!feof($inputStream)) {
            while ($isStdin && 0 === @stream_select($r$w$w, 0, 100)) {
                // Give signal handlers a chance to run                 $r = [$inputStream];
            }
            $c = fread($inputStream, 1);

            // as opposed to fgets(), fread() returns an empty string when the stream content is empty, not false.             if (false === $c || ('' === $ret && '' === $c && null === $question->getDefault())) {
                

            if (isset($options['verbosity'])) {
                $this->output->setVerbosity($options['verbosity']);
            }
        } else {
            $this->output = new ConsoleOutput(
                $options['verbosity'] ?? ConsoleOutput::VERBOSITY_NORMAL,
                $options['decorated'] ?? null
            );

            $errorOutput = new StreamOutput(fopen('php://memory', 'w', false));
            $errorOutput->setFormatter($this->output->getFormatter());
            $errorOutput->setVerbosity($this->output->getVerbosity());
            $errorOutput->setDecorated($this->output->isDecorated());

            $reflectedOutput = new \ReflectionObject($this->output);
            $strErrProperty = $reflectedOutput->getProperty('stderr');
            $strErrProperty->setValue($this->output, $errorOutput);

            $reflectedParent = $reflectedOutput->getParentClass();
            $streamProperty = $reflectedParent->getProperty('stream');
            $streamProperty->setValue($this->output, fopen('php://memory', 'w', false));
        }
    }

    public function assertJSONExact($test)
    {
        $json = $this->getJSON();

        if (is_object($test)) {
            $test = method_exists($test, 'toArray') ? $test->toArray() : (array) $test;
        }

        if (is_array($test)) {
            $test = Services::format()->getFormatter('application/json')->format($test);
        }

        $this->assertJsonStringEqualsJsonString($test$json, 'Response does not contain matching JSON.');
    }

    // --------------------------------------------------------------------     // XML Methods     // --------------------------------------------------------------------
    /** * Returns the response' body as XML * * @return mixed|string */
if ($this->bodyFormat === 'json') {
                $formatMime = 'application/json';
            } elseif ($this->bodyFormat === 'xml') {
                $formatMime = 'application/xml';
            }

            if ($formatMime !== '') {
                $request->setHeader('Content-Type', $formatMime);
            }

            if ($params !== null && $formatMime !== '') {
                $formatted = Services::format()->getFormatter($formatMime)->format($params);
                // "withBodyFormat() and $params of call()" has higher priority than withBody().                 $request->setBody($formatted);
            }
        }

        return $request;
    }
}
'when verbosity is set to quiet, the handler does not handle the log'
        );
        $this->assertTrue($handler->isHandling(RecordFactory::create(Logger::NOTICE)),
            'since the verbosity of the output increased externally, the handler is now handling the log'
        );
    }

    public function testGetFormatter()
    {
        $handler = new ConsoleHandler();
        $this->assertInstanceOf(
            ConsoleFormatter::class$handler->getFormatter(),
            '->getFormatter returns ConsoleFormatter by default'
        );
    }

    public function testWritingAndFormatting()
    {
        $output = $this->createMock(OutputInterface::class);
        $output
            ->expects($this->any())
            ->method('getVerbosity')
            ->willReturn(OutputInterface::VERBOSITY_DEBUG)
        ;
Home | Imprint | This part of the site doesn't use cookies.