1: <?php
2:
3: /*
4: * The MIT License (MIT)
5: *
6: * Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
7: *
8: * Permission is hereby granted, free of charge, to any person obtaining a copy of
9: * this software and associated documentation files (the "Software"), to deal in
10: * the Software without restriction, including without limitation the rights to
11: * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
12: * the Software, and to permit persons to whom the Software is furnished to do so,
13: * subject to the following conditions:
14: *
15: * The above copyright notice and this permission notice shall be included in all
16: * copies or substantial portions of the Software.
17: *
18: * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19: * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
20: * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
21: * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
22: * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23: * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24: */
25:
26: namespace Kint\Object\Representation;
27:
28: class SourceRepresentation extends Representation
29: {
30: public $hints = array('source');
31: public $source = array();
32: public $filename;
33: public $line = 0;
34: public $showfilename = false;
35:
36: public function __construct($filename, $line, $padding = 7)
37: {
38: parent::__construct('Source');
39:
40: $this->filename = $filename;
41: $this->line = $line;
42:
43: $start_line = \max($line - $padding, 1);
44: $length = $line + $padding + 1 - $start_line;
45: $this->source = self::getSource($filename, $start_line, $length);
46: if (null !== $this->source) {
47: $this->contents = \implode("\n", $this->source);
48: }
49: }
50:
51: /**
52: * Gets section of source code.
53: *
54: * @param string $filename Full path to file
55: * @param int $start_line The first line to display (1 based)
56: * @param null|int $length Amount of lines to show
57: *
58: * @return null|array
59: */
60: public static function getSource($filename, $start_line = 1, $length = null)
61: {
62: if (!$filename || !\file_exists($filename) || !\is_readable($filename)) {
63: return null;
64: }
65:
66: $source = \preg_split("/\r\n|\n|\r/", \file_get_contents($filename));
67: $source = \array_combine(\range(1, \count($source)), $source);
68: $source = \array_slice($source, $start_line - 1, $length, true);
69:
70: return $source;
71: }
72: }
73: