Skip to content

Commit

Permalink
v1.1.0
Browse files Browse the repository at this point in the history
* Add new 'Packages' class
* Add methods regarding licenses
* Remove code about repo being forked
* Update README & test suite
  • Loading branch information
S1SYPHOS authored Jul 11, 2021
1 parent 5d3fd0f commit de5906f
Show file tree
Hide file tree
Showing 12 changed files with 478 additions and 272 deletions.
53 changes: 33 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,10 @@ $cacheSettings = ['storage' => '/path/to/cache']; # Optional: Cache settings, s
**Note:**
For available cache drivers & settings, see [here](https://github.com/terrylinooo/simple-cache)!

Passing these options to `Thx::giveBack()` creates an instance:
Passing these options to `new Thx()` creates an instance:

```php
$obj = Thx::giveBack($pkgFile, $lockFile, $cacheDriver, $cacheSettings);
$obj = new Thx($pkgFile, $lockFile, $cacheDriver, $cacheSettings);
```

.. which you may configure to your liking by using:
Expand All @@ -56,36 +56,40 @@ $obj->setCacheDuration(7); # Cache results for one week
$obj->setBlockList(['php', 'some/library']); # Block from being processed
```

After setting everything up, `spreadLove()` makes some API calls:
After setting everything up, `giveBack()` makes some API calls & returns processed data, wrapped by a `Packages` object:

- Composer packages @ https://repo.packagist.org
- Node packages @ https://api.npms.io

```php
$obj->spreadLove();
$processed = $obj->giveBack();
```

Currently there are three methods you can use:
At this point, there are three basic methods you can use:

- `data()` returns raw data from lockfile for all used packages
- `pkgs()` returns processed data for all used packages
- `packages()` returns the names of all used packages

```php
# Alternative 1:
# Dump raw data
$raw = $obj->data();

# Process data
$obj->spreadLove();
$processed = $obj->giveBack();

# Work with it
$raw = $obj->data();
$processed = $obj->pkgs();
$pkgData = $processed->pkgs();
```

For convenience, there are methods to

# Alternative 2:
# Since `spreadLove` allows chaining, you could also do it like this:
$obj->spreadLove()->data();
- list licenses & number of occurences: `licenses()`
- group packages by license: `byLicense()`

# The second call provides cached data, no performance penalty there
$obj->spreadLove()->pkgs();
```php
$licenseData = $processed->licenses();
$groupedByLicense = $processed->byLicense();
```


Expand All @@ -104,13 +108,19 @@ $pkgFile = 'path/to/composer.json'; # or 'package.json' for NPM / Yarn
$lockFile = 'path/to/composer.lock' # or 'package-lock.json' for NPM / 'yarn.lock' for Yarn

try {
$obj = Thx::giveBack($pkgFile, $lockFile)->spreadLove();

# Dump package names
var_dump($obj->packages())
$obj = new Thx($pkgFile, $lockFile);

# Dump (raw) data extracted from lockfiles
var_dump($obj->data())
var_dump($obj->data());

# Process data
$processed = $obj->giveBack();

# Dump package data
var_dump($processed->pkgs())

# Dump package names
var_dump($processed->packages())

} catch (Exception $e) {
# No dependencies found, file not found, ..
Expand All @@ -125,7 +135,10 @@ try {
- [x] Parse yarn v1 lockfiles
- [x] Gather information using public APIs
- [x] Custom `Exception`s
- [ ] Provide more methods
- [x] Move data manipulation to uniform `Packages` class
- [ ] Provide more (sorting/filtering) methods, eg ..
- [x] .. `byLicense()` = 'MIT' => [...], 'GPL v3' => [...] etc
- .. `byDownloads()` = '2k' => [...], '1k' => [...] etc


## Credits
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"description": "Acknowledge the people behind your frontend dependencies - and give thanks!",
"type": "library",
"license": "MIT",
"version": "1.0.0",
"version": "1.1.0",
"keywords": ["gratitude", "appreciation", "gratefulness", "thankfulness"],
"homepage": "https://github.com/S1SYPHOS",
"scripts": {
Expand Down
98 changes: 24 additions & 74 deletions lib/Driver.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
namespace S1SYPHOS;


use S1SYPHOS\Traits\Caching;
use S1SYPHOS\Traits\Helpers;
use S1SYPHOS\Traits\Remote;


abstract class Driver
Expand All @@ -14,9 +12,7 @@ abstract class Driver
* Traits
*/

use Caching;
use Helpers;
use Remote;


/**
Expand All @@ -31,14 +27,6 @@ abstract class Driver
public $data = null;


/**
* Processed data
*
* @var array
*/
public $pkgs = null;


/**
* Operating mode identifier
*
Expand All @@ -47,14 +35,6 @@ abstract class Driver
public $mode;


/**
* List of packages not to be processed
*
* @var array
*/
public $blockList = [];


/**
* Constructor
*
Expand All @@ -64,80 +44,48 @@ abstract class Driver
* @param array $cacheSettings Cache settings
* @return void
*/
public function __construct(array $pkgData, string $lockFile, string $cacheDriver, array $cacheSettings)
public function __construct(array $pkgData, string $lockFile)
{
# Create cache instance
$this->createCache($cacheDriver, $cacheSettings);

# Extract raw data
$this->data = $this->extract($pkgData, $lockFile);
}


/**
* Setters & getters
*/

public function setBlockList(int $blockList): void
{
$this->blockList = $blockList;
}


public function getBlockList(): array
{
return $this->blockList;
}


/**
* Shared methods
*/

/**
* Spreads love
*
* @return \S1SYPHOS\Driver
* @param \Shieldon\SimpleCache\Cache $cache Cache object
* @param array $config Configuration options
* @return \S1SYPHOS\Packaging\Packages Processed data
*/
public function spreadLove(): \S1SYPHOS\Driver
public function spreadLove(\Shieldon\SimpleCache\Cache $cache, array $config): \S1SYPHOS\Packaging\Packages
{
# Process raw data
$this->pkgs = $this->process();

# Enable chaining
return $this;
return $this->process($cache, $config);
}


/**
* Exports raw package data
*
* @return array Raw package data
*/
public function data(): array
protected function fetchRemote(string $apiURL, int $timeout = 3, string $userAgent = ''): string
{
return $this->data;
}
# Initialize HTTP client
$client = new \GuzzleHttp\Client(['timeout' => $timeout]);

try {
$response = $client->get($apiURL, ['headers' => ['User-Agent' => $userAgent]]);
} catch (\GuzzleHttp\Exception\TransferException $e) {
return '';
}

/**
* Exports processed package data
*
* @return array Processed package data
*/
public function pkgs(): array
{
return $this->pkgs;
}
if ($response->getStatusCode() === 200) {
return $response->getBody();
}


/**
* Exports package names
*
* @return array Package names
*/
public function packages(): array {
return $this->pluck($this->pkgs, 'name');
# (3) .. otherwise, transmission *may* have worked
return '';
}


Expand All @@ -150,15 +98,17 @@ public function packages(): array {
*
* @param string $dataFile Path to data file
* @param string $lockFile Lockfile contents
* @return array
* @return array Extracted data
*/
abstract protected function extract(array $pkgData, string $lockFile): array;


/**
* Processes raw data
*
* @return array Processed data
* @param \Shieldon\SimpleCache\Cache $cache Cache object
* @param array $config Configuration options
* @return \S1SYPHOS\Packaging\Packages Processed data
*/
abstract protected function process(): array;
abstract protected function process(\Shieldon\SimpleCache\Cache $cache, array $config): \S1SYPHOS\Packaging\Packages;
}
45 changes: 21 additions & 24 deletions lib/Drivers/Composer.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

namespace S1SYPHOS\Drivers;


use S1SYPHOS\Driver;
use S1SYPHOS\Packaging\Packages;


class Composer extends Driver
Expand All @@ -20,16 +20,6 @@ class Composer extends Driver
public $mode = 'php';


/**
* List of packages not to be processed
*
* @var array
*/
public $blockList = [
'php',
];


/**
* Methods
*/
Expand All @@ -45,50 +35,55 @@ protected function extract(array $pkgData, string $lockFile): array
{
$lockData = json_decode($lockFile, true);

$phpData = [];
$data = [];

foreach ($lockData['packages'] as $pkg) {
if (in_array($pkg['name'], array_keys($pkgData['require'])) === true) {
$phpData[$pkg['name']] = $pkg;
$data[$pkg['name']] = $pkg;
}
}

return $phpData;
return $data;
}


/**
* Processes raw data
*
* @return array Processed data
* @param \Shieldon\SimpleCache\Cache $cache Cache object
* @param array $config Configuration options
* @return \S1SYPHOS\Packaging\Packages Processed data
*/
protected function process(): array
protected function process(\Shieldon\SimpleCache\Cache $cache, array $config): \S1SYPHOS\Packaging\Packages
{
return array_map(function($pkgName, $pkg) {
$pkgs = array_map(function($pkgName, $pkg) use ($cache, $config) {
$data = [];

# Build unique caching key
$hash = md5($pkgName);

# Determine whether data was stored in cache
$fromCache = false;

# Fetch information about package ..
if ($this->cache->has($hash)) {
if ($cache->has($hash)) {
# (1) .. from cache (if available)
$data = $this->cache->get($hash);

$this->fromCache = true;
$data = $cache->get($hash);
$fromCache = true;
}

if (empty($data)) {
# (2) .. from API
# Block unwanted libraries
if (in_array($pkgName, $this->blockList) === true) return false;
if (in_array($pkgName, $config['blockList']) === true) return false;

# Prepare data for each repository
$data['name'] = $pkgName;
$data['version'] = str_replace('v', '', strtolower($pkg['version']));

# Fetch additional information from https://packagist.org
$response = $this->fetchRemote('https://repo.packagist.org/p/' . $pkgName . '.json');
$apiURL = 'https://repo.packagist.org/p/' . $pkgName . '.json';
$response = $this->fetchRemote($apiURL, $config['timeout'], $config['userAgent']);
$response = json_decode($response, true)['packages'][$pkgName];

# Enrich data with results
Expand All @@ -97,10 +92,12 @@ protected function process(): array
$data['url'] = static::rtrim($response[$pkg['version']]['source']['url'], '.git');

# Cache result
$this->cache->set($hash, $data, $this->days2seconds($this->cacheDuration));
$cache->set($hash, $data, $this->days2seconds($config['cacheDuration']));
}

return $data;
}, array_keys($this->data), $this->data);

return new Packages($pkgs);
}
}
Loading

0 comments on commit de5906f

Please sign in to comment.