PhpDocController.php 11.4 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\build\controllers;

10
use Yii;
11 12
use yii\console\Controller;
use yii\helpers\Console;
13
use yii\helpers\FileHelper;
14 15 16

/**
 * PhpDocController is there to help maintaining PHPDoc annotation in class files
17
 *
18 19 20 21 22 23
 * @author Carsten Brandt <mail@cebe.cc>
 * @author Alexander Makarov <sam@rmcreative.ru>
 * @since 2.0
 */
class PhpDocController extends Controller
{
24 25 26
	public $defaultAction = 'property';

	/**
27
	 * @var boolean whether to update class docs directly. Setting this to false will just output docs
28 29 30 31
	 * for copy and paste.
	 */
	public $updateFiles = true;

32
	/**
Alexander Makarov committed
33
	 * Generates `@property annotations` in class files from getters and setters
34
	 *
Alexander Makarov committed
35
	 * Property description will be taken from getter or setter or from an `@property annotation`
36 37 38 39
	 * in the getters docblock if there is one defined.
	 *
	 * See https://github.com/yiisoft/yii2/wiki/Core-framework-code-style#documentation for details.
	 *
Alexander Makarov committed
40
	 * @param string $root the directory to parse files from. Defaults to YII_PATH.
41
	 */
42
	public function actionProperty($root = null)
43
	{
44
		$except = [];
45
		if ($root === null) {
Qiang Xue committed
46
			$root = dirname(YII_PATH);
Qiang Xue committed
47
			$extensionPath = "$root/extensions";
48 49 50 51 52
			foreach (scandir($extensionPath) as $extension) {
				if (ctype_alpha($extension) && is_dir($extensionPath . '/' . $extension)) {
					Yii::setAlias("@yii/$extension", "$extensionPath/$extension");
				}
			}
53 54

			$except = [
55
				'.git/',
56 57 58
				'/apps/',
				'/build/',
				'/docs/',
59 60 61
				'/extensions/apidoc/helpers/PrettyPrinter.php',
				'/extensions/codeception/TestCase.php',
				'/extensions/codeception/DbTestCase.php',
Qiang Xue committed
62
				'/extensions/composer/',
63
				'/extensions/gii/components/DiffRendererHtmlInline.php',
64
				'/extensions/gii/generators/extension/templates/*',
65 66 67
				'/extensions/twig/TwigSimpleFileLoader.php',
				'/framework/BaseYii.php',
				'/framework/Yii.php',
68 69
				'tests/',
				'vendor/',
70
			];
71
		}
72
		$root = FileHelper::normalizePath($root);
Alexander Makarov committed
73
		$options = [
74 75 76 77 78 79 80 81 82
			'filter' => function ($path) {
				if (is_file($path)) {
					$file = basename($path);
					if ($file[0] < 'A' || $file[0] > 'Z') {
						return false;
					}
				}
				return null;
			},
83
			'only' => ['*.php'],
84
			'except' => array_merge($except, [
85 86 87 88
				'views/',
				'requirements/',
				'gii/generators/',
				'vendor/',
89
			]),
Alexander Makarov committed
90
		];
91
		$files = FileHelper::findFiles($root, $options);
92
		$nFilesTotal = 0;
93
		$nFilesUpdated = 0;
94 95 96 97
		foreach ($files as $file) {
			$result = $this->generateClassPropertyDocs($file);
			if ($result !== false) {
				list($className, $phpdoc) = $result;
98
				if ($this->updateFiles) {
99 100 101 102 103 104 105 106 107 108
					if ($this->updateClassPropertyDocs($file, $className, $phpdoc)) {
						$nFilesUpdated++;
					}
				} elseif (!empty($phpdoc)) {
					$this->stdout("\n[ " . $file . " ]\n\n", Console::BOLD);
					$this->stdout($phpdoc);
				}
			}
			$nFilesTotal++;
		}
109

110
		$this->stdout("\nParsed $nFilesTotal files.\n");
111
		$this->stdout("Updated $nFilesUpdated files.\n");
112 113
	}

Alexander Makarov committed
114 115 116
	/**
	 * @inheritdoc
	 */
117
	public function options($id)
118
	{
119
		return array_merge(parent::options($id), ['updateFiles']);
120 121
	}

122
	protected function updateClassPropertyDocs($file, $className, $propertyDoc)
123
	{
124 125 126 127 128
		$ref = new \ReflectionClass($className);
		if ($ref->getFileName() != $file) {
			$this->stderr("[ERR] Unable to create ReflectionClass for class: $className loaded class is not from file: $file\n", Console::FG_RED);
		}

129
		if (!$ref->isSubclassOf('yii\base\Object') && $className != 'yii\base\Object') {
130
			$this->stderr("[INFO] Skipping class $className as it is not a subclass of yii\\base\\Object.\n", Console::FG_BLUE, Console::BOLD);
131 132 133
			return false;
		}

134 135 136 137 138 139
		$oldDoc = $ref->getDocComment();
		$newDoc = $this->cleanDocComment($this->updateDocComment($oldDoc, $propertyDoc));

		$seenSince = false;
		$seenAuthor = false;

140
		// TODO move these checks to different action
141
		$lines = explode("\n", $newDoc);
142 143 144
		if (trim($lines[1]) == '*' || substr(trim($lines[1]), 0, 3) == '* @') {
			$this->stderr("[WARN] Class $className has no short description.\n", Console::FG_YELLOW, Console::BOLD);
		}
145
		foreach ($lines as $line) {
146 147 148 149 150 151 152 153 154 155 156 157 158 159
			if (substr(trim($line), 0, 9) == '* @since ') {
				$seenSince = true;
			} elseif (substr(trim($line), 0, 10) == '* @author ') {
				$seenAuthor = true;
			}
		}

		if (!$seenSince) {
			$this->stderr("[ERR] No @since found in class doc in file: $file\n", Console::FG_RED);
		}
		if (!$seenAuthor) {
			$this->stderr("[ERR] No @author found in class doc in file: $file\n", Console::FG_RED);
		}

160
		if (trim($oldDoc) != trim($newDoc)) {
161

162 163 164
			$fileContent = explode("\n", file_get_contents($file));
			$start = $ref->getStartLine() - 2;
			$docStart = $start - count(explode("\n", $oldDoc)) + 1;
165

Alexander Makarov committed
166
			$newFileContent = [];
167
			$n = count($fileContent);
168
			for ($i = 0; $i < $n; $i++) {
169
				if ($i > $start || $i < $docStart) {
170
					$newFileContent[] = $fileContent[$i];
171 172
				} else {
					$newFileContent[] = trim($newDoc);
173
					$i = $start;
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
				}
			}

			file_put_contents($file, implode("\n", $newFileContent));

			return true;
		}
		return false;
	}

