Skip to content

Instantly share code, notes, and snippets.

@mvriel
Created January 1, 2012 21:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvriel/1548455 to your computer and use it in GitHub Desktop.
Save mvriel/1548455 to your computer and use it in GitHub Desktop.
Extract dependency namespaces from DocBlox structure file and attempt to generate composer.json requires
<?php
if ($argc < 2) {
throw new Exception('Must provide location of DocBlox structure.xml file as argument');
}
$structure_file = $argv[1];
$packages = array();
$packagist = json_decode(file_get_contents('http://packagist.org/packages.json'));
foreach($packagist as $package_obj) {
$packages[] = strtolower(str_replace('/', '\\', $package_obj->name));
}
$dom = new DOMDocument('1.0', 'utf-8');
$dom->formatOutput = true;
$dom->loadXML(file_get_contents($structure_file));
$xpath = new DOMXPath($dom);
$qry = $xpath->query('//@namespace');
$own = array();
foreach($qry as $item) {
if ($item->nodeValue == 'default') continue;
$own['\\'.(string)$item->nodeValue] = true;
}
$own = array_keys($own);
$qry = $xpath->query('//type');
$result = array();
foreach($qry as $item) {
if (isset($item->nodeValue[0]) && $item->nodeValue[0] == '\\') {
foreach($own as $own_space) {
// if this namespace starts with a namespace defined in this project; it is not a dependency
if (strpos((string)$item->nodeValue, $own_space) === 0) continue 2;
}
// filter all namespaces with less than 2 parts
if (substr_count($item->nodeValue, '\\') < 2) continue;
$result[(string)$item->nodeValue] = true;
}
}
$found = array_keys($result);
echo '=========== Packagist ============'.PHP_EOL;
var_export($packages);
echo PHP_EOL.PHP_EOL;
echo '=========== Own namespaces ============'.PHP_EOL;
var_export($own);
echo PHP_EOL.PHP_EOL;
echo '=========== Found dependency namespaces ============'.PHP_EOL;
var_export($found);
echo PHP_EOL.PHP_EOL;
// strip all but the first two namespace parts
// safe to assume there is never a namespace with less than 2 parts; we filter those
foreach($found as &$item) {
// lowercase for ease of comparison
$item = strtolower($item);
}
array_unique($found);
$composer = new stdClass();
$composer->require = new stdClass();
foreach($found as $found_space) {
if (in_array($found_space, $packages)) {
$name = str_replace('\\', '/', $found_space);
$composer->require->$name = '*';
}
}
var_export(json_encode($composer));
@mvriel
Copy link
Author

mvriel commented Jan 1, 2012

Warning to the reader: this code is not optimized or written with reusability in mind. It is adviced to refactor the code before use as it is not nice to look at.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment