create-single-file.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. #!/usr/bin/env php
  2. <?php
  3. /*
  4. * This file is part of the Predis package.
  5. *
  6. * (c) Daniele Alessandri <suppakilla@gmail.com>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. // -------------------------------------------------------------------------- //
  12. // This script can be used to automatically glue all the .php files of Predis
  13. // into a single monolithic script file that can be used without an autoloader,
  14. // just like the other previous versions of the library.
  15. //
  16. // Much of its complexity is due to the fact that we cannot simply join PHP
  17. // files, but namespaces and classes definitions must follow a precise order
  18. // when dealing with subclassing and inheritance.
  19. //
  20. // The current implementation is pretty naïve, but it should do for now.
  21. // -------------------------------------------------------------------------- //
  22. class CommandLine
  23. {
  24. public static function getOptions()
  25. {
  26. $parameters = array(
  27. 's:' => 'source:',
  28. 'o:' => 'output:',
  29. 'e:' => 'exclude:',
  30. 'E:' => 'exclude-classes:',
  31. );
  32. $getops = getopt(implode(array_keys($parameters)), $parameters);
  33. $options = array(
  34. 'source' => __DIR__ . "/../lib/",
  35. 'output' => PredisFile::NS_ROOT . '.php',
  36. 'exclude' => array(),
  37. );
  38. foreach ($getops as $option => $value) {
  39. switch ($option) {
  40. case 's':
  41. case 'source':
  42. $options['source'] = $value;
  43. break;
  44. case 'o':
  45. case 'output':
  46. $options['output'] = $value;
  47. break;
  48. case 'E':
  49. case 'exclude-classes':
  50. $options['exclude'] = @file($value, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: $value;
  51. break;
  52. case 'e':
  53. case 'exclude':
  54. $options['exclude'] = is_array($value) ? $value : array($value);
  55. break;
  56. }
  57. }
  58. return $options;
  59. }
  60. }
  61. class PredisFile
  62. {
  63. const NS_ROOT = 'Predis';
  64. private $namespaces;
  65. public function __construct()
  66. {
  67. $this->namespaces = array();
  68. }
  69. public static function from($libraryPath, Array $exclude = array())
  70. {
  71. $nsroot = self::NS_ROOT;
  72. $predisFile = new PredisFile();
  73. $libIterator = new RecursiveDirectoryIterator("$libraryPath$nsroot");
  74. foreach (new RecursiveIteratorIterator($libIterator) as $classFile)
  75. {
  76. if (!$classFile->isFile()) {
  77. continue;
  78. }
  79. $namespace = strtr(str_replace($libraryPath, '', $classFile->getPath()), '/', '\\');
  80. if (in_array(sprintf('%s\\%s', $namespace, $classFile->getBasename('.php')), $exclude)) {
  81. continue;
  82. }
  83. $phpNamespace = $predisFile->getNamespace($namespace);
  84. if ($phpNamespace === false) {
  85. $phpNamespace = new PhpNamespace($namespace);
  86. $predisFile->addNamespace($phpNamespace);
  87. }
  88. $phpClass = new PhpClass($phpNamespace, $classFile);
  89. }
  90. return $predisFile;
  91. }
  92. public function addNamespace(PhpNamespace $namespace)
  93. {
  94. if (isset($this->namespaces[(string)$namespace])) {
  95. throw new InvalidArgumentException("Duplicated namespace");
  96. }
  97. $this->namespaces[(string)$namespace] = $namespace;
  98. }
  99. public function getNamespaces()
  100. {
  101. return $this->namespaces;
  102. }
  103. public function getNamespace($namespace)
  104. {
  105. if (!isset($this->namespaces[$namespace])) {
  106. return false;
  107. }
  108. return $this->namespaces[$namespace];
  109. }
  110. public function getClassByFQN($classFqn)
  111. {
  112. if (($nsLastPos = strrpos($classFqn, '\\')) !== false) {
  113. $namespace = $this->getNamespace(substr($classFqn, 0, $nsLastPos));
  114. if ($namespace === false) {
  115. return null;
  116. }
  117. $className = substr($classFqn, $nsLastPos + 1);
  118. return $namespace->getClass($className);
  119. }
  120. return null;
  121. }
  122. private function calculateDependencyScores(&$classes, $fqn)
  123. {
  124. if (!isset($classes[$fqn])) {
  125. $classes[$fqn] = 0;
  126. }
  127. $classes[$fqn] += 1;
  128. if (($phpClass = $this->getClassByFQN($fqn)) === null) {
  129. throw new RuntimeException(
  130. "Cannot found the class $fqn which is required by other subclasses. Are you missing a file?"
  131. );
  132. }
  133. foreach ($phpClass->getDependencies() as $fqn) {
  134. $this->calculateDependencyScores($classes, $fqn);
  135. }
  136. }
  137. private function getDependencyScores()
  138. {
  139. $classes = array();
  140. foreach ($this->getNamespaces() as $phpNamespace) {
  141. foreach ($phpNamespace->getClasses() as $phpClass) {
  142. $this->calculateDependencyScores($classes, $phpClass->getFQN());
  143. }
  144. }
  145. return $classes;
  146. }
  147. private function getOrderedNamespaces($dependencyScores)
  148. {
  149. $namespaces = array_fill_keys(array_unique(
  150. array_map(
  151. function ($fqn) { return PhpNamespace::extractName($fqn); },
  152. array_keys($dependencyScores)
  153. )
  154. ), 0);
  155. foreach ($dependencyScores as $classFqn => $score) {
  156. $namespaces[PhpNamespace::extractName($classFqn)] += $score;
  157. }
  158. arsort($namespaces);
  159. return array_keys($namespaces);
  160. }
  161. private function getOrderedClasses(PhpNamespace $phpNamespace, $classes)
  162. {
  163. $nsClassesFQNs = array_map(function ($cl) { return $cl->getFQN(); }, $phpNamespace->getClasses());
  164. $nsOrderedClasses = array();
  165. foreach ($nsClassesFQNs as $nsClassFQN) {
  166. $nsOrderedClasses[$nsClassFQN] = $classes[$nsClassFQN];
  167. }
  168. arsort($nsOrderedClasses);
  169. return array_keys($nsOrderedClasses);
  170. }
  171. public function getPhpCode()
  172. {
  173. $buffer = array("<?php\n\n", PhpClass::LICENSE_HEADER, "\n\n");
  174. $classes = $this->getDependencyScores();
  175. $namespaces = $this->getOrderedNamespaces($classes);
  176. foreach ($namespaces as $namespace) {
  177. $phpNamespace = $this->getNamespace($namespace);
  178. // generate namespace directive
  179. $buffer[] = $phpNamespace->getPhpCode();
  180. $buffer[] = "\n";
  181. // generate use directives
  182. $useDirectives = $phpNamespace->getUseDirectives();
  183. if (count($useDirectives) > 0) {
  184. $buffer[] = $useDirectives->getPhpCode();
  185. $buffer[] = "\n";
  186. }
  187. // generate classes bodies
  188. $nsClasses = $this->getOrderedClasses($phpNamespace, $classes);
  189. foreach ($nsClasses as $classFQN) {
  190. $buffer[] = $this->getClassByFQN($classFQN)->getPhpCode();
  191. $buffer[] = "\n\n";
  192. }
  193. $buffer[] = "/* " . str_repeat("-", 75) . " */";
  194. $buffer[] = "\n\n";
  195. }
  196. return implode($buffer);
  197. }
  198. public function saveTo($outputFile)
  199. {
  200. // TODO: add more sanity checks
  201. if ($outputFile === null || $outputFile === '') {
  202. throw new InvalidArgumentException('You must specify a valid output file');
  203. }
  204. file_put_contents($outputFile, $this->getPhpCode());
  205. }
  206. }
  207. class PhpNamespace implements IteratorAggregate
  208. {
  209. private $namespace;
  210. private $classes;
  211. public function __construct($namespace)
  212. {
  213. $this->namespace = $namespace;
  214. $this->classes = array();
  215. $this->useDirectives = new PhpUseDirectives($this);
  216. }
  217. public static function extractName($fqn)
  218. {
  219. $nsSepLast = strrpos($fqn, '\\');
  220. if ($nsSepLast === false) {
  221. return $fqn;
  222. }
  223. $ns = substr($fqn, 0, $nsSepLast);
  224. return $ns !== '' ? $ns : null;
  225. }
  226. public function addClass(PhpClass $class)
  227. {
  228. $this->classes[$class->getName()] = $class;
  229. }
  230. public function getClass($className)
  231. {
  232. if (isset($this->classes[$className])) {
  233. return $this->classes[$className];
  234. }
  235. }
  236. public function getClasses()
  237. {
  238. return array_values($this->classes);
  239. }
  240. public function getIterator()
  241. {
  242. return new \ArrayIterator($this->getClasses());
  243. }
  244. public function getUseDirectives()
  245. {
  246. return $this->useDirectives;
  247. }
  248. public function getPhpCode()
  249. {
  250. return "namespace $this->namespace;\n";
  251. }
  252. public function __toString()
  253. {
  254. return $this->namespace;
  255. }
  256. }
  257. class PhpUseDirectives implements Countable, IteratorAggregate
  258. {
  259. private $use;
  260. private $aliases;
  261. private $namespace;
  262. public function __construct(PhpNamespace $namespace)
  263. {
  264. $this->use = array();
  265. $this->aliases = array();
  266. $this->namespace = $namespace;
  267. }
  268. public function add($use, $as = null)
  269. {
  270. if (in_array($use, $this->use)) {
  271. return;
  272. }
  273. $this->use[] = $use;
  274. $this->aliases[$as ?: PhpClass::extractName($use)] = $use;
  275. }
  276. public function getList()
  277. {
  278. return $this->use;
  279. }
  280. public function getIterator()
  281. {
  282. return new \ArrayIterator($this->getList());
  283. }
  284. public function getPhpCode()
  285. {
  286. $reducer = function ($str, $use) {
  287. return $str .= "use $use;\n";
  288. };
  289. return array_reduce($this->getList(), $reducer, '');
  290. }
  291. public function getNamespace()
  292. {
  293. return $this->namespace;
  294. }
  295. public function getFQN($className)
  296. {
  297. if (($nsSepFirst = strpos($className, '\\')) === false) {
  298. if (isset($this->aliases[$className])) {
  299. return $this->aliases[$className];
  300. }
  301. return (string)$this->getNamespace() . "\\$className";
  302. }
  303. if ($nsSepFirst != 0) {
  304. throw new InvalidArgumentException("Partially qualified names are not supported");
  305. }
  306. return $className;
  307. }
  308. public function count()
  309. {
  310. return count($this->use);
  311. }
  312. }
  313. class PhpClass
  314. {
  315. const LICENSE_HEADER = <<<LICENSE
  316. /*
  317. * This file is part of the Predis package.
  318. *
  319. * (c) Daniele Alessandri <suppakilla@gmail.com>
  320. *
  321. * For the full copyright and license information, please view the LICENSE
  322. * file that was distributed with this source code.
  323. */
  324. LICENSE;
  325. private $namespace;
  326. private $file;
  327. private $body;
  328. private $implements;
  329. private $extends;
  330. private $name;
  331. public function __construct(PhpNamespace $namespace, SplFileInfo $classFile)
  332. {
  333. $this->namespace = $namespace;
  334. $this->file = $classFile;
  335. $this->implements = array();
  336. $this->extends = array();
  337. $this->extractData();
  338. $namespace->addClass($this);
  339. }
  340. public static function extractName($fqn)
  341. {
  342. $nsSepLast = strrpos($fqn, '\\');
  343. if ($nsSepLast === false) {
  344. return $fqn;
  345. }
  346. return substr($fqn, $nsSepLast + 1);
  347. }
  348. private function extractData()
  349. {
  350. $useDirectives = $this->getNamespace()->getUseDirectives();
  351. $useExtractor = function ($m) use ($useDirectives) {
  352. $useDirectives->add(($namespacedPath = $m[1]));
  353. };
  354. $classBuffer = stream_get_contents(fopen($this->getFile()->getPathname(), 'r'));
  355. $classBuffer = str_replace(self::LICENSE_HEADER, '', $classBuffer);
  356. $classBuffer = preg_replace('/<\?php\s?\\n\s?/', '', $classBuffer);
  357. $classBuffer = preg_replace('/\s?\?>\n?/ms', '', $classBuffer);
  358. $classBuffer = preg_replace('/namespace\s+[\w\d_\\\\]+;\s?/', '', $classBuffer);
  359. $classBuffer = preg_replace_callback('/use\s+([\w\d_\\\\]+)(\s+as\s+.*)?;\s?\n?/', $useExtractor, $classBuffer);
  360. $this->body = trim($classBuffer);
  361. $this->extractHierarchy();
  362. }
  363. private function extractHierarchy()
  364. {
  365. $implements = array();
  366. $extends = array();
  367. $extractor = function ($iterator, $callback) {
  368. $className = '';
  369. $iterator->seek($iterator->key() + 1);
  370. while ($iterator->valid()) {
  371. $token = $iterator->current();
  372. if (is_string($token)) {
  373. if (preg_match('/\s?,\s?/', $token)) {
  374. $callback(trim($className));
  375. $className = '';
  376. } else if ($token == '{') {
  377. $callback(trim($className));
  378. return;
  379. }
  380. }
  381. switch ($token[0]) {
  382. case T_NS_SEPARATOR:
  383. $className .= '\\';
  384. break;
  385. case T_STRING:
  386. $className .= $token[1];
  387. break;
  388. case T_IMPLEMENTS:
  389. case T_EXTENDS:
  390. $callback(trim($className));
  391. $iterator->seek($iterator->key() - 1);
  392. return;
  393. }
  394. $iterator->next();
  395. }
  396. };
  397. $tokens = token_get_all("<?php\n" . trim($this->getPhpCode()));
  398. $iterator = new ArrayIterator($tokens);
  399. while ($iterator->valid()) {
  400. $token = $iterator->current();
  401. if (is_string($token)) {
  402. $iterator->next();
  403. continue;
  404. }
  405. switch ($token[0]) {
  406. case T_CLASS:
  407. case T_INTERFACE:
  408. $iterator->seek($iterator->key() + 2);
  409. $tk = $iterator->current();
  410. $this->name = $tk[1];
  411. break;
  412. case T_IMPLEMENTS:
  413. $extractor($iterator, function ($fqn) use (&$implements) {
  414. $implements[] = $fqn;
  415. });
  416. break;
  417. case T_EXTENDS:
  418. $extractor($iterator, function ($fqn) use (&$extends) {
  419. $extends[] = $fqn;
  420. });
  421. break;
  422. }
  423. $iterator->next();
  424. }
  425. $this->implements = $this->guessFQN($implements);
  426. $this->extends = $this->guessFQN($extends);
  427. }
  428. public function guessFQN($classes)
  429. {
  430. $useDirectives = $this->getNamespace()->getUseDirectives();
  431. return array_map(array($useDirectives, 'getFQN'), $classes);
  432. }
  433. public function getImplementedInterfaces($all = false)
  434. {
  435. if ($all) {
  436. return $this->implements;
  437. }
  438. return array_filter(
  439. $this->implements,
  440. function ($cn) { return strpos($cn, 'Predis\\') === 0; }
  441. );
  442. }
  443. public function getExtendedClasses($all = false)
  444. {
  445. if ($all) {
  446. return $this->extemds;
  447. }
  448. return array_filter(
  449. $this->extends,
  450. function ($cn) { return strpos($cn, 'Predis\\') === 0; }
  451. );
  452. }
  453. public function getDependencies($all = false)
  454. {
  455. return array_merge(
  456. $this->getImplementedInterfaces($all),
  457. $this->getExtendedClasses($all)
  458. );
  459. }
  460. public function getNamespace()
  461. {
  462. return $this->namespace;
  463. }
  464. public function getFile()
  465. {
  466. return $this->file;
  467. }
  468. public function getName()
  469. {
  470. return $this->name;
  471. }
  472. public function getFQN()
  473. {
  474. return (string)$this->getNamespace() . '\\' . $this->name;
  475. }
  476. public function getPhpCode()
  477. {
  478. return $this->body;
  479. }
  480. public function __toString()
  481. {
  482. return "class " . $this->getName() . '{ ... }';
  483. }
  484. }
  485. /* -------------------------------------------------------------------------- */
  486. $options = CommandLine::getOptions();
  487. $predisFile = PredisFile::from($options['source'], $options['exclude']);
  488. $predisFile->saveTo($options['output']);