	/**
	 * remove multi empty lines and trim trailing whitespace
	 *
	 * @param $doc
	 * @return string
	 */
	protected function cleanDocComment($doc)
	{
		$lines = explode("\n", $doc);
		$n = count($lines);
194
		for ($i = 0; $i < $n; $i++) {
195 196 197 198 199 200 201 202 203
			$lines[$i] = rtrim($lines[$i]);
			if (trim($lines[$i]) == '*' && trim($lines[$i + 1]) == '*') {
				unset($lines[$i]);
			}
		}
		return implode("\n", $lines);
	}

	/**
Alexander Makarov committed
204
	 * Replace property annotations in doc comment
205 206 207 208 209 210 211 212 213
	 * @param $doc
	 * @param $properties
	 * @return string
	 */
	protected function updateDocComment($doc, $properties)
	{
		$lines = explode("\n", $doc);
		$propertyPart = false;
		$propertyPosition = false;
214
		foreach ($lines as $i => $line) {
215 216 217 218 219 220 221
			if (substr(trim($line), 0, 12) == '* @property ') {
				$propertyPart = true;
			} elseif ($propertyPart && trim($line) == '*') {
				$propertyPosition = $i;
				$propertyPart = false;
			}
			if (substr(trim($line), 0, 10) == '* @author ' && $propertyPosition === false) {
222
				$propertyPosition = $i - 1;
223 224 225 226 227 228 229
				$propertyPart = false;
			}
			if ($propertyPart) {
				unset($lines[$i]);
			}
		}
		$finalDoc = '';
230
		foreach ($lines as $i => $line) {
231 232 233 234 235 236
			$finalDoc .= $line . "\n";
			if ($i == $propertyPosition) {
				$finalDoc .= $properties;
			}
		}
		return $finalDoc;
237 238 239 240
	}

