Skip to content

Commit c0bb414

Browse files
committed
Initial commit
0 parents  commit c0bb414

18 files changed

+653
-0
lines changed

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
/.idea/
2+
/vendor/

.travis.yml

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
language: php
2+
3+
before_script: composer install --dev
4+
5+
script:
6+
- mkdir -p build/logs
7+
- phpunit --coverage-clover build/logs/clover.xml
8+
9+
after_script:
10+
- php vendor/bin/coveralls -v

README.md

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Генератор phpStorm-метафайла для фабрик объектов.
2+
3+
## Установка
4+
5+
```
6+
composer require mediartis/phpstormmetagenerator
7+
```
8+
9+
## Пример использования
10+
Создаём файл со следующим кодом и запускаем его
11+
12+
### HostCMS
13+
14+
```
15+
use PhpStormMetaGenerator\Classes\HostCMS\AdminEntitiesNamespace;
16+
use PhpStormMetaGenerator\Classes\HostCMS\EntitiesNamespace;
17+
use PhpStormMetaGenerator\Classes\MetaGenerator;
18+
19+
// Путь к создаваемому мета-файлу
20+
$phpStormMetaFilePath = CMS_FOLDER . '.phpstorm.meta.php';
21+
// Путь к директории, содержащей ORM-сущности
22+
$entitiesPath = CMS_FOLDER . 'modules';
23+
// Путь к директории, содержащей специальные сущности панели администратора
24+
$adminEntitiesPath = CMS_FOLDER . 'modules' . DIRECTORY_SEPARATOR . 'admin' . DIRECTORY_SEPARATOR . 'form' . DIRECTORY_SEPARATOR . 'entity';
25+
26+
$metaGenerator = new MetaGenerator($phpStormMetaFilePath);
27+
$metaGenerator->addNamespace(new EntitiesNamespace($entitiesPath)) // Добавляем пространство имён ORM-сущностей
28+
->addNamespace(new AdminEntitiesNamespace($adminEntitiesPath)) // Добавляем пространство имён сущностей панели администратора
29+
->scan() // Сканируем добавленные пространства имён
30+
->printFile(); // Пишем сгенерированные мета-данные в файл
31+
```

composer.json

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
{
2+
"name": "met_mw/phpstormmetagenerator",
3+
"type": "library",
4+
"keywords": ["phpStorm", "HostCMS", "metagenerator", "meta", "generator", ".phpstorm.meta.php"],
5+
"license": "MIT",
6+
"authors": [
7+
{
8+
"name": "met-mw",
9+
"email": "[email protected]"
10+
}
11+
],
12+
"repositories": [],
13+
"require": {},
14+
"require-dev": {
15+
"phpunit/phpunit": "^5.4",
16+
"satooshi/php-coveralls": "dev-master"
17+
},
18+
"autoload": {
19+
"psr-4": {
20+
"PhpStormMetaGenerator\\": "src/PhpStormMetaGenerator"
21+
}
22+
}
23+
}

