1
0
mirror of https://github.com/danog/psalm.git synced 2024-12-14 18:36:58 +01:00
psalm/src/Psalm/FileManipulation.php

85 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;
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;
/**
* @param int $start
* @param int $end
* @param string $insertion_text
*/
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-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
{
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) === '') {
$this->insertion_text = $this->insertion_text . $indentation;
}
}
if ($this->remove_trailing_newline && $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);
}
}