create-single-file 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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 $reverseAliases;
  262. private $namespace;
  263. public function __construct(PhpNamespace $namespace)
  264. {
  265. $this->namespace = $namespace;
  266. $this->use = array();
  267. $this->aliases = array();
  268. $this->reverseAliases = array();
  269. }
  270. public function add($use, $as = null)
  271. {
  272. if (in_array($use, $this->use)) {
  273. return;
  274. }
  275. $rename = null;
  276. $this->use[] = $use;
  277. $aliasedClassName = $as ?: PhpClass::extractName($use);
  278. if (isset($this->aliases[$aliasedClassName])) {
  279. $parentNs = $this->getParentNamespace();
  280. if ($parentNs && false !== $pos = strrpos($parentNs, '\\')) {
  281. $parentNs = substr($parentNs, $pos);
  282. }
  283. $newAlias = "{$parentNs}_{$aliasedClassName}";
  284. $rename = (object) array(
  285. 'namespace' => $this->namespace,
  286. 'from' => $aliasedClassName,
  287. 'to' => $newAlias,
  288. );
  289. $this->aliases[$newAlias] = $use;
  290. $as = $newAlias;
  291. } else {
  292. $this->aliases[$aliasedClassName] = $use;
  293. }
  294. if ($as !== null) {
  295. $this->reverseAliases[$use] = $as;
  296. }
  297. return $rename;
  298. }
  299. public function getList()
  300. {
  301. return $this->use;
  302. }
  303. public function getIterator()
  304. {
  305. return new \ArrayIterator($this->getList());
  306. }
  307. public function getPhpCode()
  308. {
  309. $reverseAliases = $this->reverseAliases;
  310. $reducer = function ($str, $use) use ($reverseAliases) {
  311. if (isset($reverseAliases[$use])) {
  312. return $str .= "use $use as {$reverseAliases[$use]};\n";
  313. } else {
  314. return $str .= "use $use;\n";
  315. }
  316. };
  317. return array_reduce($this->getList(), $reducer, '');
  318. }
  319. public function getNamespace()
  320. {
  321. return $this->namespace;
  322. }
  323. public function getParentNamespace()
  324. {
  325. if (false !== $pos = strrpos($this->namespace, '\\')) {
  326. return substr($this->namespace, 0, $pos);
  327. }
  328. return '';
  329. }
  330. public function getFQN($className)
  331. {
  332. if (($nsSepFirst = strpos($className, '\\')) === false) {
  333. if (isset($this->aliases[$className])) {
  334. return $this->aliases[$className];
  335. }
  336. return (string)$this->getNamespace() . "\\$className";
  337. }
  338. if ($nsSepFirst != 0) {
  339. throw new InvalidArgumentException("Partially qualified names are not supported");
  340. }
  341. return $className;
  342. }
  343. public function count()
  344. {
  345. return count($this->use);
  346. }
  347. }
  348. class PhpClass
  349. {
  350. const LICENSE_HEADER = <<<LICENSE
  351. /*
  352. * This file is part of the Predis package.
  353. *
  354. * (c) Daniele Alessandri <suppakilla@gmail.com>
  355. *
  356. * For the full copyright and license information, please view the LICENSE
  357. * file that was distributed with this source code.
  358. */
  359. LICENSE;
  360. private $namespace;
  361. private $file;
  362. private $body;
  363. private $implements;
  364. private $extends;
  365. private $name;
  366. public function __construct(PhpNamespace $namespace, SplFileInfo $classFile)
  367. {
  368. $this->namespace = $namespace;
  369. $this->file = $classFile;
  370. $this->implements = array();
  371. $this->extends = array();
  372. $this->extractData();
  373. $namespace->addClass($this);
  374. }
  375. public static function extractName($fqn)
  376. {
  377. $nsSepLast = strrpos($fqn, '\\');
  378. if ($nsSepLast === false) {
  379. return $fqn;
  380. }
  381. return substr($fqn, $nsSepLast + 1);
  382. }
  383. private function extractData()
  384. {
  385. $renames = array();
  386. $useDirectives = $this->getNamespace()->getUseDirectives();
  387. $useExtractor = function ($m) use ($useDirectives, &$renames) {
  388. array_shift($m);
  389. if (isset($m[1])) {
  390. $m[1] = str_replace(" as ", '', $m[1]);
  391. }
  392. if ($rename = call_user_func_array(array($useDirectives, 'add'), $m)) {
  393. $renames[] = $rename;
  394. }
  395. };
  396. $classBuffer = stream_get_contents(fopen($this->getFile()->getPathname(), 'r'));
  397. $classBuffer = str_replace(self::LICENSE_HEADER, '', $classBuffer);
  398. $classBuffer = preg_replace('/<\?php\s?\\n\s?/', '', $classBuffer);
  399. $classBuffer = preg_replace('/\s?\?>\n?/ms', '', $classBuffer);
  400. $classBuffer = preg_replace('/namespace\s+[\w\d_\\\\]+;\s?/', '', $classBuffer);
  401. $classBuffer = preg_replace_callback('/use\s+([\w\d_\\\\]+)(\s+as\s+.*)?;\s?\n?/', $useExtractor, $classBuffer);
  402. foreach ($renames as $rename) {
  403. $classBuffer = str_replace($rename->from, $rename->to, $classBuffer);
  404. }
  405. $this->body = trim($classBuffer);
  406. $this->extractHierarchy();
  407. }
  408. private function extractHierarchy()
  409. {
  410. $implements = array();
  411. $extends = array();
  412. $extractor = function ($iterator, $callback) {
  413. $className = '';
  414. $iterator->seek($iterator->key() + 1);
  415. while ($iterator->valid()) {
  416. $token = $iterator->current();
  417. if (is_string($token)) {
  418. if (preg_match('/\s?,\s?/', $token)) {
  419. $callback(trim($className));
  420. $className = '';
  421. } else if ($token == '{') {
  422. $callback(trim($className));
  423. return;
  424. }
  425. }
  426. switch ($token[0]) {
  427. case T_NS_SEPARATOR:
  428. $className .= '\\';
  429. break;
  430. case T_STRING:
  431. $className .= $token[1];
  432. break;
  433. case T_IMPLEMENTS:
  434. case T_EXTENDS:
  435. $callback(trim($className));
  436. $iterator->seek($iterator->key() - 1);
  437. return;
  438. }
  439. $iterator->next();
  440. }
  441. };
  442. $tokens = token_get_all("<?php\n" . trim($this->getPhpCode()));
  443. $iterator = new ArrayIterator($tokens);
  444. while ($iterator->valid()) {
  445. $token = $iterator->current();
  446. if (is_string($token)) {
  447. $iterator->next();
  448. continue;
  449. }
  450. switch ($token[0]) {
  451. case T_CLASS:
  452. case T_INTERFACE:
  453. $iterator->seek($iterator->key() + 2);
  454. $tk = $iterator->current();
  455. $this->name = $tk[1];
  456. break;
  457. case T_IMPLEMENTS:
  458. $extractor($iterator, function ($fqn) use (&$implements) {
  459. $implements[] = $fqn;
  460. });
  461. break;
  462. case T_EXTENDS:
  463. $extractor($iterator, function ($fqn) use (&$extends) {
  464. $extends[] = $fqn;
  465. });
  466. break;
  467. }
  468. $iterator->next();
  469. }
  470. $this->implements = $this->guessFQN($implements);
  471. $this->extends = $this->guessFQN($extends);
  472. }
  473. public function guessFQN($classes)
  474. {
  475. $useDirectives = $this->getNamespace()->getUseDirectives();
  476. return array_map(array($useDirectives, 'getFQN'), $classes);
  477. }
  478. public function getImplementedInterfaces($all = false)
  479. {
  480. if ($all) {
  481. return $this->implements;
  482. }
  483. return array_filter(
  484. $this->implements,
  485. function ($cn) { return strpos($cn, 'Predis\\') === 0; }
  486. );
  487. }
  488. public function getExtendedClasses($all = false)
  489. {
  490. if ($all) {
  491. return $this->extemds;
  492. }
  493. return array_filter(
  494. $this->extends,
  495. function ($cn) { return strpos($cn, 'Predis\\') === 0; }
  496. );
  497. }
  498. public function getDependencies($all = false)
  499. {
  500. return array_merge(
  501. $this->getImplementedInterfaces($all),
  502. $this->getExtendedClasses($all)
  503. );
  504. }
  505. public function getNamespace()
  506. {
  507. return $this->namespace;
  508. }
  509. public function getFile()
  510. {
  511. return $this->file;
  512. }
  513. public function getName()
  514. {
  515. return $this->name;
  516. }
  517. public function getFQN()
  518. {
  519. return (string)$this->getNamespace() . '\\' . $this->name;
  520. }
  521. public function getPhpCode()
  522. {
  523. return $this->body;
  524. }
  525. public function __toString()
  526. {
  527. return "class " . $this->getName() . '{ ... }';
  528. }
  529. }
  530. /* -------------------------------------------------------------------------- */
  531. $options = CommandLine::getOptions();
  532. $predisFile = PredisFile::from($options['source'], $options['exclude']);
  533. $predisFile->saveTo($options['output']);