phpunit.xml

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<phpunit backupGlobals="false"
3+
backupStaticAttributes="false"
4+
bootstrap="vendor/autoload.php"
5+
colors="true"
6+
convertErrorsToExceptions="true"
7+
convertNoticesToExceptions="true"
8+
convertWarningsToExceptions="true"
9+
processIsolation="false"
10+
stopOnFailure="false"
11+
syntaxCheck="false"
12+
>
13+
<testsuites>
14+
<testsuite name="Package Test Suite">
15+
<directory suffix=".php">./tests/</directory>
16+
</testsuite>
17+
</testsuites>
18+
<filter>
19+
<whitelist>
20+
<directory>src</directory>
21+
</whitelist>
22+
</filter>
23+
</phpunit>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
<?php
2+
namespace PhpStormMetaGenerator\Classes;
3+
4+
5+
use InvalidArgumentException;
6+
use PhpStormMetaGenerator\Interfaces\InterfaceNamespace;
7+
8+
abstract class AbstractNamespace implements InterfaceNamespace
9+
{
10+
11+
/** @var string */
12+
protected $root = '';
13+
14+
/**
15+
* AbstractNamespace constructor.
16+
* @param string $root
17+
*/
18+
public function __construct($root)
19+
{
20+
$this->setRoot($root);
21+
}
22+
23+
/**
24+
* Получить разметку классов пространства имён в виде строки
25+
*
26+
* @return string
27+
*/
28+
public function get()
29+
{
30+
ob_start();
31+
$this->render();
32+
$content = ob_get_contents();
33+
ob_end_clean();
34+
35+
return $content;
36+
}
37+
38+
/**
39+
* Получить путь к корневой директории пространства имён
40+
*
41+
* @return string
42+
*/
43+
public function getRoot()
44+
{
45+
return $this->root;
46+
}
47+
48+
/**
49+
* Установить путь к корневой директории пространства имён
50+
*
51+
* @param string $root
52+
* @return $this
53+
*/
54+
public function setRoot($root)
55+
{
56+
if (!is_string($root)) {
57+
throw new InvalidArgumentException('Путь к корневой директории пространства имён должен быть строкой.');
58+
}
59+
60+
if (!is_dir($root)) {
61+
throw new InvalidArgumentException('Путь должен указывать на директорию.');
62+
}
63+
64+
$this->root = rtrim($root, DIRECTORY_SEPARATOR);
65+
return $this;
66+
}
67+
68+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
<?php
2+
namespace PhpStormMetaGenerator\Classes\HostCMS;
3+
4+
5+
use PhpStormMetaGenerator\Classes\AbstractNamespace;
6+
use PhpStormMetaGenerator\Interfaces\InterfaceNamespace;
7+
8+
class AdminEntitiesNamespace extends AbstractNamespace implements InterfaceNamespace
9+
{
10+
11+
const PREFIX = 'Admin_Form_Entity_';
12+
13+
/** @var string[] */
14+
protected $classes = [];
15+
16+
/**
17+
* Получить все найнеднные классы в заданном пространстве имён
18+
*
19+
* @return string[]
20+
*/
21+
public function getClasses()
22+
{
23+
return $this->classes;
24+
}
25+
26+
/**
27+
* Сканировать заданную директорию на предмет удовлетворябщих шаблону файлов
28+
*
29+
* @param string|null $directoryPath Путь к сканируемой директории
30+
* @return $this
31+
*/
32+
public function scan($directoryPath = null)
33+
{
34+
$scannedElements = scandir(is_null($directoryPath) ? $this->getRoot() : $directoryPath);
35+
$scannedElements = array_diff($scannedElements, ['.', '..']);
36+
foreach ($scannedElements as $element) {
37+
$currentElementPath = $directoryPath . DIRECTORY_SEPARATOR . $element;
38+
if (is_dir($currentElementPath)) {
39+
$this->scan($currentElementPath);
40+
continue;
41+
}
42+
43+
$this->classes[] = self::PREFIX . ucfirst(substr($element, 0, strlen($element) - strlen('.php')));
44+
}
45+
46+
return $this;
47+
}
48+
49+
/**
50+
* Вывести разметку классов пространства имён
51+
*
52+
* @return void
53+
*/
54+
public function render()
55+
{
56+
echo ' \Admin_Form_Entity::factory(\'\') => array(', PHP_EOL;
57+
foreach ($this->getClasses() as $class) {
58+
echo ' \'', substr($class, strlen(self::PREFIX)), '\' instanceof \\', $class, ',', PHP_EOL;
59+
}
60+
echo ' ),' . PHP_EOL;
61+
}
62+
63+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
<?php
2+
namespace PhpStormMetaGenerator\Classes\HostCMS;
3+
4+
5+
use InvalidArgumentException;
6+
use PhpStormMetaGenerator\Classes\AbstractNamespace;
7+
use PhpStormMetaGenerator\Interfaces\InterfaceNamespace;
8+
9+
class EntitiesNamespace extends AbstractNamespace implements InterfaceNamespace
10+
{
11+
12+
const SEARCH_FILE_NAME = 'model.php';
13+
14+
/** @var string[] */
15+
protected $classes = [];
16+
17+
protected function calcClassNameByFilePath($path)
18+
{
19+
if (!file_exists($path) || !is_file($path)) {
20+
throw new InvalidArgumentException('Должен быть указан путь к файлу.');
21+
}
22+
23+
$classNameFragments = ['Model'];
24+
$path = substr($path, 0, strlen($path) - strlen(DIRECTORY_SEPARATOR . self::SEARCH_FILE_NAME));
25+
while ($this->getRoot() != $path) {
26+
$fragment = basename($path);
27+
$path = substr($path, 0, strlen($path) - strlen(DIRECTORY_SEPARATOR . $fragment));
28+
$classNameFragments[] = ucfirst($fragment);
29+
}
30+
31+
return implode('_', array_reverse($classNameFragments));
32+
}
33+
34+
/**
35+
* Получить все найнеднные классы в заданном пространстве имён
36+
*
37+
* @return string[]
38+
*/
39+
public function getClasses()
40+
{
41+
return $this->classes;
42+
}
43+
44+
/**
45+
* Сканировать заданную директорию на предмет удовлетворябщих шаблону файлов
46+
*
47+
* @param string|null $directoryPath Путь к сканируемой директории
48+
* @return $this
49+
*/
50+
public function scan($directoryPath = null)
51+
{
52+
$directoryPath = is_null($directoryPath) ? $this->getRoot() : $directoryPath;
53+
$scannedElements = scandir($directoryPath);
54+
$scannedElements = array_diff($scannedElements, ['.', '..']);
55+
foreach ($scannedElements as $element) {
56+
$currentElementPath = $directoryPath . DIRECTORY_SEPARATOR . $element;
57+
if (is_dir($currentElementPath)) {
58+
$this->scan($currentElementPath);
59+
continue;
60+
} elseif ($element != self::SEARCH_FILE_NAME) {
61+
continue;
62+
}
63+
64+
$this->classes[] = $this->calcClassNameByFilePath($currentElementPath);
65+
}
66+
67+
return $this;
68+
}
69+
70+
/**
71+
* Вывести разметку классов пространства имён
72+
*
73+
* @return void
74+
*/
75+
public function render()
76+
{
77+
echo ' \\Core_ORM::factory(\'\') => array(', PHP_EOL;
78+
foreach ($this->getClasses() as $class) {
79+
echo ' \'', substr($class, 0, strlen($class) - strlen('_Model')), '\' instanceof \\', $class, ',', PHP_EOL;
80+
}
81+
echo ' ),' . PHP_EOL;
82+
}
83+
84+
}

0 commit comments

Comments
 (0)