1
0
mirror of https://github.com/danog/psalm.git synced 2024-12-13 17:57:37 +01:00
psalm/src/Psalm/FileManipulation.php

84 lines
2.3 KiB
PHP
Raw Normal View History

<?php
namespace Psalm;
use function sha1;
use function strlen;
2019-07-05 22:24:00 +02:00
use function strrpos;
use function substr;
use function trim;
final class FileManipulation
{
/** @var int */
public $start;
/** @var int */
public $end;
/** @var string */
public $insertion_text;
2019-06-04 22:36:32 +02:00
/** @var bool */
public $preserve_indentation;
/** @var bool */
public $remove_trailing_newline;
2020-10-15 19:04:24 +02:00
public function __construct(
int $start,
int $end,
string $insertion_text,
bool $preserve_indentation = false,
bool $remove_trailing_newline = false
) {
$this->start = $start;
$this->end = $end;
$this->insertion_text = $insertion_text;
2019-06-04 22:36:32 +02:00
$this->preserve_indentation = $preserve_indentation;
$this->remove_trailing_newline = $remove_trailing_newline;
}
2019-06-02 07:10:50 +02:00
public function getKey(): string
2019-06-02 07:10:50 +02:00
{
2019-06-10 23:09:34 +02:00
return $this->start === $this->end
? ($this->start . ':' . sha1($this->insertion_text))
: ($this->start . ':' . $this->end);
2019-06-02 07:10:50 +02:00
}
2019-06-04 22:36:32 +02:00
public function transform(string $existing_contents): string
2019-06-04 22:36:32 +02:00
{
if ($this->preserve_indentation) {
$newline_pos = strrpos($existing_contents, "\n", $this->start - strlen($existing_contents));
$newline_pos = $newline_pos !== false ? $newline_pos + 1 : 0;
$indentation = substr($existing_contents, $newline_pos, $this->start - $newline_pos);
if (trim($indentation) === '') {
2021-09-26 22:44:33 +02:00
$this->insertion_text .= $indentation;
2019-06-04 22:36:32 +02:00
}
}
2020-10-15 19:04:24 +02:00
if ($this->remove_trailing_newline
&& strlen($existing_contents) > $this->end
&& $existing_contents[$this->end] === "\n"
) {
$newline_pos = strrpos($existing_contents, "\n", $this->start - strlen($existing_contents));
$newline_pos = $newline_pos !== false ? $newline_pos + 1 : 0;
$indentation = substr($existing_contents, $newline_pos, $this->start - $newline_pos);
if (trim($indentation) === '') {
$this->start -= strlen($indentation);
$this->end++;
}
}
2019-06-04 22:36:32 +02:00
return substr($existing_contents, 0, $this->start)
. $this->insertion_text
. substr($existing_contents, $this->end);
}
}