Skip to content

Instantly share code, notes, and snippets.

@drzippie
Created January 20, 2015 15:51
Show Gist options
  • Select an option

  • Save drzippie/30c37456ad1305997186 to your computer and use it in GitHub Desktop.

Select an option

Save drzippie/30c37456ad1305997186 to your computer and use it in GitHub Desktop.
Publisher - Dependence and hierarchy of nodes to publish.php
<?php
$nodes = [
'1' => ['50'],
'2' => ['21','53', '14'],
'21' => ['53', '10', '15'] ,
'10' => ['14', '1'],
'14' => [],
'15' => ['21'],
'53' => [ '14'] ,
];
$publisher = new Publisher( [ 1, 2 , 53 ] , $nodes ) ;
print_R( $nodes ) ;
$publisher->run();
class Publisher {
private $pending = [];
private $sent = [];
private $nodeDependences = [];
public function __construct( Array $nodes , $nodeDependences ) {
$this->pending = $nodes ;
// nodeDependences is a mock to show dependences for this algorithm
$this->nodeDependences = $nodeDependences ;
}
public function run( ) {
while (!empty( $this->pending )) {
$nodeId = array_shift( $this->pending ) ;
if ( $this->hasDependences( $nodeId )) {
continue ;
}
$this->sendToPublish( $nodeId );
}
}
public function hasDependences( $nodeId ) {
// echo "CHECK: NODE: {$nodeId}" . PHP_EOL ;
if (!isset( $this->nodeDependences["$nodeId"] ) || empty($this->nodeDependences["$nodeId"] )) {
return false ;
}
$pending = array_values( array_diff( $this->nodeDependences["$nodeId"], $this->pending, $this->sent ) ) ;
if ( empty( $pending )) {
return false ;
} else {
$this->pending =array_merge( [ $pending[0] , $nodeId ] , $this->pending ) ;
return true ;
}
}
public function sendToPublish( $nodeId) {
echo "\t >> Publish: NODE: {$nodeId}" . PHP_EOL ;
$this->sent[] = $nodeId ;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment