2017-09-16 18:45:11 +02:00
|
|
|
<?php
|
2018-11-12 16:46:55 +01:00
|
|
|
namespace Psalm;
|
2017-09-16 18:45:11 +02:00
|
|
|
|
|
|
|
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;
|
|
|
|
|
2017-09-16 18:45:11 +02:00
|
|
|
/**
|
|
|
|
* @param int $start
|
|
|
|
* @param int $end
|
|
|
|
* @param string $insertion_text
|
|
|
|
*/
|
2019-06-04 22:36:32 +02:00
|
|
|
public function __construct(int $start, int $end, string $insertion_text, bool $preserve_indentation = false)
|
2017-09-16 18:45:11 +02:00
|
|
|
{
|
|
|
|
$this->start = $start;
|
|
|
|
$this->end = $end;
|
|
|
|
$this->insertion_text = $insertion_text;
|
2019-06-04 22:36:32 +02:00
|
|
|
$this->preserve_indentation = $preserve_indentation;
|
2017-09-16 18:45:11 +02:00
|
|
|
}
|
2019-06-02 07:10:50 +02:00
|
|
|
|
|
|
|
public function getKey() : string
|
|
|
|
{
|
|
|
|
return sha1($this->start . ':' . $this->insertion_text);
|
|
|
|
}
|
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;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return substr($existing_contents, 0, $this->start)
|
|
|
|
. $this->insertion_text
|
|
|
|
. substr($existing_contents, $this->end);
|
|
|
|
}
|
2017-09-16 18:45:11 +02:00
|
|
|
}
|