# UnifiedDiffRenderer

> Renders the output of git diff --unified=<context>, without its diff --git and index lines, for two texts compared after normalizing their line endings to "\n".

[API reference](/docs/api/index.md) › [Diff](/docs/extensions/diff/reference/index.md) › UnifiedDiffRenderer

| final readonly class | `PHPForge\Diff\UnifiedDiffRenderer` |
| --- | --- |
| Source | [`src/UnifiedDiffRenderer.php`](https://github.com/php-forge/diff/blob/main/src/UnifiedDiffRenderer.php#L34) |

Renders the output of `git diff --unified=<context>`, without its `diff --git` and `index` lines, for two texts
compared after normalizing their line endings to `"\n"`.

The injected differ receives the lines without their terminators and a carriage return in place of a missing final
newline, so a last line without `"\n"` differs from the same line with one, as in Git, and a differ that weighs
indentation, such as [`LineDiffer`](/docs/extensions/diff/reference/linediffer/index.md), sees the layout of the original text. The rendered lines are taken back from
the texts by position, so any [`DifferInterface`](/docs/extensions/diff/reference/differinterface/index.md) implementation can be injected.

See also: <https://www.gnu.org/software/diffutils/manual/html_node/Unified-Format.html>.

## Methods

| Method | Description | Defined by |
| --- | --- | --- |
| [`__construct()`](#method-__construct) | Creates a renderer. | `UnifiedDiffRenderer` |
| [`render()`](#method-render) | Renders the unified diff that transforms `$old` into `$new`. | `UnifiedDiffRenderer` |

## Method details

### __construct() <span id="method-__construct"></span>

```php
public function __construct(PHPForge\Diff\DifferInterface $differ = new \PHPForge\Diff\LineDiffer())
```

Creates a renderer.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$differ` | [`DifferInterface`](/docs/extensions/diff/reference/differinterface/index.md) | Differ that computes the edit scripts. |

### render() <span id="method-render"></span>

```php
public function render(string $old, string $new, string $fromLabel, string $toLabel, int $context = 3): string
```

Renders the unified diff that transforms `$old` into `$new`.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$old` | `string` | Original text. |
| `$new` | `string` | Target text. |
| `$fromLabel` | `string` | Label written after `--- `. |
| `$toLabel` | `string` | Label written after `+++ `. |
| `$context` | `int` | Number of unchanged lines shown around each change; negative values count as `0`. |

**Returns**

`string`: Unified diff without a trailing newline, or an empty string when both texts are identical after line-ending normalization.

**Throws**

- [`LogicException`](https://www.php.net/manual/en/class.logicexception.php): when the differ returns a script that does not reproduce its inputs.