	protected function generateClassPropertyDocs($fileName)
	{
241 242
		$phpdoc = "";
		$file = str_replace("\r", "", str_replace("\t", " ", file_get_contents($fileName, true)));
243 244 245
		$ns = $this->match('#\nnamespace (?<name>[\w\\\\]+);\n#', $file);
		$namespace = reset($ns);
		$namespace = $namespace['name'];
246
		$classes = $this->match('#\n(?:abstract )?class (?<name>\w+)( extends .+)?( implements .+)?\n\{(?<content>.*)\n\}(\n|$)#', $file);
247 248 249 250 251 252

		if (count($classes) > 1) {
			$this->stderr("[ERR] There should be only one class in a file: $fileName\n", Console::FG_RED);
			return false;
		}
		if (count($classes) < 1) {
253
			$interfaces = $this->match('#\ninterface (?<name>\w+)( extends .+)?\n\{(?<content>.+)\n\}(\n|$)#', $file);
254 255 256 257 258
			if (count($interfaces) == 1) {
				return false;
			} elseif (count($interfaces) > 1) {
				$this->stderr("[ERR] There should be only one interface in a file: $fileName\n", Console::FG_RED);
			} else {
259 260 261 262 263 264 265 266
				$traits = $this->match('#\ntrait (?<name>\w+)\n\{(?<content>.+)\n\}(\n|$)#', $file);
				if (count($traits) == 1) {
					return false;
				} elseif (count($traits) > 1) {
					$this->stderr("[ERR] There should be only one class/trait/interface in a file: $fileName\n", Console::FG_RED);
				} else {
					$this->stderr("[ERR] No class in file: $fileName\n", Console::FG_RED);
				}
267
			}
268 269 270 271
			return false;
		}

		$className = null;
272
		foreach ($classes as &$class) {
273

274
			$className = $namespace . '\\' . $class['name'];
275

276
			$gets = $this->match(
277
				'#\* @return (?<type>[\w\\|\\\\\\[\\]]+)(?: (?<comment>(?:(?!\*/|\* @).)+?)(?:(?!\*/).)+|[\s\n]*)\*/' .
278 279 280
				'[\s\n]{2,}public function (?<kind>get)(?<name>\w+)\((?:,? ?\$\w+ ?= ?[^,]+)*\)#',
				$class['content']);
			$sets = $this->match(
281
				'#\* @param (?<type>[\w\\|\\\\\\[\\]]+) \$\w+(?: (?<comment>(?:(?!\*/|\* @).)+?)(?:(?!\*/).)+|[\s\n]*)\*/' .
282 283
				'[\s\n]{2,}public function (?<kind>set)(?<name>\w+)\(\$\w+(?:, ?\$\w+ ?= ?[^,]+)*\)#',
				$class['content']);
284 285 286 287 288 289
			// check for @property annotations in getter and setter
			$properties = $this->match(
				'#\* @(?<kind>property) (?<type>[\w\\|\\\\\\[\\]]+)(?: (?<comment>(?:(?!\*/|\* @).)+?)(?:(?!\*/).)+|[\s\n]*)\*/' .
				'[\s\n]{2,}public function [g|s]et(?<name>\w+)\(((?:,? ?\$\w+ ?= ?[^,]+)*|\$\w+(?:, ?\$\w+ ?= ?[^,]+)*)\)#',
				$class['content']);
			$acrs = array_merge($properties, $gets, $sets);
290

Alexander Makarov committed
291
			$props = [];
292 293 294
			foreach ($acrs as &$acr) {
				$acr['name'] = lcfirst($acr['name']);
				$acr['comment'] = trim(preg_replace('#(^|\n)\s+\*\s?#', '$1 * ', $acr['comment']));
Alexander Makarov committed
295
				$props[$acr['name']][$acr['kind']] = [
296 297
					'type' => $acr['type'],
					'comment' => $this->fixSentence($acr['comment']),
Alexander Makarov committed
298
				];
299 300 301
			}

			ksort($props);
302

303 304 305
			if (count($props) > 0) {
				$phpdoc .= " *\n";
				foreach ($props as $propName => &$prop) {
306 307
					$docline = ' * @';
					$docline .= 'property'; // Do not use property-read and property-write as few IDEs support complex syntax.
308
					$note = '';
309
					if (isset($prop['get']) && isset($prop['set'])) {
310 311
						if ($prop['get']['type'] != $prop['set']['type']) {
							$note = ' Note that the type of this property differs in getter and setter.'
Luciano Baraglia committed
312
								  . ' See [[get' . ucfirst($propName) . '()]] and [[set' . ucfirst($propName) . '()]] for details.';  
313
						}
314
					} elseif (isset($prop['get'])) {
315 316 317
						// check if parent class has setter defined
						$c = $className;
						$parentSetter = false;
Alexander Mohorev committed
318
						while ($parent = get_parent_class($c)) {
319 320 321 322 323 324 325 326 327 328
							if (method_exists($parent, 'set' . ucfirst($propName))) {
								$parentSetter = true;
								break;
							}
							$c = $parent;
						}
						if (!$parentSetter) {
							$note = ' This property is read-only.';
//							$docline .= '-read';
						}
329
					} elseif (isset($prop['set'])) {
330 331 332
						// check if parent class has getter defined
						$c = $className;
						$parentGetter = false;
Alexander Mohorev committed
333
						while ($parent = get_parent_class($c)) {
334 335 336 337 338 339 340 341 342 343
							if (method_exists($parent, 'set' . ucfirst($propName))) {
								$parentGetter = true;
								break;
							}
							$c = $parent;
						}
						if (!$parentGetter) {
							$note = ' This property is write-only.';
//							$docline .= '-write';
						}
344 345
					} else {
						continue;
346 347 348 349 350 351 352 353 354
					}
					$docline .= ' ' . $this->getPropParam($prop, 'type') . " $$propName ";
					$comment = explode("\n", $this->getPropParam($prop, 'comment') . $note);
					foreach ($comment as &$cline) {
						$cline = ltrim($cline, '* ');
					}
					$docline = wordwrap($docline . implode(' ', $comment), 110, "\n * ") . "\n";

					$phpdoc .= $docline;
355 356 357 358
				}
				$phpdoc .= " *\n";
			}
		}
Alexander Makarov committed
359
		return [$className, $phpdoc];
360 361 362 363
	}

	protected function match($pattern, $subject)
	{
Alexander Makarov committed
364
		$sets = [];
365 366 367 368 369 370
		preg_match_all($pattern . 'suU', $subject, $sets, PREG_SET_ORDER);
		foreach ($sets as &$set)
			foreach ($set as $i => $match)
				if (is_numeric($i) /*&& $i != 0*/)
					unset($set[$i]);
		return $sets;
371 372 373 374 375
	}

	protected function fixSentence($str)
	{
		// TODO fix word wrap
376 377 378
		if ($str == '')
			return '';
		return strtoupper(substr($str, 0, 1)) . substr($str, 1) . ($str[strlen($str) - 1] != '.' ? '.' : '');
379 380 381 382
	}

	protected function getPropParam($prop, $param)
	{
383
		return isset($prop['property']) ? $prop['property'][$param] : (isset($prop['get']) ? $prop['get'][$param] : $prop['set'][$param]);
384
	}
Qiang Xue committed
385
}