Completed
Push — stable3.0 ( 04db6f )
by Robin
03:38
created

Parser   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 159
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 85.54%

Importance

Changes 0
Metric Value
wmc 32
lcom 1
cbo 9
dl 0
loc 159
ccs 71
cts 83
cp 0.8554
rs 9.84
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A getErrorCode() 0 9 3
A checkForError() 0 13 3
B checkConnectionError() 0 21 7
A parseMode() 0 9 3
A parseStat() 0 17 5
A parseDir() 0 18 5
A parseListShares() 0 16 5
1
<?php
2
/**
3
 * Copyright (c) 2014 Robin Appelman <[email protected]>
4
 * This file is licensed under the Licensed under the MIT license:
5
 * http://opensource.org/licenses/MIT
6
 */
7
8
namespace Icewind\SMB\Wrapped;
9
10
use Icewind\SMB\Exception\AccessDeniedException;
11
use Icewind\SMB\Exception\AlreadyExistsException;
12
use Icewind\SMB\Exception\AuthenticationException;
13
use Icewind\SMB\Exception\Exception;
14
use Icewind\SMB\Exception\FileInUseException;
15
use Icewind\SMB\Exception\InvalidHostException;
16
use Icewind\SMB\Exception\InvalidParameterException;
17
use Icewind\SMB\Exception\InvalidResourceException;
18
use Icewind\SMB\Exception\InvalidTypeException;
19
use Icewind\SMB\Exception\NoLoginServerException;
20
use Icewind\SMB\Exception\NotEmptyException;
21
use Icewind\SMB\Exception\NotFoundException;
22
use Icewind\SMB\TimeZoneProvider;
23
24
class Parser {
25
	const MSG_NOT_FOUND = 'Error opening local file ';
26
27
	/**
28
	 * @var \Icewind\SMB\TimeZoneProvider
29
	 */
30
	protected $timeZoneProvider;
31
32
	// todo replace with static once <5.6 support is dropped
33
	// see error.h
34
	const EXCEPTION_MAP = [
35
		ErrorCodes::LogonFailure      => AuthenticationException::class,
36
		ErrorCodes::PathNotFound      => NotFoundException::class,
37
		ErrorCodes::ObjectNotFound    => NotFoundException::class,
38
		ErrorCodes::NoSuchFile        => NotFoundException::class,
39
		ErrorCodes::NameCollision     => AlreadyExistsException::class,
40
		ErrorCodes::AccessDenied      => AccessDeniedException::class,
41
		ErrorCodes::DirectoryNotEmpty => NotEmptyException::class,
42
		ErrorCodes::FileIsADirectory  => InvalidTypeException::class,
43
		ErrorCodes::NotADirectory     => InvalidTypeException::class,
44
		ErrorCodes::SharingViolation  => FileInUseException::class,
45
		ErrorCodes::InvalidParameter  => InvalidParameterException::class
46
	];
47
48
	const MODE_STRINGS = [
49
		'R' => FileInfo::MODE_READONLY,
50
		'H' => FileInfo::MODE_HIDDEN,
51
		'S' => FileInfo::MODE_SYSTEM,
52
		'D' => FileInfo::MODE_DIRECTORY,
53
		'A' => FileInfo::MODE_ARCHIVE,
54
		'N' => FileInfo::MODE_NORMAL
55
	];
56
57
	/**
58
	 * @param TimeZoneProvider $timeZoneProvider
59
	 */
60 825
	public function __construct(TimeZoneProvider $timeZoneProvider) {
61 825
		$this->timeZoneProvider = $timeZoneProvider;
62 825
	}
63
64 60
	private function getErrorCode($line) {
65 60
		$parts = explode(' ', $line);
66 60
		foreach ($parts as $part) {
67 60
			if (substr($part, 0, 9) === 'NT_STATUS') {
68 60
				return $part;
69
			}
70
		}
71 6
		return false;
72
	}
73
74 60
	public function checkForError($output, $path) {
75 60
		if (strpos($output[0], 'does not exist')) {
76
			throw new NotFoundException($path);
77
		}
78 60
		$error = $this->getErrorCode($output[0]);
79
80 60
		if (substr($output[0], 0, strlen(self::MSG_NOT_FOUND)) === self::MSG_NOT_FOUND) {
81 3
			$localPath = substr($output[0], strlen(self::MSG_NOT_FOUND));
82 3
			throw new InvalidResourceException('Failed opening local file "' . $localPath . '" for writing');
83
		}
84
85 60
		throw Exception::fromMap(self::EXCEPTION_MAP, $error, $path);
86
	}
87
88
	/**
89
	 * check if the first line holds a connection failure
90
	 *
91
	 * @param $line
92
	 * @throws AuthenticationException
93
	 * @throws InvalidHostException
94
	 * @throws NoLoginServerException
95
	 * @throws AccessDeniedException
96
	 */
97 777
	public function checkConnectionError($line) {
98 777
		$line = rtrim($line, ')');
99 777
		if (substr($line, -23) === ErrorCodes::LogonFailure) {
100 3
			throw new AuthenticationException('Invalid login');
101
		}
102 774
		if (substr($line, -26) === ErrorCodes::BadHostName) {
103
			throw new InvalidHostException('Invalid hostname');
104
		}
105 774
		if (substr($line, -22) === ErrorCodes::Unsuccessful) {
106 9
			throw new InvalidHostException('Connection unsuccessful');
107
		}
108 768
		if (substr($line, -28) === ErrorCodes::ConnectionRefused) {
109
			throw new InvalidHostException('Connection refused');
110
		}
111 768
		if (substr($line, -26) === ErrorCodes::NoLogonServers) {
112
			throw new NoLoginServerException('No login server');
113
		}
114 768
		if (substr($line, -23) === ErrorCodes::AccessDenied) {
115
			throw new AccessDeniedException('Access denied');
116
		}
117 768
	}
118
119 324
	public function parseMode($mode) {
120 324
		$result = 0;
121 324
		foreach (self::MODE_STRINGS as $char => $val) {
122 324
			if (strpos($mode, $char) !== false) {
123 324
				$result |= $val;
124 9
			}
125 9
		}
126 324
		return $result;
127
	}
128
129 81
	public function parseStat($output) {
130 81
		$data = [];
131 81
		foreach ($output as $line) {
132
			// A line = explode statement may not fill all array elements
133
			// properly. May happen when accessing non Windows Fileservers
134 81
			$words = explode(':', $line, 2);
135 81
			$name = isset($words[0]) ? $words[0] : '';
136 81
			$value = isset($words[1]) ? $words[1] : '';
137 81
			$value = trim($value);
138 81
			$data[$name] = $value;
139 3
		}
140
		return [
141 81
			'mtime' => strtotime($data['write_time']),
142 81
			'mode'  => hexdec(substr($data['attributes'], strpos($data['attributes'], '('), -1)),
143 81
			'size'  => isset($data['stream']) ? (int)(explode(' ', $data['stream'])[1]) : 0
144 3
		];
145
	}
146
147 754
	public function parseDir($output, $basePath) {
148
		//last line is used space
149 754
		array_pop($output);
150 754
		$regex = '/^\s*(.*?)\s\s\s\s+(?:([NDHARS]*)\s+)?([0-9]+)\s+(.*)$/';
151
		//2 spaces, filename, optional type, size, date
152 754
		$content = array();
153 754
		foreach ($output as $line) {
154 754
			if (preg_match($regex, $line, $matches)) {
155 754
				list(, $name, $mode, $size, $time) = $matches;
156 754
				if ($name !== '.' and $name !== '..') {
157 292
					$mode = $this->parseMode($mode);
158 292
					$time = strtotime($time . ' ' . $this->timeZoneProvider->get());
159 600
					$content[] = new FileInfo($basePath . '/' . $name, $name, $size, $time, $mode);
160 1
				}
161 1
			}
162 1
		}
163 754
		return $content;
164
	}
165
166 6
	public function parseListShares($output) {
167 6
		$shareNames = array();
168 6
		foreach ($output as $line) {
169 6
			if (strpos($line, '|')) {
170
				list($type, $name, $description) = explode('|', $line);
171
				if (strtolower($type) === 'disk') {
172
					$shareNames[$name] = $description;
173
				}
174 6
			} else if (strpos($line, 'Disk')) {
175
				// new output format
176 6
				list($name, $description) = explode('Disk', $line);
177 6
				$shareNames[trim($name)] = trim($description);
178
			}
179
		}
180 6
		return $shareNames;
181
	}
182
}
183