Completed
Push — master ( 228057...4623d7 )
by Robin
05:13
created

Parser   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 150
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
wmc 30
lcom 1
cbo 8
dl 0
loc 150
rs 10
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 18 6
A parseMode() 0 17 3
B parseStat() 0 17 5
B parseDir() 0 18 5
A parseListShares() 0 12 4
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
	/**
49
	 * @param TimeZoneProvider $timeZoneProvider
50
	 */
51
	public function __construct(TimeZoneProvider $timeZoneProvider) {
52
		$this->timeZoneProvider = $timeZoneProvider;
53
	}
54
55
	private function getErrorCode($line) {
56
		$parts = explode(' ', $line);
57
		foreach ($parts as $part) {
58
			if (substr($part, 0, 9) === 'NT_STATUS') {
59
				return $part;
60
			}
61
		}
62
		return false;
63
	}
64
65
	public function checkForError($output, $path) {
66
		if (strpos($output[0], 'does not exist')) {
67
			throw new NotFoundException($path);
68
		}
69
		$error = $this->getErrorCode($output[0]);
70
71
		if (substr($output[0], 0, strlen(self::MSG_NOT_FOUND)) === self::MSG_NOT_FOUND) {
72
			$localPath = substr($output[0], strlen(self::MSG_NOT_FOUND));
73
			throw new InvalidResourceException('Failed opening local file "' . $localPath . '" for writing');
74
		}
75
76
		throw Exception::fromMap(self::EXCEPTION_MAP, $error, $path);
77
	}
78
79
	/**
80
	 * check if the first line holds a connection failure
81
	 *
82
	 * @param $line
83
	 * @throws AuthenticationException
84
	 * @throws InvalidHostException
85
	 * @throws NoLoginServerException
86
	 */
87
	public function checkConnectionError($line) {
88
		$line = rtrim($line, ')');
89
		if (substr($line, -23) === ErrorCodes::LogonFailure) {
90
			throw new AuthenticationException('Invalid login');
91
		}
92
		if (substr($line, -26) === ErrorCodes::BadHostName) {
93
			throw new InvalidHostException('Invalid hostname');
94
		}
95
		if (substr($line, -22) === ErrorCodes::Unsuccessful) {
96
			throw new InvalidHostException('Connection unsuccessful');
97
		}
98
		if (substr($line, -28) === ErrorCodes::ConnectionRefused) {
99
			throw new InvalidHostException('Connection refused');
100
		}
101
		if (substr($line, -26) === ErrorCodes::NoLogonServers) {
102
			throw new NoLoginServerException('No login server');
103
		}
104
	}
105
106
	public function parseMode($mode) {
107
		$result = 0;
108
		$modeStrings = array(
109
			'R' => FileInfo::MODE_READONLY,
110
			'H' => FileInfo::MODE_HIDDEN,
111
			'S' => FileInfo::MODE_SYSTEM,
112
			'D' => FileInfo::MODE_DIRECTORY,
113
			'A' => FileInfo::MODE_ARCHIVE,
114
			'N' => FileInfo::MODE_NORMAL
115
		);
116
		foreach ($modeStrings as $char => $val) {
117
			if (strpos($mode, $char) !== false) {
118
				$result |= $val;
119
			}
120
		}
121
		return $result;
122
	}
123
124
	public function parseStat($output) {
125
		$data = [];
126
		foreach ($output as $line) {
127
			// A line = explode statement may not fill all array elements
128
			// properly. May happen when accessing non Windows Fileservers
129
			$words = explode(':', $line, 2);
130
			$name = isset($words[0]) ? $words[0] : '';
131
			$value = isset($words[1]) ? $words[1] : '';
132
			$value = trim($value);
133
			$data[$name] = $value;
134
		}
135
		return [
136
			'mtime' => strtotime($data['write_time']),
137
			'mode'  => hexdec(substr($data['attributes'], strpos($data['attributes'], '('), -1)),
138
			'size'  => isset($data['stream']) ? intval(explode(' ', $data['stream'])[1]) : 0
139
		];
140
	}
141
142
	public function parseDir($output, $basePath) {
143
		//last line is used space
144
		array_pop($output);
145
		$regex = '/^\s*(.*?)\s\s\s\s+(?:([NDHARS]*)\s+)?([0-9]+)\s+(.*)$/';
146
		//2 spaces, filename, optional type, size, date
147
		$content = array();
148
		foreach ($output as $line) {
149
			if (preg_match($regex, $line, $matches)) {
150
				list(, $name, $mode, $size, $time) = $matches;
151
				if ($name !== '.' and $name !== '..') {
152
					$mode = $this->parseMode($mode);
153
					$time = strtotime($time . ' ' . $this->timeZoneProvider->get());
154
					$content[] = new FileInfo($basePath . '/' . $name, $name, $size, $time, $mode);
155
				}
156
			}
157
		}
158
		return $content;
159
	}
160
161
	public function parseListShares($output) {
162
		$shareNames = array();
163
		foreach ($output as $line) {
164
			if (strpos($line, '|')) {
165
				list($type, $name, $description) = explode('|', $line);
166
				if (strtolower($type) === 'disk') {
167
					$shareNames[$name] = $description;
168
				}
169
			}
170
		}
171
		return $shareNames;
172
	}
173
}
174