repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/TravelingSalesmanProblem/Bruteforce.php | src/TravelingSalesmanProblem/Bruteforce.php | <?php
namespace Graphp\Algorithms\TravelingSalesmanProblem;
use Graphp\Algorithms\TravelingSalesmanProblem\MinimumSpanningTree as AlgorithmTspMst;
use Graphp\Graph\Edge;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Exception\UnderflowException;
use Graphp\Graph\Graph;
use Graphp\Graph\Set\Edges;
use Graphp\Graph\Vertex;
class Bruteforce extends Base
{
/**
*
* @var Graph
*/
private $graph;
/**
* best weight so for (used for branch-and-bound)
*
* @var number|NULL
*/
private $bestWeight;
/**
* reference to start vertex
*
* @var Vertex
*/
private $startVertex;
/**
* total number of edges needed
*
* @var int
*/
private $numEdges;
/**
* upper limit to use for branch-and-bound (BNB)
*
* @var float|NULL
* @see self::setUpperLimit()
*/
private $upperLimit = NULL;
/**
* whether to use branch-and-bound
*
* simply put, there's no valid reason why anybody would want to turn off this flag
*
* @var bool
*/
private $branchAndBound = true;
/**
*
* @param Graph $graph
*/
public function __construct(Graph $graph)
{
$this->graph = $graph;
}
/**
* explicitly set upper limit to use for branch-and-bound
*
* this method can be used to optimize the algorithm by providing an upper
* bound of when to stop branching any further.
*
* @param float $limit
* @return self $this (chainable)
*/
public function setUpperLimit($limit)
{
$this->upperLimit = $limit;
return $this;
}
/**
* automatically sets upper limit to use for branch-and-bound from the MST heuristic
*
* @return self $this (chainable)
* @uses AlgorithmTspMst
*/
public function setUpperLimitMst()
{
$alg = new AlgorithmTspMst($this->graph);
$this->upperLimit = $alg->getWeight();
return $this;
}
protected function getVertexStart()
{
// actual start doesn't really matter as we're only considering complete graphs here
return $this->graph->getVertices()->getVertexFirst();
}
protected function getGraph()
{
return $this->graph;
}
/**
* get resulting (first) best circle of edges connecting all vertices
*
* @throws \Exception on error
* @return Edges
*/
public function getEdges()
{
$this->numEdges = \count($this->graph->getVertices());
if ($this->numEdges < 3) {
throw new UnderflowException('Needs at least 3 vertices');
}
// numEdges 3-12 should work
$this->bestWeight = $this->upperLimit;
$this->startVertex = $this->getVertexStart();
$result = $this->step($this->startVertex,
0,
array(),
array()
);
if ($result === NULL) {
throw new UnexpectedValueException('No resulting solution for TSP found');
}
return new Edges($result);
}
/**
*
* @param Vertex $vertex current point-of-view
* @param number $totalWeight total weight (so far)
* @param bool[] $visitedVertices
* @param Edge[] $visitedEdges
* @return Edge[]|null
*/
private function step(Vertex $vertex, $totalWeight, array $visitedVertices, array $visitedEdges)
{
// stop recursion if best result is exceeded (branch and bound)
if ($this->branchAndBound && $this->bestWeight !== NULL && $totalWeight >= $this->bestWeight) {
return NULL;
}
// kreis geschlossen am Ende
if ($vertex === $this->startVertex && \count($visitedEdges) === $this->numEdges) {
// new best result
$this->bestWeight = $totalWeight;
return $visitedEdges;
}
// only visit each vertex once
if (isset($visitedVertices[$vertex->getId()])) {
return NULL;
}
$visitedVertices[$vertex->getId()] = true;
$bestResult = NULL;
// weiter verzweigen in alle vertices
foreach ($vertex->getEdgesOut() as $edge) {
// get target vertex of this edge
$target = $edge->getVertexToFrom($vertex);
$weight = $edge->getWeight();
if ($weight < 0) {
throw new UnexpectedValueException('Edge with negative weight "' . $weight . '" not supported');
}
$result = $this->step($target,
$totalWeight + $weight,
$visitedVertices,
\array_merge($visitedEdges, array($edge))
);
// new result found
if ($result !== NULL) {
// branch and bound enabled (default): returned result MUST be the new best result
if($this->branchAndBound ||
// this is the first result, just use it anyway
$bestResult === NULL ||
// this is the new best result
$this->sumEdges($result) < $this->sumEdges($bestResult)){
$bestResult = $result;
}
}
}
return $bestResult;
}
/**
* get sum of weight of given edges
*
* no need to optimize this further, as it's only evaluated if branchAndBound is disabled and
* there's no valid reason why anybody would want to do so.
*
* @param Edge[] $edges
* @return float
*/
private function sumEdges(array $edges)
{
$sum = 0;
foreach ($edges as $edge) {
$sum += $edge->getWeight();
}
return $sum;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/TravelingSalesmanProblem/NearestNeighbor.php | src/TravelingSalesmanProblem/NearestNeighbor.php | <?php
namespace Graphp\Algorithms\TravelingSalesmanProblem;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Set\Edges;
use Graphp\Graph\Vertex;
use SplPriorityQueue;
class NearestNeighbor extends Base
{
/**
* @var Vertex
*/
private $vertex;
public function __construct(Vertex $startVertex)
{
$this->vertex = $startVertex;
}
protected function getVertexStart()
{
return $this->vertex;
}
protected function getGraph()
{
return $this->vertex->getGraph();
}
/**
* @return Edges
*/
public function getEdges()
{
$returnEdges = array();
$n = \count($this->vertex->getGraph()->getVertices());
$vertex = $nextVertex = $this->vertex;
$visitedVertices = array($vertex->getId() => true);
for ($i = 0; $i < $n - 1; ++$i,
// n-1 steps (spanning tree)
$vertex = $nextVertex) {
// get all edges from the aktuel vertex
$edges = $vertex->getEdgesOut();
$sortedEdges = new SplPriorityQueue();
// sort the edges
foreach ($edges as $edge) {
$sortedEdges->insert($edge, - $edge->getWeight());
}
// Untill first is found: get cheepest edge
foreach ($sortedEdges as $edge) {
// Get EndVertex of this edge
$nextVertex = $edge->getVertexToFrom($vertex);
// is unvisited
if (!isset($visitedVertices[$nextVertex->getId()])) {
break;
}
}
// check if there is a way i can use
if (isset($visitedVertices[$nextVertex->getId()])) {
throw new UnexpectedValueException('Graph is not complete - can\'t find an edge to unconnected vertex');
}
$visitedVertices[$nextVertex->getId()] = TRUE;
// clone edge in new Graph
assert(isset($edge));
$returnEdges[] = $edge;
}
// check if there is a way from end edge to start edge
// get first connecting edge
// connect the last vertex with the start vertex
$returnEdges[] = $vertex->getEdgesTo($this->vertex)->getEdgeFirst();
return new Edges($returnEdges);
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/TravelingSalesmanProblem/MinimumSpanningTree.php | src/TravelingSalesmanProblem/MinimumSpanningTree.php | <?php
namespace Graphp\Algorithms\TravelingSalesmanProblem;
use Graphp\Algorithms\MinimumSpanningTree\Kruskal as MstKruskal;
use Graphp\Algorithms\Search\BreadthFirst as SearchDepthFirst;
use Graphp\Graph\Graph;
use Graphp\Graph\Set\Edges;
class MinimumSpanningTree extends Base
{
/**
* @var Graph
*/
private $graph;
public function __construct(Graph $inputGraph)
{
$this->graph = $inputGraph;
}
protected function getVertexStart()
{
return $this->graph->getVertices()->getVertexFirst();
}
protected function getGraph()
{
return $this->graph;
}
/**
* @return Edges
*/
public function getEdges()
{
$returnEdges = array();
// Create minimum spanning tree
$minimumSpanningTreeAlgorithm = new MstKruskal($this->graph);
$minimumSpanningTree = $minimumSpanningTreeAlgorithm->createGraph();
$alg = new SearchDepthFirst($minimumSpanningTree->getVertices()->getVertexFirst());
// Depth first search in minmum spanning tree (for the eulerian path)
$startVertex = NULL;
$oldVertex = NULL;
// connect vertices in order of the depth first search
foreach ($alg->getVertices() as $vertex) {
// get vertex from the original graph (not from the depth first search)
$vertex = $this->graph->getVertex($vertex->getId());
// need to clone the edge from the original graph, therefore i need the original edge
if ($startVertex === NULL) {
$startVertex = $vertex;
} else {
// get edge(s) to clone, multiple edges are possible (returns an array if undirected edge)
assert($oldVertex !== null);
$returnEdges[] = $oldVertex->getEdgesTo($vertex)->getEdgeFirst();
}
$oldVertex = $vertex;
}
// connect last vertex with start vertex
// multiple edges are possible (returns an array if undirected edge)
assert($startVertex !== null && $oldVertex !== null);
$returnEdges[] = $oldVertex->getEdgesTo($startVertex)->getEdgeFirst();
return new Edges($returnEdges);
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/MaximumMatching/Base.php | src/MaximumMatching/Base.php | <?php
namespace Graphp\Algorithms\MaximumMatching;
use Graphp\Algorithms\BaseGraph;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Graph;
use Graphp\Graph\Set\Edges;
abstract class Base extends BaseGraph
{
/**
* Get the count of edges that are in the match
*
* @return int
* @throws UnexpectedValueException if graph is directed or is not bipartit
* @uses Base::getEdges()
*/
public function getNumberOfMatches()
{
return \count($this->getEdges());
}
/**
* create new resulting graph with only edges from maximum matching
*
* @return Graph
* @uses Base::getEdges()
* @uses Graph::createGraphCloneEdges()
*/
public function createGraph()
{
return $this->graph->createGraphCloneEdges($this->getEdges());
}
/**
* create new resulting graph with minimum-cost flow on edges
*
* @return Edges
*/
abstract public function getEdges();
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/MaximumMatching/Flow.php | src/MaximumMatching/Flow.php | <?php
namespace Graphp\Algorithms\MaximumMatching;
use Graphp\Algorithms\Directed;
use Graphp\Algorithms\Groups;
use Graphp\Algorithms\MaxFlow\EdmondsKarp as MaxFlowEdmondsKarp;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Set\Edges;
use Graphp\Graph\Vertex;
class Flow extends Base
{
public function getEdges()
{
$alg = new Directed($this->graph);
if ($alg->hasDirected()) {
throw new UnexpectedValueException('Input graph contains directed edges');
}
$alg = new Groups($this->graph);
if (!$alg->isBipartit()) {
throw new UnexpectedValueException('Input graph does not have bipartit groups assigned to each vertex. Consider Using "AlgorithmBipartit::createGraph()" first');
}
// create temporary flow graph with supersource and supersink
$graphFlow = $this->graph->createGraphCloneEdgeless();
$superSource = $graphFlow->createVertex();
$superSink = $graphFlow->createVertex();
$groups = $alg->getGroups();
$groupA = $groups[0];
// connect supersource s* to set A and supersink t* to set B
foreach ($graphFlow->getVertices() as $vertex) {
assert($vertex instanceof Vertex);
// we want to skip over supersource & supersink as they do not have a partition assigned
if ($vertex === $superSource || $vertex === $superSink) continue;
$group = $vertex->getGroup();
if ($group === $groupA) {
// group A: source
$graphFlow->createEdgeDirected($superSource, $vertex)->setCapacity(1)->setFlow(0);
// temporarily create edges from A->B for flow graph
$originalVertex = $this->graph->getVertex($vertex->getId());
foreach ($originalVertex->getVerticesEdgeTo() as $vertexTarget) {
$graphFlow->createEdgeDirected($vertex, $graphFlow->getVertex($vertexTarget->getId()))->setCapacity(1)->setFlow(0);
}
} else {
// group B: sink
$graphFlow->createEdgeDirected($vertex, $superSink)->setCapacity(1)->setFlow(0);
}
}
// visualize($resultGraph);
// calculate (s*, t*)-flow
$algMaxFlow = new MaxFlowEdmondsKarp($superSource, $superSink);
$resultGraph = $algMaxFlow->createGraph();
// destroy temporary supersource and supersink again
$resultGraph->getVertex($superSink->getId())->destroy();
$resultGraph->getVertex($superSource->getId())->destroy();
$returnEdges = array();
foreach ($resultGraph->getEdges() as $edge) {
// only keep matched edges
if ($edge->getFlow() > 0) {
$originalEdge = $this->graph->getEdgeClone($edge);
$returnEdges[] = $originalEdge;
}
}
return new Edges($returnEdges);
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Tree/Base.php | src/Tree/Base.php | <?php
namespace Graphp\Algorithms\Tree;
use Graphp\Algorithms\BaseGraph;
use Graphp\Algorithms\Degree;
use Graphp\Graph\Graph;
use Graphp\Graph\Set\Vertices;
use Graphp\Graph\Vertex;
/**
* Abstract base class for tree algorithms
*
* This abstract base class provides the base interface for working with
* graphs that represent a tree.
*
* A tree is a connected Graph (single component) with no cycles. Every Tree is
* a Graph, but not every Graph is a Tree. A null Graph (a Graph with no Vertices
* and thus no Edges) is *NOT* considered a valid Tree, as it is not considered
* connected (@see ConnectedComponents and @link)
*
* A
* / \
* B C
* / \
* D E
*
* Special cases are undirected trees (like the one pictured above), handled via
* Tree\Undirected and directed, rooted trees (InTree and OutTree), handled via
* Tree\BaseDirected.
*
* @link http://en.wikipedia.org/wiki/Tree_%28graph_theory%29
* @link http://en.wikipedia.org/wiki/Tree_%28data_structure%29
* @link http://mathoverflow.net/questions/120536/is-the-empty-graph-a-tree
* @see Undirected for an implementation of these algorithms on (undirected) trees
* @see BaseDirected for an abstract implementation of these algorithms on directed, rooted trees
*/
abstract class Base extends BaseGraph
{
/**
* @var Degree
*/
protected $degree;
public function __construct(Graph $graph)
{
parent::__construct($graph);
$this->degree = new Degree($graph);
}
/**
* checks whether the given graph is actually a tree
*
* @return bool
*/
abstract public function isTree();
/**
* checks if the given $vertex is a leaf (outermost vertext)
*
* leaf vertex is also known as leaf node, external node or terminal node
*
* @param Vertex $vertex
* @return bool
*/
abstract public function isVertexLeaf(Vertex $vertex);
/**
* checks if the given $vertex is an internal vertex (somewhere in the "middle" of the tree)
*
* internal vertex is also known as inner node (inode) or branch node
*
* @param Vertex $vertex
* @return bool
*/
abstract public function isVertexInternal(Vertex $vertex);
/**
* get array of leaf vertices (outermost vertices with no children)
*
* @return Vertices
* @uses Graph::getVertices()
* @uses self::isVertexLeaf()
*/
public function getVerticesLeaf()
{
return $this->graph->getVertices()->getVerticesMatch(array($this, 'isVertexLeaf'));
}
/**
* get array of internal vertices
*
* @return Vertices
* @uses Graph::getVertices()
* @uses self::isVertexInternal()
*/
public function getVerticesInternal()
{
return $this->graph->getVertices()->getVerticesMatch(array($this, 'isVertexInternal'));
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Tree/InTree.php | src/Tree/InTree.php | <?php
namespace Graphp\Algorithms\Tree;
use Graphp\Algorithms\Tree\BaseDirected as DirectedTree;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Vertex;
/**
* Alternative InTree implementation where Edges "point towards" root Vertex
*
* ROOT
* ^ ^
* / \
* A B
* ^
* \
* C
*
* @link http://en.wikipedia.org/wiki/Spaghetti_stack
* @see DirectedTree for more information on directed, rooted trees
*/
class InTree extends DirectedTree
{
public function getVerticesChildren(Vertex $vertex)
{
$vertices = $vertex->getVerticesEdgeFrom();
if ($vertices->hasDuplicates()) {
throw new UnexpectedValueException();
}
return $vertices;
}
protected function getVerticesParent(Vertex $vertex)
{
$vertices = $vertex->getVerticesEdgeTo();
if ($vertices->hasDuplicates()) {
throw new UnexpectedValueException();
}
return $vertices;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Tree/OutTree.php | src/Tree/OutTree.php | <?php
namespace Graphp\Algorithms\Tree;
use Graphp\Algorithms\Tree\BaseDirected as DirectedTree;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Vertex;
/**
* Usual OutTree implementation where Edges "point away" from root Vertex
*
* ROOT
* / \
* A <--/ \--> B
* \
* \--> C
*
* also known as arborescence
*
* @link http://en.wikipedia.org/wiki/Arborescence_%28graph_theory%29
* @see DirectedTree for more information on directed, rooted trees
*/
class OutTree extends DirectedTree
{
public function getVerticesChildren(Vertex $vertex)
{
$vertices = $vertex->getVerticesEdgeTo();
if ($vertices->hasDuplicates()) {
throw new UnexpectedValueException();
}
return $vertices;
}
protected function getVerticesParent(Vertex $vertex)
{
$vertices = $vertex->getVerticesEdgeFrom();
if ($vertices->hasDuplicates()) {
throw new UnexpectedValueException();
}
return $vertices;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Tree/Undirected.php | src/Tree/Undirected.php | <?php
namespace Graphp\Algorithms\Tree;
use Graphp\Algorithms\Tree\Base as Tree;
use Graphp\Graph\EdgeUndirected;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Set\Vertices;
use Graphp\Graph\Vertex;
/**
* Undirected tree implementation
*
* An undirected tree is a connected Graph (single component) with no cycles.
* Every undirected Tree is an undirected Graph, but not every undirected Graph
* is an undirected Tree.
*
* A
* / \
* B C
* / \
* D E
*
* Undirected trees do not have special root Vertices (like the above picture
* might suggest). The above tree Graph can also be equivalently be pictured
* like this:
*
* C
* /|\
* / | \
* A D E
* /
* B
*
* If you're looking for a tree with a designated root Vertex, use directed,
* rooted trees (BaseDirected).
*
* @link http://en.wikipedia.org/wiki/Tree_%28graph_theory%29
* @see BaseDirected if you're looking for directed, rooted trees
*/
class Undirected extends Tree
{
/**
* checks if this is a tree
*
* @return bool
* @uses Vertices::isEmpty() to skip null Graphs (a Graph with no Vertices is *NOT* a valid tree)
* @uses Vertices::getVertexFirst() to get get get random "root" Vertex to start search from
* @uses self::getVerticesSubtreeRecursive() to count number of vertices connected to root
*/
public function isTree()
{
if ($this->graph->getVertices()->isEmpty()) {
return false;
}
// every vertex can represent a root vertex, so just pick one
$root = $this->graph->getVertices()->getVertexFirst();
$vertices = array();
try {
$this->getVerticesSubtreeRecursive($root, $vertices, null);
} catch (UnexpectedValueException $e) {
return false;
}
return (\count($vertices) === \count($this->graph->getVertices()));
}
/**
* checks if the given $vertex is a leaf (outermost vertex with exactly one edge)
*
* @param Vertex $vertex
* @return bool
* @uses Degree::getDegreeVertex()
*/
public function isVertexLeaf(Vertex $vertex)
{
return ($this->degree->getDegreeVertex($vertex) === 1);
}
/**
* checks if the given $vertex is an internal vertex (inner vertex with at least 2 edges)
*
* @param Vertex $vertex
* @return bool
* @uses Degree::getDegreeVertex()
*/
public function isVertexInternal(Vertex $vertex)
{
return ($this->degree->getDegreeVertex($vertex) >= 2);
}
/**
* get subtree for given Vertex and ignore path to "parent" ignoreVertex
*
* @param Vertex $vertex
* @param Vertex[] $vertices
* @param Vertex|null $ignore
* @throws UnexpectedValueException for cycles or directed edges (check isTree()!)
* @uses self::getVerticesNeighbor()
* @uses self::getVerticesSubtreeRecursive() to recurse into sub-subtrees
*/
private function getVerticesSubtreeRecursive(Vertex $vertex, array &$vertices, Vertex $ignore = null)
{
if (isset($vertices[$vertex->getId()])) {
// vertex already visited => must be a cycle
throw new UnexpectedValueException('Vertex already visited');
}
$vertices[$vertex->getId()] = $vertex;
foreach ($this->getVerticesNeighbor($vertex) as $vertexNeighboor) {
if ($vertexNeighboor === $ignore) {
// ignore source vertex only once
$ignore = null;
continue;
}
$this->getVerticesSubtreeRecursive($vertexNeighboor, $vertices, $vertex);
}
}
/**
* get neighbor vertices for given start vertex
*
* @param Vertex $vertex
* @return Vertices (might include possible duplicates)
* @throws UnexpectedValueException for directed edges
* @uses Vertex::getEdges()
* @uses Edge::getVertexToFrom()
* @see Vertex::getVerticesEdge()
*/
private function getVerticesNeighbor(Vertex $vertex)
{
$vertices = array();
foreach ($vertex->getEdges() as $edge) {
if (!$edge instanceof EdgeUndirected) {
throw new UnexpectedValueException('Directed edge encountered');
}
$vertices[] = $edge->getVertexToFrom($vertex);
}
return new Vertices($vertices);
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Tree/BaseDirected.php | src/Tree/BaseDirected.php | <?php
namespace Graphp\Algorithms\Tree;
use Graphp\Algorithms\Tree\Base as Tree;
use Graphp\Graph\Exception\UnderflowException;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Set\Vertices;
use Graphp\Graph\Vertex;
/**
* Abstract algorithm base class for working with directed, rooted trees
*
* Directed trees have an designated root Vertex, which is the uppermost Vertex.
* Every other Vertex is either a directed child of this root Vertex or an
* indirect descendant (recursive child).
*
* There are two common implementations of directed trees:
*
* - Usual OutTree implementation where Edges "point away" from root Vertex
*
* ROOT
* / \
* A <--/ \--> B
* \
* \--> C
*
* - Alternative InTree implementation where Edges "point towards" root Vertex
*
* ROOT
* ^ ^
* / \
* A B
* ^
* \
* C
*
* It's your choice on how to direct the edges, but make sure they all point in
* the "same direction", or it will not be a valid tree anymore. However your
* decision may be, in the above example, ROOT is always the root Vertex,
* B is the parent of "C" and A, B are the children of ROOT.
*
* For performance reasons, except for `isTree()`, none of the below methods
* check if the given Graph is actually a valid tree. So make sure to verify
* `isTree()` returns `true` before relying on any of the methods.
*
* @link http://en.wikipedia.org/wiki/Arborescence_%28graph_theory%29
* @link http://en.wikipedia.org/wiki/Spaghetti_stack
* @see OutTree usual implementation where Edges "point away" from root vertex
* @see InTree alternative implementation where Edges "point towards" root vertex
*/
abstract class BaseDirected extends Tree
{
/**
* get root vertex for this in-tree
*
* @return Vertex
* @throws UnderflowException if given graph is empty or no possible root candidate was found (check isTree()!)
* @uses Graph::getVertices() to iterate over each Vertex
* @uses self::isVertexPossibleRoot() to check if any Vertex is a possible root candidate
*/
public function getVertexRoot()
{
foreach ($this->graph->getVertices() as $vertex) {
if ($this->isVertexPossibleRoot($vertex)) {
return $vertex;
}
}
throw new UnderflowException('No possible root found. Either empty graph or no Vertex with proper degree found.');
}
/**
* checks if this is a tree
*
* @return bool
* @uses self::getVertexRoot() to get root Vertex to start search from
* @uses self::getVerticesSubtree() to count number of vertices connected to root
*/
public function isTree()
{
try {
$root = $this->getVertexRoot();
} catch (UnderflowException $e) {
return false;
} catch (UnexpectedValueException $e) {
return false;
}
try {
$num = \count($this->getVerticesSubtree($root));
} catch (UnexpectedValueException $e) {
return false;
}
// check number of vertices reachable from root should match total number of vertices
return ($num === \count($this->graph->getVertices()));
}
/**
* get parent vertex for given $vertex
*
* @param Vertex $vertex
* @throws UnderflowException if vertex has no parent (is a root vertex)
* @throws UnexpectedValueException if vertex has more than one possible parent (check isTree()!)
* @return Vertex
* @uses self::getVerticesParents() to get array of parent vertices
*/
public function getVertexParent(Vertex $vertex)
{
$parents = $this->getVerticesParent($vertex);
if (\count($parents) !== 1) {
if ($parents->isEmpty()) {
throw new UnderflowException('No parents for given vertex found');
} else {
throw new UnexpectedValueException('More than one parent');
}
}
return $parents->getVertexFirst();
}
/**
* get array of child vertices for given $vertex
*
* @param Vertex $vertex
* @return Vertices
* @throws UnexpectedValueException if the given $vertex contains invalid / parallel edges (check isTree()!)
*/
abstract public function getVerticesChildren(Vertex $vertex);
/**
* internal helper to get all parents vertices
*
* a valid tree vertex only ever has a single parent, except for the root,
* which has none.
*
* @param Vertex $vertex
* @return Vertices
* @throws UnexpectedValueException if the given $vertex contains invalid / parallel edges (check isTree()!)
*/
abstract protected function getVerticesParent(Vertex $vertex);
/**
* check if given vertex is a possible root (i.e. has no parent)
*
* @param Vertex $vertex
* @return bool
* @uses self::getVerticesParent()
*/
protected function isVertexPossibleRoot(Vertex $vertex)
{
return (\count($this->getVerticesParent($vertex)) === 0);
}
/**
* checks if the given $vertex is a leaf (outermost vertex with no children)
*
* @param Vertex $vertex
* @return bool
* @uses self::getVerticesChildren() to check given vertex has no children
*/
public function isVertexLeaf(Vertex $vertex)
{
return (\count($this->getVerticesChildren($vertex)) === 0);
}
/**
* checks if the given $vertex is an internal vertex (has children and is not root)
*
* @param Vertex $vertex
* @return bool
* @uses self::getVerticesParent() to check given vertex has a parent (is not root)
* @uses self::getVerticesChildren() to check given vertex has children (is not a leaf)
* @see \Graphp\Algorithms\Tree\Base::isVertexInternal() for more information
*/
public function isVertexInternal(Vertex $vertex)
{
return (!$this->getVerticesParent($vertex)->isEmpty() && !$this->getVerticesChildren($vertex)->isEmpty());
}
/**
* get degree of tree (maximum number of children)
*
* @return int
* @throws UnderflowException for empty graphs
* @uses Graph::getVertices()
* @uses self::getVerticesChildren()
*/
public function getDegree()
{
$max = null;
foreach ($this->graph->getVertices() as $vertex) {
$num = \count($this->getVerticesChildren($vertex));
if ($max === null || $num > $max) {
$max = $num;
}
}
if ($max === null) {
throw new UnderflowException('No vertices found');
}
return $max;
}
/**
* get depth of given $vertex (number of edges between root vertex)
*
* root has depth zero
*
* @param Vertex $vertex
* @return int
* @throws UnderflowException for empty graphs
* @throws UnexpectedValueException if there's no path to root node (check isTree()!)
* @uses self::getVertexRoot()
* @uses self::getVertexParent() for each step
*/
public function getDepthVertex(Vertex $vertex)
{
$root = $this->getVertexRoot();
$depth = 0;
while ($vertex !== $root) {
$vertex = $this->getVertexParent($vertex);
++$depth;
}
return $depth;
}
/**
* get height of this tree (longest downward path to a leaf)
*
* a single vertex graph has height zero
*
* @return int
* @throws UnderflowException for empty graph
* @uses self::getVertexRoot()
* @uses self::getHeightVertex()
*/
public function getHeight()
{
return $this->getHeightVertex($this->getVertexRoot());
}
/**
* get height of given vertex (longest downward path to a leaf)
*
* leafs has height zero
*
* @param Vertex $vertex
* @return int
* @uses self::getVerticesChildren() to get children of given vertex
* @uses self::getHeightVertex() to recurse into sub-children
*/
public function getHeightVertex(Vertex $vertex)
{
$max = 0;
foreach ($this->getVerticesChildren($vertex) as $vertex) {
$height = $this->getHeightVertex($vertex) + 1;
if ($height > $max) {
$max = $height;
}
}
return $max;
}
/**
* get all vertices that are in the subtree of the given $vertex (which IS included)
*
* root vertex will return the whole tree, leaf vertices will only return themselves
*
* @param Vertex $vertex
* @throws UnexpectedValueException if there are invalid edges (check isTree()!)
* @return Vertices
* @uses self::getVerticesSubtreeRecursive()
* @uses self::getVerticesSubtree()
*/
public function getVerticesSubtree(Vertex $vertex)
{
$vertices = array();
$this->getVerticesSubtreeRecursive($vertex, $vertices);
return new Vertices($vertices);
}
/**
* helper method to get recursively get subtree for given $vertex
*
* @param Vertex $vertex
* @param Vertex[] $vertices
* @throws UnexpectedValueException if multiple links were found to the given edge (check isTree()!)
* @uses self::getVerticesChildren()
* @uses self::getVerticesSubtreeRecursive() to recurse into subtrees
*/
private function getVerticesSubtreeRecursive(Vertex $vertex, array &$vertices)
{
$vid = $vertex->getId();
if (isset($vertices[$vid])) {
throw new UnexpectedValueException('Multiple links found');
}
$vertices[$vid] = $vertex;
foreach ($this->getVerticesChildren($vertex) as $vertexChild) {
$this->getVerticesSubtreeRecursive($vertexChild, $vertices);
}
}
/**
* get all vertices below the given $vertex (which is NOT included)
*
* think of this as the recursive version of getVerticesChildren()
*
* @param Vertex $vertex
* @return Vertices
* @throws UnexpectedValueException if there are invalid edges (check isTree()!)
* @uses self::getVerticesSubtree()
*/
public function getVerticesDescendant(Vertex $vertex)
{
$vertices = $this->getVerticesSubtree($vertex)->getMap();
unset($vertices[$vertex->getId()]);
return new Vertices($vertices);
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/MaxFlow/EdmondsKarp.php | src/MaxFlow/EdmondsKarp.php | <?php
namespace Graphp\Algorithms\MaxFlow;
use Graphp\Algorithms\Base;
use Graphp\Algorithms\ResidualGraph;
use Graphp\Algorithms\ShortestPath\BreadthFirst;
use Graphp\Graph\EdgeDirected;
use Graphp\Graph\Exception\InvalidArgumentException;
use Graphp\Graph\Exception\OutOfBoundsException;
use Graphp\Graph\Exception\UnderflowException;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Graph;
use Graphp\Graph\Set\Edges;
use Graphp\Graph\Vertex;
class EdmondsKarp extends Base
{
/**
* @var Vertex
*/
private $startVertex;
/**
* @var Vertex
*/
private $destinationVertex;
/**
* @param Vertex $startVertex the vertex where the flow search starts
* @param Vertex $destinationVertex the vertex where the flow search ends (destination)
*/
public function __construct(Vertex $startVertex, Vertex $destinationVertex)
{
if ($startVertex === $destinationVertex) {
throw new InvalidArgumentException('Start and destination must not be the same vertex');
}
if ($startVertex->getGraph() !== $destinationVertex->getGraph()) {
throw new InvalidArgumentException('Start and target vertex have to be in the same graph instance');
}
$this->startVertex = $startVertex;
$this->destinationVertex = $destinationVertex;
}
/**
* Returns max flow graph
*
* @return Graph
* @throws UnexpectedValueException for undirected edges
*/
public function createGraph()
{
$graphResult = $this->startVertex->getGraph()->createGraphClone();
// initialize null flow and check edges
foreach ($graphResult->getEdges() as $edge) {
if (!($edge instanceof EdgeDirected)) {
throw new UnexpectedValueException('Undirected edges not supported for edmonds karp');
}
$edge->setFlow(0);
}
$idA = $this->startVertex->getId();
$idB = $this->destinationVertex->getId();
do {
// Generate new residual graph and repeat
$residualAlgorithm = new ResidualGraph($graphResult);
$graphResidual = $residualAlgorithm->createGraph();
// 1. Search _shortest_ (number of hops and cheapest) path from s -> t
$alg = new BreadthFirst($graphResidual->getVertex($idA));
try {
$pathFlow = $alg->getWalkTo($graphResidual->getVertex($idB));
} catch (OutOfBoundsException $e) {
$pathFlow = NULL;
}
// If path exists add the new flow to graph
if ($pathFlow) {
// 2. get max flow from path
$maxFlowValue = $pathFlow->getEdges()->getEdgeOrder(Edges::ORDER_CAPACITY)->getCapacity();
// 3. add flow to path
foreach ($pathFlow->getEdges() as $edge) {
// try to look for forward edge to increase flow
try {
$originalEdge = $graphResult->getEdgeClone($edge);
$originalEdge->setFlow($originalEdge->getFlow() + $maxFlowValue);
// forward edge not found, look for back edge to decrease flow
} catch (UnderflowException $e) {
$originalEdge = $graphResult->getEdgeCloneInverted($edge);
$originalEdge->setFlow($originalEdge->getFlow() - $maxFlowValue);
}
}
}
// repeat while we still finds paths with residual capacity to add flow to
} while ($pathFlow);
return $graphResult;
}
/**
* Returns max flow value
*
* @return float
*/
public function getFlowMax()
{
$resultGraph = $this->createGraph();
$start = $resultGraph->getVertex($this->startVertex->getId());
$maxFlow = 0;
foreach ($start->getEdgesOut() as $edge) {
$maxFlow = $maxFlow + $edge->getFlow();
}
return $maxFlow;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Search/BreadthFirst.php | src/Search/BreadthFirst.php | <?php
namespace Graphp\Algorithms\Search;
use Graphp\Graph\Set\Vertices;
class BreadthFirst extends Base
{
/**
* @param int $maxDepth
* @return Vertices
*/
public function getVertices($maxDepth = PHP_INT_MAX)
{
$queue = array($this->vertex);
// to not add vertices twice in array visited
$mark = array($this->vertex->getId() => true);
// visited vertices
$visited = array();
// keep track of depth
$currentDepth = 0;
$nodesThisLevel = 1;
$nodesNextLevel = 0;
do {
// get first from queue
$t = \array_shift($queue);
// save as visited
$visited[$t->getId()] = $t;
// get next vertices
$children = $this->getVerticesAdjacent($t);
// track depth
$nodesNextLevel = $children->count();
if (--$nodesThisLevel === 0) {
if (++$currentDepth > $maxDepth) {
return new Vertices($visited);
}
$nodesThisLevel = $nodesNextLevel;
$nodesNextLevel = 0;
}
// process next vertices
foreach ($children->getMap() as $id => $vertex) {
// if not "touched" before
if (!isset($mark[$id])) {
// add to queue
$queue[] = $vertex;
// and mark
$mark[$id] = true;
}
}
// until queue is empty
} while ($queue);
return new Vertices($visited);
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Search/Base.php | src/Search/Base.php | <?php
namespace Graphp\Algorithms\Search;
use Graphp\Algorithms\BaseVertex;
use Graphp\Graph\Exception\InvalidArgumentException;
use Graphp\Graph\Set\Vertices;
use Graphp\Graph\Vertex;
abstract class Base extends BaseVertex
{
const DIRECTION_FORWARD = 0;
const DIRECTION_REVERSE = 1;
const DIRECTION_BOTH = 2;
private $direction = self::DIRECTION_FORWARD;
/**
* set direction in which to follow adjacent vertices
*
* @param int $direction
* @return $this (chainable)
* @throws InvalidArgumentException
* @see self::getVerticesAdjacent()
*/
public function setDirection($direction)
{
if ($direction !== self::DIRECTION_FORWARD && $direction !== self::DIRECTION_REVERSE && $direction !== self::DIRECTION_BOTH) {
throw new InvalidArgumentException('Invalid direction given');
}
$this->direction = $direction;
return $this;
}
protected function getVerticesAdjacent(Vertex $vertex)
{
if ($this->direction === self::DIRECTION_FORWARD) {
return $vertex->getVerticesEdgeTo();
} elseif ($this->direction === self::DIRECTION_REVERSE) {
return $vertex->getVerticesEdgeFrom();
} else {
return $vertex->getVerticesEdge();
}
}
/**
* get set of all Vertices that can be reached from start vertex
*
* @return Vertices
*/
abstract public function getVertices();
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Search/DepthFirst.php | src/Search/DepthFirst.php | <?php
namespace Graphp\Algorithms\Search;
use Graphp\Graph\Set\Vertices;
class DepthFirst extends Base
{
/**
* calculates an iterative depth-first search
*
* @return Vertices
*/
public function getVertices()
{
$visited = array();
$todo = array($this->vertex);
while ($vertex = \array_shift($todo)) {
if (!isset($visited[$vertex->getId()])) {
$visited[$vertex->getId()] = $vertex;
foreach (\array_reverse($this->getVerticesAdjacent($vertex)->getMap(), true) as $nextVertex) {
$todo[] = $nextVertex;
}
}
}
return new Vertices($visited);
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/MinimumSpanningTree/Base.php | src/MinimumSpanningTree/Base.php | <?php
namespace Graphp\Algorithms\MinimumSpanningTree;
use Graphp\Algorithms\Base as AlgorithmBase;
use Graphp\Graph\Edge;
use Graphp\Graph\Graph;
use Graphp\Graph\Set\Edges;
use SplPriorityQueue;
/**
* Abstract base class for minimum spanning tree (MST) algorithms
*
* A minimum spanning tree of a graph is a subgraph that is a tree and connects
* all the vertices together while minimizing the total sum of all edges'
* weights.
*
* A spanning tree thus requires a connected graph (single connected component),
* otherwise we can span multiple trees (spanning forest) within each component.
* Because a null graph (a Graph with no vertices) is not considered connected,
* it also can not contain a spanning tree.
*
* Most authors demand that the input graph has to be undirected, whereas this
* library supports also directed and mixed graphs. The actual direction of the
* edge will be ignored, only its incident vertices will be checked. This is
* done in order to be consistent to how ConnectedComponents are checked.
*
* @link http://en.wikipedia.org/wiki/Minimum_Spanning_Tree
* @link http://en.wikipedia.org/wiki/Spanning_Tree
* @link http://mathoverflow.net/questions/120536/is-the-empty-graph-a-tree
*/
abstract class Base extends AlgorithmBase
{
/**
* create new resulting graph with only edges on minimum spanning tree
*
* @return Graph
* @uses self::getGraph()
* @uses self::getEdges()
* @uses Graph::createGraphCloneEdges()
*/
public function createGraph()
{
return $this->getGraph()->createGraphCloneEdges($this->getEdges());
}
/**
* get all edges on minimum spanning tree
*
* @return Edges
*/
abstract public function getEdges();
/**
* return reference to current Graph
*
* @return Graph
*/
abstract protected function getGraph();
/**
* get total weight of minimum spanning tree
*
* @return float
*/
public function getWeight()
{
return $this->getEdges()->getSumCallback(function (Edge $edge) {
return $edge->getWeight();
});
}
/**
* helper method to add a set of Edges to the given set of sorted edges
*
* @param Edges $edges
* @param SplPriorityQueue $sortedEdges
*/
protected function addEdgesSorted(Edges $edges, SplPriorityQueue $sortedEdges)
{
// For all edges
foreach ($edges as $edge) {
assert($edge instanceof Edge);
// ignore loops (a->a)
if (!$edge->isLoop()) {
// Add edges with negative weight because of order in stl
$sortedEdges->insert($edge, -$edge->getWeight());
}
}
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/MinimumSpanningTree/Prim.php | src/MinimumSpanningTree/Prim.php | <?php
namespace Graphp\Algorithms\MinimumSpanningTree;
use Graphp\Graph\Edge;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Set\Edges;
use Graphp\Graph\Vertex;
use SplPriorityQueue;
class Prim extends Base
{
/**
* @var Vertex
*/
private $startVertex;
public function __construct(Vertex $startVertex)
{
$this->startVertex = $startVertex;
}
/**
* @return Edges
*/
public function getEdges()
{
// Initialize algorithm
$edgeQueue = new SplPriorityQueue();
$vertexCurrent = $this->startVertex;
$markInserted = array();
$returnEdges = array();
// iterate n-1 times (per definition, resulting MST MUST have n-1 edges)
for ($i = 0, $n = \count($this->startVertex->getGraph()->getVertices()) - 1; $i < $n; ++$i) {
$markInserted[$vertexCurrent->getId()] = true;
// get unvisited vertex of the edge and add edges from new vertex
// Add all edges from $currentVertex to priority queue
$this->addEdgesSorted($vertexCurrent->getEdges(), $edgeQueue);
do {
if ($edgeQueue->isEmpty()) {
throw new UnexpectedValueException('Graph has more than one component');
}
// Get next cheapest edge
$cheapestEdge = $edgeQueue->extract();
assert($cheapestEdge instanceof Edge);
// Check if edge is between unmarked and marked edge
$vertices = $cheapestEdge->getVertices();
$vertexA = $vertices->getVertexFirst();
$vertexB = $vertices->getVertexLast();
} while (!(isset($markInserted[$vertexA->getId()]) XOR isset($markInserted[$vertexB->getId()])));
// Cheapest Edge found, add edge to returnGraph
$returnEdges[] = $cheapestEdge;
// set current vertex for next iteration in order to add its edges to queue
if (isset($markInserted[$vertexA->getId()])) {
$vertexCurrent = $vertexB;
} else {
$vertexCurrent = $vertexA;
}
}
return new Edges($returnEdges);
}
protected function getGraph()
{
return $this->startVertex->getGraph();
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/MinimumSpanningTree/Kruskal.php | src/MinimumSpanningTree/Kruskal.php | <?php
namespace Graphp\Algorithms\MinimumSpanningTree;
use Graphp\Graph\Edge;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Graph;
use Graphp\Graph\Set\Edges;
use SplPriorityQueue;
class Kruskal extends Base
{
/**
* @var Graph
*/
private $graph;
public function __construct(Graph $inputGraph)
{
$this->graph = $inputGraph;
}
protected function getGraph()
{
return $this->graph;
}
/**
* @return Edges
*/
public function getEdges()
{
// Sortiere Kanten im Graphen
$sortedEdges = new SplPriorityQueue();
// For all edges
$this->addEdgesSorted($this->graph->getEdges(), $sortedEdges);
$returnEdges = array();
// next color to assign
$colorNext = 0;
// array(color1 => array(vid1, vid2, ...), color2=>...)
$colorVertices = array();
// array(vid1 => color1, vid2 => color1, ...)
$colorOfVertices = array();
// Füge billigste Kanten zu neuen Graphen hinzu und verschmelze teilgragen wenn es nötig ist (keine Kreise)
// solange ich mehr als einen Graphen habe mit weniger als n-1 kanten (bei n knoten im original)
foreach ($sortedEdges as $edge) {
assert($edge instanceof Edge);
// Gucke Kante an:
$vertices = $edge->getVertices()->getIds();
$aId = $vertices[0];
$bId = $vertices[1];
$aColor = isset($colorOfVertices[$aId]) ? $colorOfVertices[$aId] : NULL;
$bColor = isset($colorOfVertices[$bId]) ? $colorOfVertices[$bId] : NULL;
// 1. weder start noch end gehört zu einem graphen
// => neuer Graph mit kanten
if ($aColor === NULL && $bColor === NULL) {
$colorOfVertices[$aId] = $colorNext;
$colorOfVertices[$bId] = $colorNext;
$colorVertices[$colorNext] = array($aId, $bId);
++$colorNext;
// connect both vertices
$returnEdges[] = $edge;
}
// 4. start xor end gehören zu einem graphen
// => erweitere diesesn Graphen
// Only b has color
else if ($aColor === NULL && $bColor !== NULL) {
// paint a in b's color
$colorOfVertices[$aId] = $bColor;
$colorVertices[$bColor][]=$aId;
$returnEdges[] = $edge;
// Only a has color
} elseif ($aColor !== NULL && $bColor === NULL) {
// paint b in a's color
$colorOfVertices[$bId] = $aColor;
$colorVertices[$aColor][]=$bId;
$returnEdges[] = $edge;
}
// 3. start und end gehören zu unterschiedlichen graphen
// => vereinigung
// Different color
else if ($aColor !== $bColor) {
$betterColor = $aColor;
$worseColor = $bColor;
// more vertices with color a => paint all in b in a's color
if (\count($colorVertices[$bColor]) > \count($colorVertices[$aColor])) {
$betterColor = $bColor;
$worseColor = $aColor;
}
// search all vertices with color b
foreach ($colorVertices[$worseColor] as $vid) {
$colorOfVertices[$vid] = $betterColor;
// repaint in a's color
$colorVertices[$betterColor][]=$vid;
}
// delete old color
unset($colorVertices[$worseColor]);
$returnEdges[] = $edge;
}
// 2. start und end gehören zum gleichen graphen => zirkel
// => nichts machen
}
// definition of spanning tree: number of edges = number of vertices - 1
// above algorithm does not check isolated edges or may otherwise return multiple connected components => force check
if (\count($returnEdges) !== (\count($this->graph->getVertices()) - 1)) {
throw new UnexpectedValueException('Graph is not connected');
}
return new Edges($returnEdges);
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Property/GraphProperty.php | src/Property/GraphProperty.php | <?php
namespace Graphp\Algorithms\Property;
use Graphp\Algorithms\BaseGraph;
/**
* Simple algorithms for working with Graph properties
*
* @link https://en.wikipedia.org/wiki/Graph_property
*/
class GraphProperty extends BaseGraph
{
/**
* checks whether this graph has no edges
*
* Also known as empty Graph. An empty Graph contains no edges, but can
* possibly contain any number of isolated vertices.
*
* @return bool
*/
public function isEdgeless()
{
return $this->graph->getEdges()->isEmpty();
}
/**
* checks whether this graph is a null graph (no vertex - and thus no edges)
*
* Each Edge is incident to two Vertices, or in case of an loop Edge,
* incident to the same Vertex twice. As such an Edge can not exist when
* no Vertices exist. So if we check we have no Vertices, we can also be
* sure that no Edges exist either.
*
* @return bool
*/
public function isNull()
{
return $this->graph->getVertices()->isEmpty();
}
/**
* checks whether this graph is trivial (one vertex and no edges)
*
* @return bool
*/
public function isTrivial()
{
return ($this->graph->getEdges()->isEmpty() && \count($this->graph->getVertices()) === 1);
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/src/Property/WalkProperty.php | src/Property/WalkProperty.php | <?php
namespace Graphp\Algorithms\Property;
use Graphp\Algorithms\Base as BaseAlgorithm;
use Graphp\Algorithms\Loop as AlgorithmLoop;
use Graphp\Graph\Walk;
/**
* Simple algorithms for working with Walk properties
*
* @see GraphProperty
*/
class WalkProperty extends BaseAlgorithm
{
/**
* the Walk to operate on
*
* @var Walk
*/
protected $walk;
/**
* instantiate new WalkProperty algorithm
*
* @param Walk $walk
*/
public function __construct(Walk $walk)
{
$this->walk = $walk;
}
/**
* checks whether walk is a cycle (i.e. source vertex = target vertex)
*
* A cycle is also known as a closed path, a walk that is NOT a cycle is
* also known as an open path.
*
* A walk with no edges is not considered a cycle. The shortest possible
* cycle is a single loop edge:
*
* 1--\
* ^ |
* \--/
*
* The following Walk is also considered a valid cycle:
*
* /->3--\
* | |
* 1 -> 2 -\ |
* ^ ^ | |
* | \--/ |
* | |
* \----------/
*
* @return bool
* @link http://en.wikipedia.org/wiki/Cycle_%28graph_theory%29
* @see self::isCircuit()
* @see self::isLoop()
*/
public function isCycle()
{
$vertices = $this->walk->getVertices();
return ($vertices->getVertexFirst() === $vertices->getVertexLast() && !$this->walk->getEdges()->isEmpty());
}
/**
* checks whether this walk is a circuit (i.e. a cycle with no duplicate edges)
*
* A circuit is also known as a closed (=cycle) trail (=path), that has at
* least one edge.
*
* The following Walk is considered both a valid cycle and a valid circuit:
*
* 1 -> 2 -> 3 -\
* ^ |
* | |
* \------------/
*
* The following Walk is also considered both a valid cycle and a valid circuit:
*
* /->3--\
* | |
* 1 -> 2 -\ |
* ^ ^ | |
* | \--/ |
* | |
* \----------/
*
* The later circuit walk can be expressed by its Vertex IDs as
* "1, 2, 2, 3, 1". If however, the inner loop would be "walked along"
* several times, the resulting walk would be expressed as
* "1, 2, 2, 2, 3, 1", which would still be a valid cycle, but NOT a valid
* circuit anymore.
*
* @return bool
* @link http://www.proofwiki.org/wiki/Definition:Circuit
* @uses self::isCycle()
* @uses self::isPath()
*/
public function isCircuit()
{
return ($this->isCycle() && $this->isPath());
}
/**
* checks whether walk is a path (i.e. does not contain any duplicate edges)
*
* A path Walk is also known as a trail.
*
* @return bool
* @uses self::hasArrayDuplicates()
* @link http://www.proofwiki.org/wiki/Definition:Trail
*/
public function isPath()
{
return !$this->hasArrayDuplicates($this->walk->getEdges()->getVector());
}
/**
* checks whether walk contains a cycle (i.e. contains a duplicate vertex)
*
* A walk that CONTAINS a cycle does not neccessarily have to BE a cycle.
* Conversely, a Walk that *is* a cycle, automatically always *contains* a
* cycle.
*
* The following Walk is NOT a cycle, but it *contains* a valid cycle:
*
* /->4
* |
* 1 -> 2 -> 3 -\
* ^ |
* \-------/
*
* @return bool
* @uses self::hasArrayDuplicates()
* @see self::isCycle()
*/
public function hasCycle()
{
return $this->hasArrayDuplicates($this->walk->getVertices()->getVector());
}
/**
* checks whether this walk IS a loop (single edge connecting vertex A with vertex A again)
*
* A loop is the simplest possible cycle. As such, each loop is also a
* cycle. Accordingly, every Walk that *is* a loop, automatically also *is*
* a cycle and automatically *contains* a loop and automatically *contains*
* a cycle.
*
* The following Walk represents a simple (directed) loop:
*
* 1--\
* ^ |
* \--/
*
* @return bool
* @uses self::isCycle()
* @see self::hasLoop()
*/
public function isLoop()
{
return (\count($this->walk->getEdges()) === 1 && $this->isCycle());
}
/**
* checks whether this walk HAS a loop (single edge connecting vertex A with vertex A again)
*
* The following Walk is NOT a valid loop, but it contains a valid loop:
*
* /->3
* |
* 1 -> 2 -\
* ^ |
* \--/
*
* @return bool
* @uses AlgorithmLoop::hasLoop()
* @see self::isLoop()
*/
public function hasLoop()
{
$alg = new AlgorithmLoop($this->walk);
return $alg->hasLoop();
}
/**
* checks whether this walk is a digon (a pair of parallel edges in a multigraph or a pair of antiparallel edges in a digraph)
*
* A digon is a cycle connecting exactly two distinct vertices with exactly
* two distinct edges.
*
* The following Graph represents a digon in an undirected Graph:
*
* /--\
* 1 2
* \--/
*
* The following Graph represents a digon as a set of antiparallel directed
* Edges in a directed Graph:
*
* 1 -> 2
* ^ |
* | |
* \----/
*
* @return bool
* @uses self::hasArrayDuplicates()
* @uses self::isCycle()
*/
public function isDigon()
{
// exactly 2 edges
return (\count($this->walk->getEdges()) === 2 &&
// no duplicate edges
!$this->hasArrayDuplicates($this->walk->getEdges()->getVector()) &&
// exactly two distinct vertices
\count($this->walk->getVertices()->getVerticesDistinct()) === 2 &&
// this is actually a cycle
$this->isCycle());
}
/**
* checks whether this walk is a triangle (a simple cycle with exactly three distinct vertices)
*
* The following Graph is a valid directed triangle:
*
* 1->2->3
* ^ |
* \-----/
*
* @return bool
* @uses self::isCycle()
*/
public function isTriangle()
{
// exactly 3 (implicitly distinct) edges
return (\count($this->walk->getEdges()) === 3 &&
// exactly three distinct vertices
\count($this->walk->getVertices()->getVerticesDistinct()) === 3 &&
// this is actually a cycle
$this->isCycle());
}
/**
* check whether this walk is simple
*
* contains no duplicate/repeated vertices (and thus no duplicate edges either)
* other than the starting and ending vertices of cycles.
*
* A simple Walk is also known as a chain.
*
* The term "simple walk" is somewhat related to a walk with no cycles. If
* a Walk has a cycle, it is not simple - with one single exception: a Walk
* that IS a cycle automatically also contains a cycle, but if it contains
* no "further" additional cycles, it is considered a simple cycle.
*
* The following Graph represents a (very) simple Walk:
*
* 1 -- 2
*
* The following Graph IS a cycle and is simple:
*
* 1 -> 2
* ^ |
* \----/
*
* The following Graph contains a cycle and is NOT simple:
*
* /->4
* |
* 1 -> 2 -> 3 -\
* ^ |
* \-------/
*
* The following Graph IS a cycle and thus automatically contains a cycle.
* Due to the additional "inner" cycle (loop at vertex 2), it is NOT simple:
*
* /->3--\
* | |
* 1 -> 2 -\ |
* ^ ^ | |
* | \--/ |
* | |
* \----------/
*
* @return bool
* @uses self::isCycle()
* @uses self::hasArrayDuplicates()
* @see self::hasCycle()
*/
public function isSimple()
{
$vertices = $this->walk->getVertices()->getVector();
// ignore starting vertex for cycles as it's always the same as ending vertex
if ($this->isCycle()) {
unset($vertices[0]);
}
return !$this->hasArrayDuplicates($vertices);
}
/**
* checks whether walk is hamiltonian (i.e. walk over ALL VERTICES of the graph)
*
* A hamiltonian Walk is also known as a spanning walk.
*
* @return bool
* @see self::isEulerian() if you want to check for all EDGES instead of VERTICES
* @uses self::isArrayContentsEqual()
* @link http://en.wikipedia.org/wiki/Hamiltonian_path
*/
public function isHamiltonian()
{
$vertices = $this->walk->getVertices()->getVector();
// ignore starting vertex for cycles as it's always the same as ending vertex
if ($this->isCycle()) {
unset($vertices[0]);
}
return $this->isArrayContentsEqual($vertices, $this->walk->getGraph()->getVertices()->getVector());
}
/**
* checks whether walk is eulerian (i.e. a walk over ALL EDGES of the graph)
*
* @return bool
* @see self::isHamiltonian() if you want to check for all VERTICES instead of EDGES
* @uses self::isArrayContentsEqual()
* @link http://en.wikipedia.org/wiki/Eulerian_path
*/
public function isEulerian()
{
return $this->isArrayContentsEqual($this->walk->getEdges()->getVector(), $this->walk->getGraph()->getEdges()->getVector());
}
/**
* checks whether ths given array contains duplicate identical entries
*
* @param array $array
* @return bool
*/
private function hasArrayDuplicates($array)
{
$compare = array();
foreach ($array as $element) {
// duplicate element found
if (\in_array($element, $compare, true)) {
return true;
} else {
// add element to temporary array to check for duplicates
$compare [] = $element;
}
}
return false;
}
/**
* checks whether the contents of array a equals those of array b (ignore keys and order but otherwise strict check)
*
* @param array $a
* @param array $b
* @return bool
*/
private function isArrayContentsEqual($a, $b)
{
foreach ($b as $one) {
$pos = \array_search($one, $a, true);
if ($pos === false) {
return false;
} else {
unset($a[$pos]);
}
}
return $a ? false : true;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/DegreeTest.php | tests/DegreeTest.php | <?php
namespace Graphp\Tests\Algorithms;
use Graphp\Algorithms\Degree as AlgorithmDegree;
use Graphp\Graph\Exception\UnderflowException;
use Graphp\Graph\Exception\UnexpectedValueException;
use Graphp\Graph\Graph;
class DegreeTest extends TestCase
{
public function testGraphEmpty()
{
$graph = new Graph();
$alg = new AlgorithmDegree($graph);
try {
$alg->getDegree();
$this->fail();
} catch (UnderflowException $e) { }
try {
$alg->getDegreeMin();
$this->fail();
} catch (UnderflowException $e) { }
try {
$alg->getDegreeMax();
$this->fail();
} catch (UnderflowException $e) { }
$this->assertTrue($alg->isRegular());
$this->assertTrue($alg->isBalanced());
}
public function testGraphIsolated()
{
$graph = new Graph();
$graph->createVertex(1);
$graph->createVertex(2);
$alg = new AlgorithmDegree($graph);
$this->assertEquals(0, $alg->getDegree());
$this->assertEquals(0, $alg->getDegreeMin());
$this->assertEquals(0, $alg->getDegreeMax());
$this->assertTrue($alg->isRegular());
$this->assertTrue($alg->isBalanced());
}
public function testGraphIrregular()
{
// 1 -> 2 -> 3
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$v3 = $graph->createVertex(3);
$graph->createEdgeDirected($v1, $v2);
$graph->createEdgeDirected($v2, $v3);
$alg = new AlgorithmDegree($graph);
try {
$this->assertEquals(0, $alg->getDegree());
$this->fail();
} catch (UnexpectedValueException $e) { }
$this->assertEquals(1, $alg->getDegreeMin());
$this->assertEquals(2, $alg->getDegreeMax());
$this->assertFalse($alg->isRegular());
$this->assertFalse($alg->isBalanced());
$this->assertEquals(0, $alg->getDegreeInVertex($v1));
$this->assertEquals(1, $alg->getDegreeOutVertex($v1));
$this->assertEquals(1, $alg->getDegreeVertex($v1));
$this->assertFalse($alg->isVertexIsolated($v1));
$this->assertFalse($alg->isVertexSink($v1));
$this->assertTrue($alg->isVertexSource($v1));
$this->assertEquals(1, $alg->getDegreeInVertex($v2));
$this->assertEquals(1, $alg->getDegreeOutVertex($v2));
$this->assertEquals(2, $alg->getDegreeVertex($v2));
$this->assertFalse($alg->isVertexIsolated($v2));
$this->assertFalse($alg->isVertexSink($v2));
$this->assertFalse($alg->isVertexSource($v2));
$this->assertEquals(1, $alg->getDegreeInVertex($v3));
$this->assertEquals(0, $alg->getDegreeOutVertex($v3));
$this->assertEquals(1, $alg->getDegreeVertex($v3));
$this->assertFalse($alg->isVertexIsolated($v3));
$this->assertTrue($alg->isVertexSink($v3));
$this->assertFalse($alg->isVertexSource($v3));
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/ConnectedComponentsTest.php | tests/ConnectedComponentsTest.php | <?php
namespace Graphp\Tests\Algorithms;
use Graphp\Algorithms\ConnectedComponents as AlgorithmConnected;
use Graphp\Graph\Graph;
class ConnectedComponentsTest extends TestCase
{
public function testNullGraph()
{
$graph = new Graph();
$alg = new AlgorithmConnected($graph);
$this->assertEquals(0, $alg->getNumberOfComponents());
$this->assertFalse($alg->isSingle());
$this->assertCount(0, $alg->createGraphsComponents());
}
public function testGraphSingleTrivial()
{
$graph = new Graph();
$graph->createVertex(1);
$alg = new AlgorithmConnected($graph);
$this->assertEquals(1, $alg->getNumberOfComponents());
$this->assertTrue($alg->isSingle());
$graphs = $alg->createGraphsComponents();
$this->assertCount(1, $graphs);
$this->assertGraphEquals($graph, \reset($graphs));
}
public function testGraphEdgeDirections()
{
// 1 -- 2 -> 3 <- 4
$graph = new Graph();
$graph->createEdgeUndirected($graph->createVertex(1), $graph->createVertex(2));
$graph->createEdgeDirected($graph->getVertex(2), $graph->createVertex(3));
$graph->createEdgeDirected($graph->createVertex(4), $graph->getVertex(3));
$alg = new AlgorithmConnected($graph);
$this->assertEquals(1, $alg->getNumberOfComponents());
$this->assertTrue($alg->isSingle());
$graphs = $alg->createGraphsComponents();
$this->assertCount(1, $graphs);
$this->assertGraphEquals($graph, \reset($graphs));
$this->assertGraphEquals($graph, $alg->createGraphComponentVertex($graph->getVertex(1)));
}
public function testComponents()
{
// 1 -- 2, 3 -> 4, 5
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$v3 = $graph->createVertex(3);
$v4 = $graph->createVertex(4);
$v5 = $graph->createVertex(5);
$graph->createEdgeUndirected($v1, $v2);
$graph->createEdgeDirected($v3, $v4);
$alg = new AlgorithmConnected($graph);
$this->assertEquals(3, $alg->getNumberOfComponents());
$this->assertFalse($alg->isSingle());
$graphs = $alg->createGraphsComponents();
$this->assertCount(3, $graphs);
$ge = new Graph();
$ge->createEdgeUndirected($ge->createVertex(1), $ge->createVertex(2));
$this->assertGraphEquals($ge, $alg->createGraphComponentVertex($v2));
$ge = new Graph();
$ge->createVertex(5);
$this->assertEquals($ge, $alg->createGraphComponentVertex($v5));
}
public function testInvalidVertexPassedToAlgorithm()
{
$graph = new Graph();
$graph2 = new Graph();
$v2 = $graph2->createVertex(12);
$alg = new AlgorithmConnected($graph);
$this->setExpectedException('InvalidArgumentException');
$alg->createGraphComponentVertex($v2);
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/CompleteTest.php | tests/CompleteTest.php | <?php
namespace Graphp\Tests\Algorithms;
use Graphp\Algorithms\Complete as AlgorithmComplete;
use Graphp\Graph\Graph;
class CompleteTest extends TestCase
{
public function testGraphEmptyK0()
{
$graph = new Graph();
$alg = new AlgorithmComplete($graph);
$this->assertTrue($alg->isComplete());
}
public function testGraphSingleTrivialK1()
{
$graph = new Graph();
$graph->createVertex(1);
$alg = new AlgorithmComplete($graph);
$this->assertTrue($alg->isComplete());
}
public function testGraphSimplePairK2()
{
// 1 -- 2
$graph = new Graph();
$graph->createEdgeUndirected($graph->createVertex(1), $graph->createVertex(2));
$alg = new AlgorithmComplete($graph);
$this->assertTrue($alg->isComplete());
}
public function testGraphSingleDirectedIsNotComplete()
{
// 1 -> 2
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex(1), $graph->createVertex(2));
$alg = new AlgorithmComplete($graph);
$this->assertFalse($alg->isComplete());
}
public function testAdditionalEdgesToNotAffectCompleteness()
{
// 1 -> 2
// 1 -- 2
// 2 -> 1
// 1 -> 1
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex(1), $graph->createVertex(2));
$graph->createEdgeUndirected($graph->getVertex(1), $graph->getVertex(2));
$graph->createEdgeDirected($graph->getVertex(2), $graph->getVertex(1));
$graph->createEdgeDirected($graph->getVertex(1), $graph->getVertex(1));
$alg = new AlgorithmComplete($graph);
$this->assertTrue($alg->isComplete());
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/BipartitTest.php | tests/BipartitTest.php | <?php
namespace Graphp\Tests\Algorithms;
use Graphp\Algorithms\Bipartit as AlgorithmBipartit;
use Graphp\Graph\Graph;
class BipartitTest extends TestCase
{
public function testGraphEmpty()
{
$graph = new Graph();
$alg = new AlgorithmBipartit($graph);
$this->assertTrue($alg->isBipartit());
$this->assertEquals(array(), $alg->getColors());
$this->assertEquals(array(0 => array(), 1 => array()), $alg->getColorVertices());
}
public function testGraphPairIsBipartit()
{
// 1 -> 2
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$graph->createEdgeDirected($v1, $v2);
$alg = new AlgorithmBipartit($graph);
$this->assertTrue($alg->isBipartit());
$this->assertEquals(array(1 => 0, 2 => 1), $alg->getColors());
$this->assertEquals(array(0 => array(1 => $v1), 1 => array(2 => $v2)), $alg->getColorVertices());
return $alg;
}
/**
*
* @param AlgorithmBipartit $alg
* @depends testGraphPairIsBipartit
*/
public function testGraphPairBipartitGroups(AlgorithmBipartit $alg)
{
// graph does not have any groups assigned, so its groups are not bipartit
$this->assertFalse($alg->isBipartitGroups());
// create a cloned graph with groups assigned according to bipartition
$graph = $alg->createGraphGroups();
$this->assertInstanceOf('Graphp\Graph\Graph', $graph);
$alg2 = new AlgorithmBipartit($graph);
$this->assertTrue($alg2->isBipartitGroups());
}
public function testGraphTriangleCycleIsNotBipartit()
{
// 1 -> 2 --> 3 --> 1
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$v3 = $graph->createVertex(3);
$graph->createEdgeDirected($v1, $v2);
$graph->createEdgeDirected($v2, $v3);
$graph->createEdgeDirected($v3, $v1);
$alg = new AlgorithmBipartit($graph);
$this->assertFalse($alg->isBipartit());
return $alg;
}
/**
*
* @param AlgorithmBipartit $alg
* @depends testGraphTriangleCycleIsNotBipartit
*/
public function testGraphTriangleCycleColorsInvalid(AlgorithmBipartit $alg)
{
$this->setExpectedException('UnexpectedValueException');
$alg->getColors();
}
/**
*
* @param AlgorithmBipartit $alg
* @depends testGraphTriangleCycleIsNotBipartit
*/
public function testGraphTriangleCycleColorVerticesInvalid(AlgorithmBipartit $alg)
{
$this->setExpectedException('UnexpectedValueException');
$alg->getColorVertices();
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/TestCase.php | tests/TestCase.php | <?php
namespace Graphp\Tests\Algorithms;
use Graphp\Graph\Edge;
use Graphp\Graph\EdgeDirected;
use Graphp\Graph\Graph;
use Graphp\Graph\Vertex;
use PHPUnit\Framework\TestCase as BaseTestCase;
class TestCase extends BaseTestCase
{
protected function assertGraphEquals(Graph $expected, Graph $actual)
{
$f = function(Graph $graph){
$ret = \get_class($graph);
$ret .= PHP_EOL . 'vertices: ' . \count($graph->getVertices());
$ret .= PHP_EOL . 'edges: ' . \count($graph->getEdges());
return $ret;
};
// assert graph base parameters are equal
$this->assertEquals($f($expected), $f($actual));
// next, assert that all vertices in both graphs are the same
// each vertex has a unique ID, therefor it's easy to search a matching partner
// do not use assertVertexEquals() in order to not increase assertion counter
foreach ($expected->getVertices()->getMap() as $vid => $vertex) {
$other = $actual->getVertex($vid);
assert(isset($other));
if ($this->getVertexDump($vertex) !== $this->getVertexDump($vertex)) {
$this->fail();
}
}
// next, assert that all edges in both graphs are the same
// assertEdgeEquals() does not work, as the order of the edges is unknown
// therefor, build an array of edge dump and make sure each entry has a match
$edgesExpected = array();
foreach ($expected->getEdges() as $edge) {
$edgesExpected[] = $this->getEdgeDump($edge);
}
foreach ($actual->getEdges() as $edge) {
$dump = $this->getEdgeDump($edge);
$pos = \array_search($dump, $edgesExpected, true);
if ($pos === false) {
$this->fail('given edge ' . $dump . ' not found');
} else {
unset($edgesExpected[$pos]);
}
}
}
protected function assertVertexEquals(Vertex $expected, Vertex $actual)
{
$this->assertEquals($this->getVertexDump($expected), $this->getVertexDump($actual));
}
protected function assertEdgeEquals(Edge $expected, Edge $actual)
{
$this->assertEquals($this->getEdgeDump($expected), $this->getEdgeDump($actual));
}
private function getVertexDump(Vertex $vertex)
{
$ret = \get_class($vertex);
$ret .= PHP_EOL . 'id: ' . $vertex->getId();
$ret .= PHP_EOL . 'attributes: ' . \json_encode($vertex->getAttributeBag()->getAttributes());
$ret .= PHP_EOL . 'balance: ' . $vertex->getBalance();
$ret .= PHP_EOL . 'group: ' . $vertex->getGroup();
return $ret;
}
private function getEdgeDump(Edge $edge)
{
$ret = \get_class($edge) . ' ';
if ($edge instanceof EdgeDirected) {
$ret .= $edge->getVertexStart()->getId() . ' -> ' . $edge->getVertexEnd()->getId();
} else {
$vertices = $edge->getVertices()->getIds();
$ret .= $vertices[0] . ' -- ' . $vertices[1];
}
$ret .= PHP_EOL . 'flow: ' . $edge->getFlow();
$ret .= PHP_EOL . 'capacity: ' . $edge->getCapacity();
$ret .= PHP_EOL . 'weight: ' . $edge->getWeight();
$ret .= PHP_EOL . 'attributes: ' . \json_encode($edge->getAttributeBag()->getAttributes());
return $ret;
}
public function setExpectedException($exception, $exceptionMessage = '', $exceptionCode = null)
{
if (method_exists($this, 'expectException')) {
// PHPUnit 6+
$this->expectException($exception);
if ($exceptionMessage !== '') {
$this->expectExceptionMessage($exceptionMessage);
}
if ($exceptionCode !== null) {
$this->expectExceptionCode($exceptionCode);
}
} else {
// legacy PHPUnit 4 - PHPUnit 5
parent::setExpectedException($exception, $exceptionMessage, $exceptionCode);
}
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/DetectNegativeCycleTest.php | tests/DetectNegativeCycleTest.php | <?php
namespace Graphp\Tests\Algorithms;
use Graphp\Algorithms\DetectNegativeCycle;
use Graphp\Graph\Graph;
class DetectNegativeCycleTest extends TestCase
{
public function testNullGraph()
{
$graph = new Graph();
$alg = new DetectNegativeCycle($graph);
$this->assertFalse($alg->hasCycleNegative());
return $alg;
}
/**
*
* @param DetectNegativeCycle $alg
* @depends testNullGraph
*/
public function testNullGraphHasNoCycle(DetectNegativeCycle $alg)
{
$this->setExpectedException('UnderflowException');
$alg->getCycleNegative();
}
/**
*
* @param DetectNegativeCycle $alg
* @depends testNullGraph
*/
public function testNullGraphHasNoCycleGraph(DetectNegativeCycle $alg)
{
$this->setExpectedException('UnderflowException');
$alg->createGraph();
}
public function testNegativeLoop()
{
// 1 --[-1]--> 1
$graph = new Graph();
$v1 = $graph->createVertex(1);
$e1 = $graph->createEdgeDirected($v1, $v1)->setWeight(-1);
$alg = new DetectNegativeCycle($graph);
$this->assertTrue($alg->hasCycleNegative());
$cycle = $alg->getCycleNegative();
$this->assertCount(1, $cycle->getEdges());
$this->assertCount(2, $cycle->getVertices());
$this->assertEquals($e1, $cycle->getEdges()->getEdgeFirst());
$this->assertEquals($v1, $cycle->getVertices()->getVertexFirst());
}
public function testNegativeCycle()
{
// 1 --[-1]--> 2
// ^ |
// \---[-2]----/
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$graph->createEdgeDirected($v1, $v2)->setWeight(-1);
$graph->createEdgeDirected($v2, $v1)->setWeight(-2);
$alg = new DetectNegativeCycle($graph);
$this->assertTrue($alg->hasCycleNegative());
$cycle = $alg->getCycleNegative();
$this->assertCount(2, $cycle->getEdges());
$this->assertCount(3, $cycle->getVertices());
}
public function testNegativeUndirectedIsNegativeCycle()
{
// 1 --[-1]-- 2
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$graph->createEdgeUndirected($v1, $v2)->setWeight(-1);
$alg = new DetectNegativeCycle($graph);
$this->assertTrue($alg->hasCycleNegative());
$cycle = $alg->getCycleNegative();
$this->assertCount(2, $cycle->getEdges());
$this->assertCount(3, $cycle->getVertices());
}
public function testNegativeCycleSubgraph()
{
// 1 --[1]--> 2 --[1]--> 3 --[1]--> 4
// ^ |
// \---[-2]---/
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$v3 = $graph->createVertex(3);
$v4 = $graph->createVertex(4);
$graph->createEdgeDirected($v1, $v2)->setWeight(1);
$graph->createEdgeDirected($v2, $v3)->setWeight(1);
$graph->createEdgeDirected($v3, $v4)->setWeight(1);
$graph->createEdgeDirected($v4, $v3)->setWeight(-2);
$alg = new DetectNegativeCycle($graph);
$this->assertTrue($alg->hasCycleNegative());
$cycle = $alg->getCycleNegative();
$this->assertCount(2, $cycle->getEdges());
$this->assertCount(3, $cycle->getVertices());
$this->assertTrue($cycle->getVertices()->hasVertexId(3));
$this->assertTrue($cycle->getVertices()->hasVertexId(4));
}
public function testNegativeComponents()
{
// 1 -- 2 3 --[-1]--> 4
// ^ |
// \---[-2]----/
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$v3 = $graph->createVertex(3);
$v4 = $graph->createVertex(4);
$graph->createEdgeUndirected($v1, $v2);
$graph->createEdgeDirected($v3, $v4)->setWeight(-1);
$graph->createEdgeDirected($v4, $v3)->setWeight(-2);
$alg = new DetectNegativeCycle($graph);
$this->assertTrue($alg->hasCycleNegative());
$cycle = $alg->getCycleNegative();
$this->assertCount(2, $cycle->getEdges());
$this->assertCount(3, $cycle->getVertices());
$this->assertTrue($cycle->getVertices()->hasVertexId(3));
$this->assertTrue($cycle->getVertices()->hasVertexId(4));
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/ResidualGraphTest.php | tests/ResidualGraphTest.php | <?php
namespace Graphp\Tests\Algorithms;
use Graphp\Algorithms\ResidualGraph;
use Graphp\Graph\Graph;
class ResidualGraphTest extends TestCase
{
public function testGraphEmpty()
{
$graph = new Graph();
$alg = new ResidualGraph($graph);
$residual = $alg->createGraph();
$this->assertGraphEquals($graph, $residual);
}
/**
* test an edge with capacity unused
*/
public function testEdgeUnused()
{
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex(0), $graph->createVertex(1))->setFlow(0)
->setCapacity(2)
->setWeight(3);
$alg = new ResidualGraph($graph);
$residual = $alg->createGraph();
$this->assertGraphEquals($graph, $residual);
}
/**
* test an edge with capacity completely used
*/
public function testEdgeUsed()
{
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex(0), $graph->createVertex(1))->setFlow(2)
->setCapacity(2)
->setWeight(3);
$alg = new ResidualGraph($graph);
$residual = $alg->createGraph();
$expected = new Graph();
$expected->createEdgeDirected($expected->createVertex(1), $expected->createVertex(0))->setFlow(0)
->setCapacity(2)
->setWeight(-3);
$this->assertGraphEquals($expected, $residual);
}
/**
* test an edge with capacity remaining
*/
public function testEdgePartial()
{
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex(0), $graph->createVertex(1))->setFlow(1)
->setCapacity(2)
->setWeight(3);
$alg = new ResidualGraph($graph);
$residual = $alg->createGraph();
$expected = new Graph();
$expected->createVertex(0);
$expected->createVertex(1);
// remaining edge
$expected->createEdgeDirected($expected->getVertex(0), $expected->getVertex(1))->setFlow(0)
->setCapacity(1)
->setWeight(3);
// back edge
$expected->createEdgeDirected($expected->getVertex(1), $expected->getVertex(0))->setFlow(0)
->setCapacity(1)
->setWeight(-3);
$this->assertGraphEquals($expected, $residual);
}
public function testResidualGraphCanOptionallyKeepNullCapacityForEdgeWithZeroFlow()
{
// 1 -[0/2]-> 2
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$graph->createEdgeDirected($v1, $v2)->setFlow(0)->setCapacity(2);
// 1 -[0/2]-> 2
// ^ |
// \--[0/0]---/
$expected = new Graph();
$v1 = $expected->createVertex(1);
$v2 = $expected->createVertex(2);
$expected->createEdgeDirected($v1, $v2)->setFlow(0)->setCapacity(2);
$expected->createEdgeDirected($v2, $v1)->setFlow(0)->setCapacity(0);
$alg = new ResidualGraph($graph);
$alg->setKeepNullCapacity(true);
$residual = $alg->createGraph();
$this->assertGraphEquals($expected, $residual);
}
public function testResidualGraphCanOptionallyKeepNullCapacityForEdgeWithZeroCapacityRemaining()
{
// 1 -[2/2]-> 2
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$graph->createEdgeDirected($v1, $v2)->setFlow(2)->setCapacity(2);
// 1 -[0/0]-> 2
// ^ |
// \--[0/2]---/
$expected = new Graph();
$v1 = $expected->createVertex(1);
$v2 = $expected->createVertex(2);
$expected->createEdgeDirected($v1, $v2)->setFlow(0)->setCapacity(0);
$expected->createEdgeDirected($v2, $v1)->setFlow(0)->setCapacity(2);
$alg = new ResidualGraph($graph);
$alg->setKeepNullCapacity(true);
$residual = $alg->createGraph();
$this->assertGraphEquals($expected, $residual);
}
public function testParallelEdgesCanBeMerged()
{
// 1 -[1/2]-> 2
// | ^
// \--[2/3]---/
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$graph->createEdgeDirected($v1, $v2)->setFlow(1)->setCapacity(2);
$graph->createEdgeDirected($v1, $v2)->setFlow(2)->setCapacity(3);
// 1 -[0/2]-> 2
// ^ |
// \--[0/3]---/
$expected = new Graph();
$v1 = $expected->createVertex(1);
$v2 = $expected->createVertex(2);
$expected->createEdgeDirected($v1, $v2)->setFlow(0)->setCapacity(2);
$expected->createEdgeDirected($v2, $v1)->setFlow(0)->setCapacity(3);
$alg = new ResidualGraph($graph);
$alg->setMergeParallelEdges(true);
$residual = $alg->createGraph();
$this->assertGraphEquals($expected, $residual);
}
/**
* expect exception for undirected edges
*/
public function testInvalidUndirected()
{
$graph = new Graph();
$graph->createEdgeUndirected($graph->createVertex(), $graph->createVertex())->setFlow(1)
->setCapacity(2);
$alg = new ResidualGraph($graph);
$this->setExpectedException('UnexpectedValueException');
$alg->createGraph();
}
/**
* expect exception for edges with no flow
*/
public function testInvalidNoFlow()
{
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex(), $graph->createVertex())->setCapacity(1);
$alg = new ResidualGraph($graph);
$this->setExpectedException('UnexpectedValueException');
$alg->createGraph();
}
/**
* expect exception for edges with no capacity
*/
public function testInvalidNoCapacity()
{
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex(), $graph->createVertex())->setFlow(1);
$alg = new ResidualGraph($graph);
$this->setExpectedException('UnexpectedValueException');
$alg->createGraph();
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/LoopTest.php | tests/LoopTest.php | <?php
namespace Graphp\Tests\Algorithms;
use Graphp\Algorithms\Loop as AlgorithmLoop;
use Graphp\Graph\Graph;
class LoopTest extends TestCase
{
public function testGraphEmpty()
{
$graph = new Graph();
$alg = new AlgorithmLoop($graph);
$this->assertFalse($alg->hasLoop());
}
public function testGraphWithMixedCircuitIsNotConsideredLoop()
{
// 1 -> 2
// 2 -- 1
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$graph->createEdgeDirected($v1, $v2);
$graph->createEdgeUndirected($v2, $v1);
$alg = new AlgorithmLoop($graph);
$this->assertFalse($alg->hasLoop());
$this->assertFalse($alg->hasLoopVertex($v1));
$this->assertFalse($alg->hasLoopVertex($v2));
}
public function testGraphUndirectedLoop()
{
// 1 -- 1
$graph = new Graph();
$graph->createEdgeUndirected($graph->createVertex(1), $v1 = $graph->getVertex(1));
$alg = new AlgorithmLoop($graph);
$this->assertTrue($alg->hasLoop());
$this->assertTrue($alg->hasLoopVertex($v1));
}
public function testGraphDirectedLoop()
{
// 1 -> 1
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex(1), $v1 = $graph->getVertex(1));
$alg = new AlgorithmLoop($graph);
$this->assertTrue($alg->hasLoop());
$this->assertTrue($alg->hasLoopVertex($v1));
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/ParallelTest.php | tests/ParallelTest.php | <?php
namespace Graphp\Tests\Algorithms;
use Graphp\Algorithms\Parallel as AlgorithmParallel;
use Graphp\Graph\Graph;
class ParallelTest extends TestCase
{
public function testGraphEmpty()
{
$graph = new Graph();
$alg = new AlgorithmParallel($graph);
$this->assertFalse($alg->hasEdgeParallel());
}
public function testDirectedCycleIsNotConsideredParallel()
{
// 1 -> 2
// 2 -> 1
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$e1 = $graph->createEdgeDirected($v1, $v2);
$e2 = $graph->createEdgeDirected($v2, $v1);
$alg = new AlgorithmParallel($graph);
$this->assertFalse($alg->hasEdgeParallel());
$this->assertEquals(array(), $alg->getEdgesParallelEdge($e1)->getVector());
$this->assertEquals(array(), $alg->getEdgesParallelEdge($e2)->getVector());
}
public function testDirectedParallelEdge()
{
// 1 -> 2
// 1 -> 2
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$e1 = $graph->createEdgeDirected($v1, $v2);
$e2 = $graph->createEdgeDirected($v1, $v2);
$alg = new AlgorithmParallel($graph);
$this->assertTrue($alg->hasEdgeParallel());
$this->assertEquals(array($e2), $alg->getEdgesParallelEdge($e1)->getVector());
$this->assertEquals(array($e1), $alg->getEdgesParallelEdge($e2)->getVector());
}
public function testMixedParallelEdge()
{
// 1 -> 2
// 1 -- 2
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$e1 = $graph->createEdgeDirected($v1, $v2);
$e2 = $graph->createEdgeUndirected($v1, $v2);
$alg = new AlgorithmParallel($graph);
$this->assertTrue($alg->hasEdgeParallel());
$this->assertEquals(array($e2), $alg->getEdgesParallelEdge($e1)->getVector());
$this->assertEquals(array($e1), $alg->getEdgesParallelEdge($e2)->getVector());
}
public function testMixedParallelEdgesMultiple()
{
// 1 -> 2
// 1 -> 2
// 1 -- 2
// 1 -- 2
// 2 -> 1
// 2 -> 1
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$e1 = $graph->createEdgeDirected($v1, $v2);
$e2 = $graph->createEdgeDirected($v1, $v2);
$e3 = $graph->createEdgeUndirected($v1, $v2);
$e4 = $graph->createEdgeUndirected($v1, $v2);
$e5 = $graph->createEdgeDirected($v2, $v1);
$e6 = $graph->createEdgeDirected($v2, $v1);
$alg = new AlgorithmParallel($graph);
$this->assertTrue($alg->hasEdgeParallel());
$this->assertEquals(array($e2, $e3, $e4), $alg->getEdgesParallelEdge($e1)->getVector());
$this->assertEquals(array($e1, $e3, $e4), $alg->getEdgesParallelEdge($e2)->getVector());
$this->assertEquals(array($e1, $e2, $e4, $e5, $e6), $alg->getEdgesParallelEdge($e3)->getVector());
$this->assertEquals(array($e1, $e2, $e3, $e5, $e6), $alg->getEdgesParallelEdge($e4)->getVector());
$this->assertEquals(array($e3, $e4, $e6), $alg->getEdgesParallelEdge($e5)->getVector());
$this->assertEquals(array($e3, $e4, $e5), $alg->getEdgesParallelEdge($e6)->getVector());
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/WeightTest.php | tests/WeightTest.php | <?php
namespace Graphp\Tests\Algorithms;
use Graphp\Algorithms\Weight as AlgorithmWeight;
use Graphp\Graph\Graph;
class WeightTest extends TestCase
{
public function testGraphEmpty()
{
$graph = new Graph();
$alg = new AlgorithmWeight($graph);
$this->assertEquals(null, $alg->getWeight());
$this->assertEquals(0, $alg->getWeightFlow());
$this->assertEquals(null, $alg->getWeightMin());
$this->assertFalse($alg->isWeighted());
return $graph;
}
/**
*
* @param Graph $graph
* @depends testGraphEmpty
*/
public function testGraphSimple(Graph $graph)
{
// 1 -> 2
$graph->createEdgeDirected($graph->createVertex(1), $graph->createVertex(2))->setWeight(3)->setFlow(4);
$alg = new AlgorithmWeight($graph);
$this->assertEquals(3, $alg->getWeight());
$this->assertEquals(12, $alg->getWeightFlow());
$this->assertEquals(3, $alg->getWeightMin());
$this->assertTrue($alg->isWeighted());
return $graph;
}
/**
*
* @param Graph $graph
* @depends testGraphSimple
*/
public function testGraphWithUnweightedEdges(Graph $graph)
{
$graph->createEdgeDirected($graph->createVertex(5), $graph->createVertex(6))->setFlow(7);
$alg = new AlgorithmWeight($graph);
$this->assertEquals(3, $alg->getWeight());
$this->assertEquals(12, $alg->getWeightFlow());
$this->assertEquals(3, $alg->getWeightMin());
$this->assertTrue($alg->isWeighted());
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/DirectedTest.php | tests/DirectedTest.php | <?php
namespace Graphp\Tests\Algorithms;
use Graphp\Algorithms\Directed as AlgorithmDirected;
use Graphp\Graph\Graph;
class DirectedTest extends TestCase
{
public function testGraphEmpty()
{
$graph = new Graph();
$alg = new AlgorithmDirected($graph);
$this->assertFalse($alg->hasDirected());
$this->assertFalse($alg->hasUndirected());
$this->assertFalse($alg->isMixed());
}
public function testGraphUndirected()
{
// 1 -- 2
$graph = new Graph();
$graph->createEdgeUndirected($graph->createVertex(1), $graph->createVertex(2));
$alg = new AlgorithmDirected($graph);
$this->assertFalse($alg->hasDirected());
$this->assertTrue($alg->hasUndirected());
$this->assertFalse($alg->isMixed());
}
public function testGraphDirected()
{
// 1 -> 2
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex(1), $graph->createVertex(2));
$alg = new AlgorithmDirected($graph);
$this->assertTrue($alg->hasDirected());
$this->assertFalse($alg->hasUndirected());
$this->assertFalse($alg->isMixed());
}
public function testGraphMixed()
{
// 1 -- 2 -> 3
$graph = new Graph();
$graph->createEdgeUndirected($graph->createVertex(1), $graph->createVertex(2));
$graph->createEdgeDirected($graph->getVertex(2), $graph->createVertex(3));
$alg = new AlgorithmDirected($graph);
$this->assertTrue($alg->hasDirected());
$this->assertTrue($alg->hasUndirected());
$this->assertTrue($alg->isMixed());
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/EulerianTest.php | tests/EulerianTest.php | <?php
namespace Graphp\Tests\Algorithms;
use Graphp\Algorithms\Eulerian as AlgorithmEulerian;
use Graphp\Graph\Graph;
class EulerianTest extends TestCase
{
public function testGraphEmpty()
{
$graph = new Graph();
$alg = new AlgorithmEulerian($graph);
$this->assertFalse($alg->hasCycle());
}
public function testGraphPairHasNoCycle()
{
// 1 -- 2
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$graph->createEdgeUndirected($v1, $v2);
$alg = new AlgorithmEulerian($graph);
$this->assertFalse($alg->hasCycle());
}
public function testGraphTriangleCycleIsNotBipartit()
{
// 1 -- 2 -- 3 -- 1
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$v3 = $graph->createVertex(3);
$graph->createEdgeUndirected($v1, $v2);
$graph->createEdgeUndirected($v2, $v3);
$graph->createEdgeUndirected($v3, $v1);
$alg = new AlgorithmEulerian($graph);
$this->assertTrue($alg->hasCycle());
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/GroupsTest.php | tests/GroupsTest.php | <?php
namespace Graphp\Tests\Algorithms;
use Graphp\Algorithms\Groups as AlgorithmGroups;
use Graphp\Graph\Graph;
class GroupsTest extends TestCase
{
public function testGraphEmpty()
{
$graph = new Graph();
$alg = new AlgorithmGroups($graph);
$this->assertEquals(array(), $alg->getGroups());
$this->assertEquals(0, $alg->getNumberOfGroups());
$this->assertTrue($alg->getVerticesGroup(123)->isEmpty());
$this->assertFalse($alg->isBipartit());
}
public function testGraphPairIsBipartit()
{
// 1 -> 2
$graph = new Graph();
$v1 = $graph->createVertex(1)->setGroup(1);
$v2 = $graph->createVertex(2)->setGroup(2);
$graph->createEdgeDirected($v1, $v2);
$alg = new AlgorithmGroups($graph);
$this->assertEquals(array(1, 2), $alg->getGroups());
$this->assertEquals(2, $alg->getNumberOfGroups());
$this->assertTrue($alg->getVerticesGroup(123)->isEmpty());
$this->assertEquals(array(1 => $v1), $alg->getVerticesGroup(1)->getMap());
$this->assertTrue($alg->isBipartit());
}
public function testGraphTriangleCycleIsNotBipartit()
{
// 1 -> 2 -> 3 -> 1
$graph = new Graph();
$v1 = $graph->createVertex(1)->setGroup(1);
$v2 = $graph->createVertex(2)->setGroup(2);
$v3 = $graph->createVertex(3)->setGroup(1);
$graph->createEdgeDirected($v1, $v2);
$graph->createEdgeDirected($v2, $v3);
$graph->createEdgeDirected($v3, $v1);
$alg = new AlgorithmGroups($graph);
$this->assertEquals(array(1, 2), $alg->getGroups());
$this->assertEquals(2, $alg->getNumberOfGroups());
$this->assertTrue($alg->getVerticesGroup(123)->isEmpty());
$this->assertEquals(array(1 => $v1, 3 => $v3), $alg->getVerticesGroup(1)->getMap());
$this->assertFalse($alg->isBipartit());
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/TopologicalSortTest.php | tests/TopologicalSortTest.php | <?php
namespace Graphp\Tests\Algorithms;
use Graphp\Algorithms\TopologicalSort;
use Graphp\Graph\Graph;
class TopologicalSortTest extends TestCase
{
public function testGraphEmpty()
{
$graph = new Graph();
$alg = new TopologicalSort($graph);
$this->assertInstanceOf('Graphp\Graph\Set\Vertices', $alg->getVertices());
$this->assertTrue($alg->getVertices()->isEmpty());
}
public function testGraphIsolated()
{
$graph = new Graph();
$graph->createVertex(1);
$graph->createVertex(2);
$alg = new TopologicalSort($graph);
$this->assertSame(array($graph->getVertex(1), $graph->getVertex(2)), $alg->getVertices()->getVector());
}
public function testGraphSimple()
{
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex(1), $graph->createVertex(2));
$alg = new TopologicalSort($graph);
$this->assertSame(array($graph->getVertex(1), $graph->getVertex(2)), $alg->getVertices()->getVector());
}
public function testFailUndirected()
{
$graph = new Graph();
$graph->createEdgeUndirected($graph->createVertex(1), $graph->createVertex(2));
$alg = new TopologicalSort($graph);
$this->setExpectedException('UnexpectedValueException');
$alg->getVertices();
}
public function testFailLoop()
{
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex(1), $graph->getVertex(1));
$alg = new TopologicalSort($graph);
$this->setExpectedException('UnexpectedValueException');
$alg->getVertices();
}
public function testFailCycle()
{
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex(1), $graph->createVertex(2));
$graph->createEdgeDirected($graph->getVertex(2), $graph->getVertex(1));
$alg = new TopologicalSort($graph);
$this->setExpectedException('UnexpectedValueException');
$alg->getVertices();
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/FlowTest.php | tests/FlowTest.php | <?php
namespace Graphp\Tests\Algorithms;
use Graphp\Algorithms\Flow as AlgorithmFlow;
use Graphp\Graph\Graph;
class FlowTest extends TestCase
{
public function testGraphEmpty()
{
$graph = new Graph();
$alg = new AlgorithmFlow($graph);
$this->assertFalse($alg->hasFlow());
$this->assertEquals(0, $alg->getBalance());
$this->assertTrue($alg->isBalancedFlow());
return $graph;
}
public function testEdgeWithZeroFlowIsConsideredFlow()
{
// 1 -> 2
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex(1), $graph->createVertex(2))->setFlow(0);
$alg = new AlgorithmFlow($graph);
$this->assertTrue($alg->hasFlow());
$this->assertEquals(0, $alg->getFlowVertex($graph->getVertex(1)));
$this->assertEquals(0, $alg->getFlowVertex($graph->getVertex(2)));
}
/**
*
* @param Graph $graph
* @depends testGraphEmpty
*/
public function testGraphSimple(Graph $graph)
{
// 1 -> 2
$graph->createEdgeDirected($graph->createVertex(1), $graph->createVertex(2));
$alg = new AlgorithmFlow($graph);
$this->assertFalse($alg->hasFlow());
$this->assertEquals(0, $alg->getFlowVertex($graph->getVertex(1)));
$this->assertEquals(0, $alg->getFlowVertex($graph->getVertex(2)));
return $graph;
}
/**
*
* @param Graph $graph
* @depends testGraphSimple
*/
public function testGraphWithUnweightedEdges(Graph $graph)
{
// additional flow edge: 2 -> 3
$graph->createEdgeDirected($graph->getVertex(2), $graph->createVertex(3))->setFlow(10);
$alg = new AlgorithmFlow($graph);
$this->assertTrue($alg->hasFlow());
$this->assertEquals(10, $alg->getFlowVertex($graph->getVertex(2)));
$this->assertEquals(-10, $alg->getFlowVertex($graph->getVertex(3)));
}
public function testGraphBalance()
{
// source(+100) -> sink(-10)
$graph = new Graph();
$graph->createVertex('source')->setBalance(100);
$graph->createVertex('sink')->setBalance(-10);
$alg = new AlgorithmFlow($graph);
$this->assertEquals(90, $alg->getBalance());
$this->assertFalse($alg->isBalancedFlow());
}
public function testVertexWithUndirectedEdgeHasInvalidFlow()
{
// 1 -- 2
$graph = new Graph();
$graph->createEdgeUndirected($graph->createVertex(1), $graph->createVertex(2))->setFlow(10);
$alg = new AlgorithmFlow($graph);
$this->setExpectedException('UnexpectedValueException');
$alg->getFlowVertex($graph->getVertex(1));
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/SymmetricTest.php | tests/SymmetricTest.php | <?php
namespace Graphp\Tests\Algorithms;
use Graphp\Algorithms\Symmetric as AlgorithmSymmetric;
use Graphp\Graph\Graph;
class SymmetricTest extends TestCase
{
public function testGraphEmpty()
{
$graph = new Graph();
$alg = new AlgorithmSymmetric($graph);
$this->assertTrue($alg->isSymmetric());
}
public function testGraphIsolated()
{
$graph = new Graph();
$graph->createVertex(1);
$graph->createVertex(2);
$alg = new AlgorithmSymmetric($graph);
$this->assertTrue($alg->isSymmetric());
}
public function testGraphSingleArcIsNotSymmetricr()
{
// 1 -> 2
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex(1), $graph->createVertex(2));
$alg = new AlgorithmSymmetric($graph);
$this->assertFalse($alg->isSymmetric());
}
public function testGraphAntiparallelIsSymmetricr()
{
// 1 -> 2 -> 1
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex(1), $graph->createVertex(2));
$graph->createEdgeDirected($graph->getVertex(2), $graph->getVertex(1));
$alg = new AlgorithmSymmetric($graph);
$this->assertTrue($alg->isSymmetric());
}
public function testGraphSingleUndirectedIsSymmetricr()
{
// 1 -- 2
$graph = new Graph();
$graph->createEdgeUndirected($graph->createVertex(1), $graph->createVertex(2));
$alg = new AlgorithmSymmetric($graph);
$this->assertTrue($alg->isSymmetric());
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/ShortestPath/DijkstraTest.php | tests/ShortestPath/DijkstraTest.php | <?php
namespace Graphp\Tests\Algorithms\ShortestPath;
use Graphp\Algorithms\ShortestPath\Dijkstra;
use Graphp\Graph\Graph;
use Graphp\Graph\Vertex;
class DijkstraTest extends BaseShortestPathTest
{
protected function createAlg(Vertex $vertex)
{
return new Dijkstra($vertex);
}
public function testGraphParallelNegative()
{
// 1 -[10]-> 2
// | ^
// \--[-1]---/
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$graph->createEdgeDirected($v1, $v2)->setWeight(10);
$graph->createEdgeDirected($v1, $v2)->setWeight(-1);
$alg = $this->createAlg($v1);
$this->setExpectedException('UnexpectedValueException');
$alg->getEdges();
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/ShortestPath/BreadthFirstTest.php | tests/ShortestPath/BreadthFirstTest.php | <?php
namespace Graphp\Tests\Algorithms\ShortestPath;
use Graphp\Algorithms\ShortestPath\BreadthFirst;
use Graphp\Graph\Graph;
use Graphp\Graph\Vertex;
class BreadthFirstTest extends BaseShortestPathTest
{
protected function createAlg(Vertex $vertex)
{
return new BreadthFirst($vertex);
}
public function testGraphParallelNegative()
{
// 1 -[10]-> 2
// | ^
// \--[-1]---/
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$e1 = $graph->createEdgeDirected($v1, $v2)->setWeight(10);
$graph->createEdgeDirected($v1, $v2)->setWeight(-1);
$alg = $this->createAlg($v1);
$this->assertEquals(1, $alg->getDistance($v2));
$this->assertEquals(array(2 => 1), $alg->getDistanceMap());
$this->assertEquals(array($e1), $alg->getEdges()->getVector());
$this->assertEquals(array($e1), $alg->getEdgesTo($v2)->getVector());
$this->assertEquals(array(2 => $v2), $alg->getVertices()->getMap());
$this->assertEquals(array(2), $alg->getVertices()->getIds());
}
protected function getExpectedWeight($edges)
{
return \count($edges);
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/ShortestPath/BaseShortestPathTest.php | tests/ShortestPath/BaseShortestPathTest.php | <?php
namespace Graphp\Tests\Algorithms\ShortestPath;
use Graphp\Algorithms\ShortestPath\Base as ShortestPathAlg;
use Graphp\Graph\Graph;
use Graphp\Graph\Vertex;
use Graphp\Tests\Algorithms\TestCase;
abstract class BaseShortestPathTest extends TestCase
{
/**
*
* @param Vertex $vertex
* @return ShortestPathAlg
*/
abstract protected function createAlg(Vertex $vertex);
abstract public function testGraphParallelNegative();
public function testGraphTrivial()
{
// 1
$graph = new Graph();
$v1 = $graph->createVertex(1);
$alg = $this->createAlg($v1);
$this->assertFalse($alg->hasVertex($v1));
//$this->assertEquals(0, $alg->getDistance($v1));
$this->assertEquals(array(), $alg->getDistanceMap());
$this->assertEquals(array(), $alg->getEdges()->getVector());
//$this->assertEquals(array(), $alg->getEdgesTo($v1));
$this->assertEquals(array(), $alg->getVertices()->getVector());
$this->assertEquals(array(), $alg->getVertices()->getIds());
$clone = $alg->createGraph();
$this->assertGraphEquals($graph,$clone);
}
public function testGraphSingleLoop()
{
// 1 -[4]> 1
$graph = new Graph();
$v1 = $graph->createVertex(1);
$e1 = $graph->createEdgeDirected($v1, $v1)->setWeight(4);
$alg = $this->createAlg($v1);
$this->assertEquals(array($e1), $alg->getEdges()->getVector());
$expectedWeight = $this->getExpectedWeight(array($e1));
$this->assertTrue($alg->hasVertex($v1));
$this->assertEquals($expectedWeight, $alg->getDistance($v1));
$this->assertEquals(array(1 => $expectedWeight), $alg->getDistanceMap());
$this->assertEquals(array($e1), $alg->getEdgesTo($v1)->getVector());
$this->assertEquals(array(1 => $v1), $alg->getVertices()->getMap());
$this->assertEquals(array(1), $alg->getVertices()->getIds());
}
public function testGraphCycle()
{
// 1 -[4]-> 2 -[2]-> 1
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$e1 = $graph->createEdgeDirected($v1, $v2)->setWeight(4);
$e2 = $graph->createEdgeDirected($v2, $v1)->setWeight(2);
$alg = $this->createAlg($v1);
//$this->assertEquals(array($e2, $e1), $alg->getEdges());
$expectedWeight = $this->getExpectedWeight(array($e1));
$this->assertTrue($alg->hasVertex($v2));
$this->assertEquals(array($e1), $alg->getEdgesTo($v2)->getVector());
$this->assertEquals($expectedWeight, $alg->getDistance($v2));
$expectedWeight = $this->getExpectedWeight(array($e1, $e2));
$this->assertTrue($alg->hasVertex($v1));
$this->assertEquals(array($e1, $e2), $alg->getEdgesTo($v1)->getVector());
$this->assertEquals($expectedWeight, $alg->getDistance($v1));
$walk = $alg->getWalkTo($v1);
$this->assertCount(2, $walk->getEdges());
}
public function testIsolatedVertexIsNotReachable()
{
// 1, 2
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$alg = $this->createAlg($v1);
$this->assertFalse($alg->hasVertex($v2));
$this->setExpectedException('OutOfBoundsException');
$alg->getEdgesTo($v2);
}
public function testSeparateGraphsAreNotReachable()
{
// 1
$graph1 = new Graph();
$vg1 = $graph1->createVertex(1);
$graph2 = new Graph();
$vg2 = $graph2->createVertex(1);
$alg = $this->createAlg($vg1);
$this->setExpectedException('OutOfBoundsException');
$alg->getEdgesTo($vg2);
}
public function testGraphUnweighted()
{
// 1 -> 2
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$e1 = $graph->createEdgeDirected($v1, $v2);
$alg = $this->createAlg($v1);
$expectedWeight = $this->getExpectedWeight(array($e1));
$this->assertEquals($expectedWeight, $alg->getDistance($v2));
$this->assertEquals(array(2 => $expectedWeight), $alg->getDistanceMap());
$this->assertEquals(array($e1), $alg->getEdges()->getVector());
$this->assertEquals(array($e1), $alg->getEdgesTo($v2)->getVector());
$this->assertEquals(array(2), $alg->getVertices()->getIds());
}
public function testGraphTwoComponents()
{
// 1 -[10]-> 2
// 3 -[20]-> 4
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$v3 = $graph->createVertex(3);
$v4 = $graph->createVertex(4);
$e1 = $graph->createEdgeDirected($v1, $v2)->setWeight(10);
$graph->createEdgeDirected($v3, $v4)->setWeight(20);
$alg = $this->createAlg($v1);
$expectedWeight = $this->getExpectedWeight(array($e1));
$this->assertEquals($expectedWeight, $alg->getDistance($v2));
$this->assertEquals(array(2 => $expectedWeight), $alg->getDistanceMap());
$this->assertEquals(array($e1), $alg->getEdges()->getVector());
// $this->assertEquals(array(), $alg->getEdgesTo($v1));
$this->assertEquals(array($e1), $alg->getEdgesTo($v2)->getVector());
$this->assertEquals(array(2 => $v2), $alg->getVertices()->getMap());
$this->assertEquals(array(2), $alg->getVertices()->getIds());
}
protected function getExpectedWeight($edges)
{
$sum = 0;
foreach ($edges as $edge) {
$sum += $edge->getWeight();
}
return $sum;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/ShortestPath/MooreBellmanFordTest.php | tests/ShortestPath/MooreBellmanFordTest.php | <?php
namespace Graphp\Tests\Algorithms\ShortestPath;
use Graphp\Algorithms\ShortestPath\MooreBellmanFord;
use Graphp\Graph\Graph;
use Graphp\Graph\Vertex;
class MooreBellmanFordTest extends BaseShortestPathTest
{
protected function createAlg(Vertex $vertex)
{
return new MooreBellmanFord($vertex);
}
public function testGraphParallelNegative()
{
// 1 -[10]-> 2
// | ^
// \--[-1]---/
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$graph->createEdgeDirected($v1, $v2)->setWeight(10);
$e2 = $graph->createEdgeDirected($v1, $v2)->setWeight(-1);
$alg = $this->createAlg($v1);
// $this->assertEquals(0, $alg->getDistance($v1));
$this->assertEquals(-1, $alg->getDistance($v2));
$this->assertEquals(array(2 => -1), $alg->getDistanceMap());
$this->assertEquals(array($e2), $alg->getEdges()->getVector());
//$this->assertEquals(array(), $alg->getEdgesTo($v1));
$this->assertEquals(array($e2), $alg->getEdgesTo($v2)->getVector());
$this->assertEquals(array(2 => $v2), $alg->getVertices()->getMap());
$this->assertEquals(array(2), $alg->getVertices()->getIds());
return $alg;
}
/**
* @param MooreBellmanFord $alg
* @depends testGraphParallelNegative
*/
public function testNoNegativeCycle(MooreBellmanFord $alg)
{
$this->setExpectedException('UnderflowException');
$alg->getCycleNegative();
}
public function testUndirectedNegativeWeightIsCycle()
{
// 1 -[-10]- 2
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$graph->createEdgeUndirected($v1, $v2)->setWeight(-10);
$alg = $this->createAlg($v1);
$cycle = $alg->getCycleNegative();
$this->assertInstanceOf('Graphp\Graph\Walk', $cycle);
}
public function testLoopNegativeWeightIsCycle()
{
// 1 -[-10]-> 1
$graph = new Graph();
$v1 = $graph->createVertex(1);
$graph->createEdgeUndirected($v1, $v1)->setWeight(-10);
$alg = $this->createAlg($v1);
$cycle = $alg->getCycleNegative();
$this->assertInstanceOf('Graphp\Graph\Walk', $cycle);
}
public function testNegativeComponentHasCycle()
{
// 1 -[1]-> 2 3 --[-1]--> 4
// ^ |
// \---[-2]----/
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$v3 = $graph->createVertex(3);
$v4 = $graph->createVertex(4);
$graph->createEdgeDirected($v1, $v2)->setWeight(1);
$graph->createEdgeDirected($v3, $v4)->setWeight(-1);
$graph->createEdgeDirected($v4, $v3)->setWeight(-2);
// second component has a cycle
$alg = $this->createAlg($v3);
$cycle = $alg->getCycleNegative();
assert(isset($cycle));
// first component does not have a cycle
$alg = $this->createAlg($v1);
$this->setExpectedException('UnderflowException');
$alg->getCycleNegative();
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/MinimumCostFlow/CycleCancellingTest.php | tests/MinimumCostFlow/CycleCancellingTest.php | <?php
namespace Graphp\Tests\Algorithms\MinimumCostFlow;
use Graphp\Algorithms\MinimumCostFlow\CycleCanceling;
use Graphp\Graph\Graph;
class CycleCancellingTest extends BaseMcfTest
{
protected function createAlgorithm(Graph $graph)
{
return new CycleCanceling($graph);
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/MinimumCostFlow/BaseMcfTest.php | tests/MinimumCostFlow/BaseMcfTest.php | <?php
namespace Graphp\Tests\Algorithms\MinimumCostFlow;
use Graphp\Algorithms\MinimumCostFlow\Base;
use Graphp\Graph\Graph;
use Graphp\Tests\Algorithms\TestCase;
abstract class BaseMcfTest extends TestCase
{
/**
*
* @param Graph $graph
* @return Base
*/
abstract protected function createAlgorithm(Graph $graph);
public function testNull()
{
$graph = new Graph();
$alg = $this->createAlgorithm($graph);
$this->assertEquals(0, $alg->getWeightFlow());
}
public function testSingleIntermediary()
{
$graph = new Graph();
$graph->createVertex(1);
$alg = $this->createAlgorithm($graph);
$this->assertEquals(0, $alg->getWeightFlow());
}
public function testSimpleEdge()
{
// 1(+2) -[0/2/2]-> 2(-2)
$graph = new Graph();
$v1 = $graph->createVertex(1)->setBalance(2);
$v2 = $graph->createVertex(2)->setBalance(-2);
$graph->createEdgeDirected($v1, $v2)->setWeight(2)->setCapacity(2);
$alg = $this->createAlgorithm($graph);
$this->assertEquals(4, $alg->getWeightFlow()); // 2x2
}
public function testMultipleSinks()
{
// 1(+2) -[0/2/2]-> 2(-1)
// -[0/4/-5]-> 3(-1)
$graph = new Graph();
$v1 = $graph->createVertex(1)->setBalance(2);
$v2 = $graph->createVertex(2)->setBalance(-1);
$v3 = $graph->createVertex(3)->setBalance(-1);
$graph->createEdgeDirected($v1, $v2)->setWeight(2)->setCapacity(2);
$graph->createEdgeDirected($v1, $v3)->setWeight(-5)->setCapacity(4);
$alg = $this->createAlgorithm($graph);
$this->assertEquals(-3, $alg->getWeightFlow()); // 1*2 + 1*-5
}
public function testIntermediaryVertices()
{
// 1(+2) -[0/1/4]-> 2 -[0/6/-2]-> 4(-2)
// -[0/4/5]-> 3 -[0/6/8]->
$graph = new Graph();
$v1 = $graph->createVertex(1)->setBalance(2);
$v2 = $graph->createVertex(2);
$v3 = $graph->createVertex(3);
$v4 = $graph->createVertex(4)->setBalance(-2);
$graph->createEdgeDirected($v1, $v2)->setWeight(4)->setCapacity(1);
$graph->createEdgeDirected($v2, $v4)->setWeight(-2)->setCapacity(6);
$graph->createEdgeDirected($v1, $v3)->setWeight(5)->setCapacity(4);
$graph->createEdgeDirected($v3, $v4)->setWeight(8)->setCapacity(6);
$alg = $this->createAlgorithm($graph);
$this->assertEquals(15, $alg->getWeightFlow()); // 1*4 + 1*-2 + 1*5 + 1*8
}
public function testEdgeCapacities()
{
// 1(+2) -[0/3/4]-> 2 -[0/4/5]-> 3 ->[0/6/-2]-> 4(-2)
$graph = new Graph();
$v1 = $graph->createVertex(1)->setBalance(2);
$v2 = $graph->createVertex(2);
$v3 = $graph->createVertex(3);
$v4 = $graph->createVertex(4)->setBalance(-2);
$graph->createEdgeDirected($v1, $v2)->setWeight(4)->setCapacity(3);
$graph->createEdgeDirected($v2, $v3)->setWeight(5)->setCapacity(4);
$graph->createEdgeDirected($v3, $v4)->setWeight(-2)->setCapacity(6);
$alg = $this->createAlgorithm($graph);
$this->assertEquals(14, $alg->getWeightFlow()); // 2*4 + 2*5 + 2*-2
}
public function testEdgeFlows()
{
// 1(+4) ---[3/4/2]---> 2 ---[3/3/3]---> 4(-4)
// | | ^
// | [0/2/1] |
// | ↓ |
// \-------[1/2/2]---> 3 ---[1/5/1]-------/
$graph = new Graph();
$v1 = $graph->createVertex(1)->setBalance(4);
$v2 = $graph->createVertex(2);
$v3 = $graph->createVertex(3);
$v4 = $graph->createVertex(4)->setBalance(-4);
$graph->createEdgeDirected($v1, $v2)->setFlow(3)->setCapacity(4)->setWeight(2);
$graph->createEdgeDirected($v2, $v4)->setFlow(3)->setCapacity(3)->setWeight(3);
$graph->createEdgeDirected($v1, $v3)->setFlow(1)->setCapacity(2)->setWeight(2);
$graph->createEdgeDirected($v3, $v4)->setFlow(1)->setCapacity(5)->setWeight(1);
$graph->createEdgeDirected($v2, $v3)->setFlow(0)->setCapacity(2)->setWeight(1);
$alg = $this->createAlgorithm($graph);
$this->assertEquals(14, $alg->getWeightFlow()); // 4*1 + 2*2 + 2*1 + 2*2
}
public function testEdgeCapacityInsufficientFails()
{
// 1(+2) -[0/1]-> 2(-2)
$graph = new Graph();
$v1 = $graph->createVertex(1)->setBalance(2);
$v2 = $graph->createVertex(2)->setBalance(-2);
$graph->createEdgeDirected($v1, $v2)->setCapacity(1);
$alg = $this->createAlgorithm($graph);
$this->setExpectedException('UnexpectedValueException');
$alg->getWeightFlow();
}
public function testEdgeCapacityUnsetFails()
{
// 1(+2) -> 2(-2)
$graph = new Graph();
$v1 = $graph->createVertex(1)->setBalance(2);
$v2 = $graph->createVertex(2)->setBalance(-2);
$graph->createEdgeDirected($v1, $v2);
$alg = $this->createAlgorithm($graph);
$this->setExpectedException('UnexpectedValueException');
$alg->getWeightFlow();
}
public function testIsolatedVerticesFail()
{
// 1(+2), 2(-2)
$graph = new Graph();
$graph->createVertex(1)->setBalance(2);
$graph->createVertex(2)->setBalance(-2);
$alg = $this->createAlgorithm($graph);
$this->setExpectedException('UnexpectedValueException');
$alg->getWeightFlow();
}
public function testUnbalancedFails()
{
// 1(+2) -> 2(-3)
$graph = new Graph();
$v1 = $graph->createVertex(1)->setBalance(2);
$v2 = $graph->createVertex(2)->setBalance(-3);
$graph->createEdgeDirected($v1, $v2)->setCapacity(3);
$alg = $this->createAlgorithm($graph);
$this->setExpectedException('UnexpectedValueException');
$alg->getWeightFlow();
}
public function testUndirectedFails()
{
// 1(+2) -- 2(-2)
$graph = new Graph();
$v1 = $graph->createVertex(1)->setBalance(2);
$v2 = $graph->createVertex(2)->setBalance(-2);
$graph->createEdgeUndirected($v1, $v2)->setCapacity(2);
$alg = $this->createAlgorithm($graph);
$this->setExpectedException('UnexpectedValueException');
$alg->getWeightFlow();
}
public function testUndirectedNegativeCycleFails()
{
// 1(+2) -[0/2/-1]- 2(-2)
$graph = new Graph();
$v1 = $graph->createVertex(1)->setBalance(2);
$v2 = $graph->createVertex(2)->setBalance(-2);
$graph->createEdgeUndirected($v1, $v2)->setCapacity(2)->setWeight(-1);
$alg = $this->createAlgorithm($graph);
$this->setExpectedException('UnexpectedValueException');
$alg->getWeightFlow();
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/MinimumCostFlow/SuccessiveShortestPathTest.php | tests/MinimumCostFlow/SuccessiveShortestPathTest.php | <?php
namespace Graphp\Tests\Algorithms\MinimumCostFlow;
use Graphp\Algorithms\MinimumCostFlow\SuccessiveShortestPath;
use Graphp\Graph\Graph;
class SuccessiveShortestPathTest extends BaseMcfTest
{
protected function createAlgorithm(Graph $graph)
{
return new SuccessiveShortestPath($graph);
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/TravelingSalesmanProblem/BruteforceTest.php | tests/TravelingSalesmanProblem/BruteforceTest.php | <?php
namespace Graphp\Tests\Algorithms\TravelingSalesmanProblem;
use Graphp\Algorithms\TravelingSalesmanProblem\Bruteforce;
use Graphp\Graph\Graph;
use Graphp\Tests\Algorithms\TestCase;
class BruteforceTest extends TestCase
{
public function testGetWeightReturnsExpectedWeightForSimpleCycle()
{
$graph = new Graph();
$a = $graph->createVertex();
$b = $graph->createVertex();
$c = $graph->createVertex();
$graph->createEdgeDirected($a, $b)->setWeight(1);
$graph->createEdgeDirected($b, $c)->setWeight(2);
$graph->createEdgeDirected($c, $a)->setWeight(3);
$alg = new Bruteforce($graph);
$this->assertEquals(6, $alg->getWeight());
}
public function testSetUpperLimitMstSetsExactLimitForSimpleCycle()
{
$graph = new Graph();
$a = $graph->createVertex();
$b = $graph->createVertex();
$c = $graph->createVertex();
$graph->createEdgeDirected($a, $b)->setWeight(1);
$graph->createEdgeDirected($b, $c)->setWeight(2);
$graph->createEdgeDirected($c, $a)->setWeight(3);
$alg = new Bruteforce($graph);
$alg->setUpperLimitMst();
$ref = new \ReflectionProperty($alg, 'upperLimit');
$ref->setAccessible(true);
$this->assertEquals(6, $ref->getValue($alg));
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/MaximumMatching/FlowTest.php | tests/MaximumMatching/FlowTest.php | <?php
namespace Graphp\Tests\Algorithms\MaximumMatching;
use Graphp\Algorithms\MaximumMatching\Flow;
use Graphp\Graph\Graph;
use Graphp\Tests\Algorithms\TestCase;
class FlowTest extends TestCase
{
// /**
// * run algorithm with small graph and check result against known result
// */
// public function testKnownResult()
// {
// $loader = new EdgeListBipartit(PATH_DATA . 'Matching_100_100.txt');
// $loader->setEnableDirectedEdges(false);
// $graph = $loader->createGraph();
// $alg = new Flow($graph);
// $this->assertEquals(100, $alg->getNumberOfMatches());
// }
public function testSingleEdge()
{
$graph = new Graph();
$edge = $graph->createEdgeUndirected($graph->createVertex(0)->setGroup(0), $graph->createVertex(1)->setGroup(1));
$alg = new Flow($graph);
// correct number of edges
$this->assertEquals(1, $alg->getNumberOfMatches());
// actual edge instance returned
$this->assertEquals(array($edge), $alg->getEdges()->getVector());
// check
$flowgraph = $alg->createGraph();
$this->assertInstanceOf('Graphp\Graph\Graph', $flowgraph);
}
/**
* expect exception for directed edges
*/
public function testInvalidDirected()
{
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex(0)->setGroup(0), $graph->createVertex(1)->setGroup(1));
$alg = new Flow($graph);
$this->setExpectedException('UnexpectedValueException');
$alg->getNumberOfMatches();
}
/**
* expect exception for non-bipartit graphs
*/
public function testInvalidBipartit()
{
$graph = new Graph();
$graph->createEdgeUndirected($graph->createVertex(0)->setGroup(1), $graph->createVertex(1)->setGroup(1));
$alg = new Flow($graph);
$this->setExpectedException('UnexpectedValueException');
$alg->getNumberOfMatches();
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/Tree/OutTreeTest.php | tests/Tree/OutTreeTest.php | <?php
namespace Graphp\Tests\Algorithms\Tree;
use Graphp\Algorithms\Tree\OutTree;
use Graphp\Graph\Graph;
class OutTreeTest extends BaseDirectedTest
{
protected function createGraphTree()
{
// c1 <- root -> c2
$graph = new Graph();
$root = $graph->createVertex();
$c1 = $graph->createVertex();
$graph->createEdgeDirected($root, $c1);
$c2 = $graph->createVertex();
$graph->createEdgeDirected($root, $c2);
return $graph;
}
protected function createTreeAlg(Graph $graph)
{
return new OutTree($graph);
}
protected function createGraphNonTree()
{
// v1 -> v3 <- v2 -> v4
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex('v1'), $graph->createVertex('v3'));
$graph->createEdgeDirected($graph->createVertex('v2'), $graph->getVertex('v3'));
$graph->createEdgeDirected($graph->getVertex('v2'), $graph->createVertex('v4'));
return $graph;
}
protected function createGraphParallelEdge()
{
// v1 -> v2, v1 -> v2
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex('v1'), $graph->createVertex('v2'));
$graph->createEdgeDirected($graph->getVertex('v1'), $graph->getVertex('v2'));
return $graph;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/Tree/InTreeTest.php | tests/Tree/InTreeTest.php | <?php
namespace Graphp\Tests\Algorithms\Tree;
use Graphp\Algorithms\Tree\InTree;
use Graphp\Graph\Graph;
class InTreeTest extends BaseDirectedTest
{
protected function createGraphTree()
{
// c1 -> root <- c2
$graph = new Graph();
$root = $graph->createVertex();
$c1 = $graph->createVertex();
$graph->createEdgeDirected($c1, $root);
$c2 = $graph->createVertex();
$graph->createEdgeDirected($c2, $root);
return $graph;
}
protected function createTreeAlg(Graph $graph)
{
return new InTree($graph);
}
protected function createGraphNonTree()
{
// v1 -> v2 <- v3 -> v4
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex('v1'), $graph->createVertex('v2'));
$graph->createEdgeDirected($graph->createVertex('v3'), $graph->getVertex('v2'));
$graph->createEdgeDirected($graph->getVertex('v3'), $graph->createVertex('v4'));
return $graph;
}
protected function createGraphParallelEdge()
{
// v1 <- v2, v1 <- v2
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex('v2'), $graph->createVertex('v1'));
$graph->createEdgeDirected($graph->getVertex('v2'), $graph->getVertex('v1'));
return $graph;
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/Tree/UndirectedTest.php | tests/Tree/UndirectedTest.php | <?php
namespace Graphp\Tests\Algorithms\Tree;
use Graphp\Algorithms\Tree\Undirected;
use Graphp\Graph\Graph;
use Graphp\Tests\Algorithms\TestCase;
class UndirectedTest extends TestCase
{
protected function createTree(Graph $graph)
{
return new Undirected($graph);
}
public function testNullGraph()
{
$graph = new Graph();
$tree = $this->createTree($graph);
$this->assertFalse($tree->isTree());
$this->assertTrue($tree->getVerticesInternal()->isEmpty());
$this->assertTrue($tree->getVerticesLeaf()->isEmpty());
}
public function testGraphTrivial()
{
$graph = new Graph();
$graph->createVertex('v1');
$tree = $this->createTree($graph);
$this->assertTrue($tree->isTree());
$this->assertSame(array(), $tree->getVerticesInternal()->getVector());
$this->assertSame(array(), $tree->getVerticesLeaf()->getVector());
}
public function testGraphSimplePair()
{
// v1 -- v2
$graph = new Graph();
$graph->createEdgeUndirected($graph->createVertex('v1'), $graph->createVertex('v2'));
$tree = $this->createTree($graph);
$this->assertTrue($tree->isTree());
$this->assertSame(array(), $tree->getVerticesInternal()->getVector());
$this->assertSame($graph->getVertices()->getVector(), $tree->getVerticesLeaf()->getVector());
}
public function testGraphSimpleLine()
{
// v1 -- v2 -- v3
$graph = new Graph();
$graph->createEdgeUndirected($graph->createVertex('v1'), $graph->createVertex('v2'));
$graph->createEdgeUndirected($graph->getVertex('v2'), $graph->createVertex('v3'));
$tree = $this->createTree($graph);
$this->assertTrue($tree->isTree());
$this->assertSame(array($graph->getVertex('v2')), $tree->getVerticesInternal()->getVector());
$this->assertSame(array($graph->getVertex('v1'), $graph->getVertex('v3')), $tree->getVerticesLeaf()->getVector());
}
public function testGraphPairParallelIsNotTree()
{
// v1 -- v2 -- v1
$graph = new Graph();
$graph->createEdgeUndirected($graph->createVertex('v1'), $graph->createVertex('v2'));
$graph->createEdgeUndirected($graph->getVertex('v1'), $graph->getVertex('v2'));
$tree = $this->createTree($graph);
$this->assertFalse($tree->isTree());
}
public function testGraphLoopIsNotTree()
{
// v1 -- v1
$graph = new Graph();
$graph->createEdgeUndirected($graph->createVertex('v1'), $graph->getVertex('v1'));
$tree = $this->createTree($graph);
$this->assertFalse($tree->isTree());
}
public function testGraphCycleIsNotTree()
{
// v1 -- v2 -- v3 -- v1
$graph = new Graph();
$graph->createEdgeUndirected($graph->createVertex('v1'), $graph->createVertex('v2'));
$graph->createEdgeUndirected($graph->getVertex('v2'), $graph->createVertex('v3'));
$graph->createEdgeUndirected($graph->getVertex('v3'), $graph->getVertex('v1'));
$tree = $this->createTree($graph);
$this->assertFalse($tree->isTree());
}
public function testGraphDirectedIsNotTree()
{
// v1 -> v2
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex('v1'), $graph->createVertex('v2'));
$tree = $this->createTree($graph);
$this->assertFalse($tree->isTree());
}
public function testGraphMixedIsNotTree()
{
// v1 -- v2 -> v3
$graph = new Graph();
$graph->createEdgeUndirected($graph->createVertex('v1'), $graph->createVertex('v2'));
$graph->createEdgeDirected($graph->getVertex('v2'), $graph->createVertex('v3'));
$tree = $this->createTree($graph);
$this->assertFalse($tree->isTree());
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/Tree/BaseDirectedTest.php | tests/Tree/BaseDirectedTest.php | <?php
namespace Graphp\Tests\Algorithms\Tree;
use Graphp\Algorithms\Tree\BaseDirected;
use Graphp\Graph\Graph;
use Graphp\Graph\Set\Vertices;
use Graphp\Tests\Algorithms\TestCase;
abstract class BaseDirectedTest extends TestCase
{
/**
*
* @param Graph $graph
* @return BaseDirected
*/
abstract protected function createTreeAlg(Graph $graph);
/**
* @return Graph
*/
abstract protected function createGraphNonTree();
/**
* @return Graph
*/
abstract protected function createGraphTree();
/**
* @return Graph
*/
abstract protected function createGraphParallelEdge();
public function testNullGraph()
{
$graph = new Graph();
$tree = $this->createTreeAlg($graph);
$this->assertFalse($tree->isTree());
$this->assertTrue($tree->getVerticesLeaf()->isEmpty());
$this->assertTrue($tree->getVerticesInternal()->isEmpty());
return $tree;
}
/**
* @param BaseDirected $tree
* @depends testNullGraph
*/
public function testEmptyGraphDoesNotHaveRootVertex(BaseDirected $tree)
{
$this->setExpectedException('UnderflowException');
$tree->getVertexRoot();
}
/**
* @param BaseDirected $tree
* @depends testNullGraph
*/
public function testEmptyGraphDoesNotHaveDegree(BaseDirected $tree)
{
$this->setExpectedException('UnderflowException');
$tree->getDegree();
}
/**
* @param BaseDirected $tree
* @depends testNullGraph
*/
public function testEmptyGraphDoesNotHaveHeight(BaseDirected $tree)
{
$this->setExpectedException('UnderflowException');
$tree->getHeight();
}
public function testGraphTree()
{
$graph = $this->createGraphTree();
$root = $graph->getVertices()->getVertexFirst();
$nonRoot = $graph->getVertices()->getMap();
unset($nonRoot[$root->getId()]);
$nonRoot = new Vertices($nonRoot);
$c1 = $nonRoot->getVertexFirst();
$tree = $this->createTreeAlg($graph);
$this->assertTrue($tree->isTree());
$this->assertSame($root, $tree->getVertexRoot());
$this->assertSame($graph->getVertices()->getVector(), $tree->getVerticesSubtree($root)->getVector());
$this->assertSame($nonRoot->getVector(), $tree->getVerticesChildren($root)->getVector());
$this->assertSame($nonRoot->getVector(), $tree->getVerticesDescendant($root)->getVector());
$this->assertSame($nonRoot->getVector(), $tree->getVerticesLeaf()->getVector());
$this->assertSame(array(), $tree->getVerticesInternal()->getVector());
$this->assertSame($root, $tree->getVertexParent($c1));
$this->assertSame(array(), $tree->getVerticesChildren($c1)->getVector());
$this->assertSame(array(), $tree->getVerticesDescendant($c1)->getVector());
$this->assertSame(array($c1), $tree->getVerticesSubtree($c1)->getVector());
$this->assertEquals(2, $tree->getDegree());
$this->assertEquals(0, $tree->getDepthVertex($root));
$this->assertEquals(1, $tree->getDepthVertex($c1));
$this->assertEquals(1, $tree->getHeight());
$this->assertEquals(1, $tree->getHeightVertex($root));
$this->assertEquals(0, $tree->getHeightvertex($c1));
return $tree;
}
/**
*
* @param BaseDirected $tree
* @depends testGraphTree
*/
public function testGraphTreeRootDoesNotHaveParent(BaseDirected $tree)
{
$root = $tree->getVertexRoot();
$this->setExpectedException('UnderflowException');
$tree->getVertexParent($root);
}
public function testNonTree()
{
$graph = $this->createGraphNonTree();
$tree = $this->createTreeAlg($graph);
$this->assertFalse($tree->isTree());
}
public function testNonTreeVertexHasMoreThanOneParent()
{
$graph = $this->createGraphNonTree();
$tree = $this->createTreeAlg($graph);
$this->setExpectedException('UnexpectedValueException');
$tree->getVertexParent($graph->getVertex('v3'));
}
public function testGraphWithParallelEdgeIsNotTree()
{
$graph = $this->createGraphParallelEdge();
$tree = $this->createTreeAlg($graph);
$this->assertFalse($tree->isTree());
}
public function testGraphWithLoopIsNotTree()
{
// v1 -> v1
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex('v1'), $graph->getVertex('v1'));
$tree = $this->createTreeAlg($graph);
$this->assertFalse($tree->isTree());
}
public function testGraphWithLoopCanNotGetSubgraph()
{
// v1 -> v1
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex('v1'), $graph->getVertex('v1'));
$tree = $this->createTreeAlg($graph);
$this->setExpectedException('UnexpectedValueException');
$tree->getVerticesSubtree($graph->getVertex('v1'));
}
public function testGraphWithUndirectedEdgeIsNotTree()
{
// v1 -- v2
$graph = new Graph();
$graph->createEdgeUndirected($graph->createVertex('v1'), $graph->createVertex('v2'));
$tree = $this->createTreeAlg($graph);
$this->assertFalse($tree->isTree());
}
public function testGraphWithMixedEdgesIsNotTree()
{
// v1 -> v2 -- v3 -> v4
$graph = new Graph();
$graph->createEdgeDirected($graph->createVertex('v1'), $graph->createVertex('v2'));
$graph->createEdgeUndirected($graph->getVertex('v2'), $graph->createVertex('v3'));
$graph->createEdgeDirected($graph->getVertex('v3'), $graph->createVertex('v4'));
$tree = $this->createTreeAlg($graph);
$this->assertFalse($tree->isTree());
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/MaxFlow/EdmondsKarpTest.php | tests/MaxFlow/EdmondsKarpTest.php | <?php
namespace Graphp\Tests\Algorithms\MaxFlow;
use Graphp\Algorithms\MaxFlow\EdmondsKarp as AlgorithmMaxFlowEdmondsKarp;
use Graphp\Graph\Graph;
use Graphp\Tests\Algorithms\TestCase;
class EdmondsKarpTest extends TestCase
{
public function testEdgeDirected()
{
// 0 -[0/10]-> 1
$graph = new Graph();
$v0 = $graph->createVertex(0);
$v1 = $graph->createVertex(1);
$graph->createEdgeDirected($v0, $v1)->setCapacity(10);
// 0 -[10/10]-> 1
$alg = new AlgorithmMaxFlowEdmondsKarp($v0, $v1);
$this->assertEquals(10, $alg->getFlowMax());
}
public function testEdgesMultiplePaths()
{
// 0 -[0/5]---------> 1
// | ^
// | |
// \-[0/7]-> 2 -[0/9]-/
$graph = new Graph();
$v0 = $graph->createVertex(0);
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$graph->createEdgeDirected($v0, $v1)->setCapacity(5);
$graph->createEdgeDirected($v0, $v2)->setCapacity(7);
$graph->createEdgeDirected($v2, $v1)->setCapacity(9);
// 0 -[5/5]---------> 1
// | ^
// | |
// \-[7/7]-> 2 -[7/9]-/
$alg = new AlgorithmMaxFlowEdmondsKarp($v0, $v1);
$this->assertEquals(12, $alg->getFlowMax());
}
public function testEdgesMultiplePathsTwo()
{
// 0 -[0/5]---------> 1-[0/10]-> 3
// | ^ |
// | | |
// \-[0/7]-> 2 -[0/9]-/ |
// ^ |
// \---[0/2]-----------/
$graph = new Graph();
$v0 = $graph->createVertex(0);
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$v3 = $graph->createVertex(3);
$graph->createEdgeDirected($v0, $v1)->setCapacity(5);
$graph->createEdgeDirected($v0, $v2)->setCapacity(7);
$graph->createEdgeDirected($v2, $v1)->setCapacity(9);
$graph->createEdgeDirected($v1, $v3)->setCapacity(10);
$graph->createEdgeDirected($v3, $v2)->setCapacity(2);
$alg = new AlgorithmMaxFlowEdmondsKarp($v0, $v3);
$this->assertEquals(10, $alg->getFlowMax());
$alg = new AlgorithmMaxFlowEdmondsKarp($v0, $v2);
$this->assertEquals(9, $alg->getFlowMax());
}
public function testEdgesMultiplePathsTree()
{
$graph = new Graph();
$v0 = $graph->createVertex(0);
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$v3 = $graph->createVertex(3);
$graph->createEdgeDirected($v0, $v1)->setCapacity(4);
$graph->createEdgeDirected($v0, $v2)->setCapacity(2);
$graph->createEdgeDirected($v1, $v2)->setCapacity(3);
$graph->createEdgeDirected($v1, $v3)->setCapacity(1);
$graph->createEdgeDirected($v2, $v3)->setCapacity(6);
$alg = new AlgorithmMaxFlowEdmondsKarp($v0, $v3);
$this->assertEquals(6, $alg->getFlowMax());
}
// public function testEdgesParallel(){
// $graph = new Graph();
// $v0 = $graph->createVertex(0);
// $v1 = $graph->createVertex(1);
// $graph->createEdgeDirected($v0, $v1)->setCapacity(3.4);
// $graph->createEdgeDirected($v0, $v1)->setCapacity(6.6);
// $alg = new AlgorithmMaxFlowEdmondsKarp($v0, $v1);
// $this->assertEquals(10, $alg->getFlowMax());
// }
public function testEdgesUndirected()
{
// 0 -[0/7]- 1
$graph = new Graph();
$v0 = $graph->createVertex(0);
$v1 = $graph->createVertex(1);
$graph->createEdgeUndirected($v1, $v0)->setCapacity(7);
// 0 -[7/7]- 1
$alg = new AlgorithmMaxFlowEdmondsKarp($v0, $v1);
$this->setExpectedException('UnexpectedValueException');
$this->assertEquals(7, $alg->getFlowMax());
}
/**
* run algorithm with bigger graph and check result against known result (will take several seconds)
*/
// public function testKnownResultBig(){
// $graph = $this->readGraph('G_1_2.txt');
// $alg = new AlgorithmMaxFlowEdmondsKarp($graph->getVertex(0), $graph->getVertex(4));
// $this->assertEquals(0.735802, $alg->getFlowMax());
// }
public function testInvalidFlowToOtherGraph()
{
$graph1 = new Graph();
$vg1 = $graph1->createVertex(1);
$graph2 = new Graph();
$vg2 = $graph2->createVertex(2);
$this->setExpectedException('InvalidArgumentException');
new AlgorithmMaxFlowEdmondsKarp($vg1, $vg2);
}
public function testInvalidFlowToSelf()
{
$graph = new Graph();
$v1 = $graph->createVertex(1);
$this->setExpectedException('InvalidArgumentException');
new AlgorithmMaxFlowEdmondsKarp($v1, $v1);
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/Search/BreadthFirstTest.php | tests/Search/BreadthFirstTest.php | <?php
namespace Graphp\Tests\Algorithms\Search;
use Graphp\Algorithms\Search\BreadthFirst;
use Graphp\Graph\Graph;
use Graphp\Tests\Algorithms\TestCase;
class BreadthFirstTest extends TestCase
{
public function providerMaxDepth()
{
return array(
"simple path (no limit)" => array(
"edges" => array(
array(1, 2), array(2, 3), array(3, 4), array(4, 5),
),
"subject" => 1,
"maxDepth" => null,
"expected" => array(1, 2, 3, 4, 5),
),
"simple path (limit = 0)" => array(
"edges" => array(
array(1, 2), array(2, 3), array(3, 4), array(4, 5),
),
"subject" => 1,
"maxDepth" => 0,
"expected" => array(1),
),
"simple path (limit = 1)" => array(
"edges" => array(
array(1, 2), array(2, 3), array(3, 4), array(4, 5),
),
"subject" => 1,
"maxDepth" => 1,
"expected" => array(1, 2),
),
);
}
/**
* @dataProvider providerMaxDepth
*/
public function testMaxDepth(array $edges, $subject, $maxDepth, array $expected)
{
$g = new Graph();
foreach ($edges as $e) {
$g->createEdgeDirected($g->createVertex($e[0], true), $g->createVertex($e[1], true));
}
$a = new BreadthFirst($g->getVertex($subject));
if ($maxDepth !== null) {
$v = $a->getVertices($maxDepth);
} else {
$v = $a->getVertices(); // Simulate default
}
$this->assertSame($expected, $v->getIds());
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/MinimumSpanningTree/PrimTest.php | tests/MinimumSpanningTree/PrimTest.php | <?php
namespace Graphp\Tests\Algorithms\MinimumSpanningTree;
use Graphp\Algorithms\MinimumSpanningTree\Prim;
use Graphp\Graph\Vertex;
class PrimTest extends BaseMstTest
{
protected function createAlg(Vertex $vertex)
{
return new Prim($vertex);
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/MinimumSpanningTree/KruskalTest.php | tests/MinimumSpanningTree/KruskalTest.php | <?php
namespace Graphp\Tests\Algorithms\MinimumSpanningTree;
use Graphp\Algorithms\MinimumSpanningTree\Kruskal;
use Graphp\Graph\Graph;
use Graphp\Graph\Vertex;
class KruskalTest extends BaseMstTest
{
protected function createAlg(Vertex $vertex)
{
return new Kruskal($vertex->getGraph());
}
public function testNullGraphIsNotConsideredToBeConnected()
{
$graph = new Graph();
$alg = new Kruskal($graph);
$this->setExpectedException('UnexpectedValueException');
$alg->getEdges();
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/MinimumSpanningTree/BaseMstTest.php | tests/MinimumSpanningTree/BaseMstTest.php | <?php
namespace Graphp\Tests\Algorithms\MinimumSpanningTree;
use Graphp\Algorithms\MinimumSpanningTree\Base as MstBase;
use Graphp\Graph\Graph;
use Graphp\Graph\Vertex;
use Graphp\Tests\Algorithms\TestCase;
abstract class BaseMstTest extends TestCase
{
/**
* @param Vertex $vertex
* @return MstBase
*/
abstract protected function createAlg(Vertex $vertex);
public function testIsolatedVertex()
{
$graph = new Graph();
$v1 = $graph->createVertex(1);
$alg = $this->createAlg($v1);
$this->assertCount(0, $alg->getEdges());
$this->assertEquals(0, $alg->getWeight());
$graphMst = $alg->createGraph();
$this->assertGraphEquals($graph, $graphMst);
}
public function testSingleEdge()
{
// 1 --[3]-- 2
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$graph->createEdgeUndirected($v1, $v2)->setWeight(3);
$alg = $this->createAlg($v1);
$this->assertCount(1, $alg->getEdges());
$this->assertEquals(3, $alg->getWeight());
$this->assertGraphEquals($graph, $alg->createGraph());
}
public function testSimpleGraph()
{
// 1 --[6]-- 2 --[9]-- 3 --[7]-- 4 --[8]-- 5
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$v3 = $graph->createVertex(3);
$v4 = $graph->createVertex(4);
$v5 = $graph->createVertex(5);
$graph->createEdgeUndirected($v1, $v2)->setWeight(6);
$graph->createEdgeUndirected($v2, $v3)->setWeight(9);
$graph->createEdgeUndirected($v3, $v4)->setWeight(7);
$graph->createEdgeUndirected($v4, $v5)->setWeight(8);
$alg = $this->createAlg($v1);
$graphMst = $alg->createGraph();
$this->assertGraphEquals($graph, $graphMst);
}
public function testFindingCheapestEdge()
{
// /--[4]--\
// / \
// 1 ---[3]--- 2
// \ /
// \--[5]--/
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$graph->createEdgeUndirected($v1, $v2)->setWeight(4);
$graph->createEdgeUndirected($v1, $v2)->setWeight(3);
$graph->createEdgeUndirected($v1, $v2)->setWeight(5);
$alg = $this->createAlg($v1);
$edges = $alg->getEdges();
$this->assertCount(1, $edges);
$this->assertEquals(3, $edges->getEdgeFirst()->getWeight());
$this->assertEquals(3, $alg->getWeight());
}
public function testFindingCheapestTree()
{
// 1 --[4]-- 2 --[5]-- 3
// \ /
// \-------[6]-----/
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$v3 = $graph->createVertex(3);
$graph->createEdgeUndirected($v1, $v2)->setWeight(4);
$graph->createEdgeUndirected($v2, $v3)->setWeight(5);
$graph->createEdgeUndirected($v3, $v1)->setWeight(6);
// 1 --[4]-- 2 -- [5] -- 3
$graphExpected = new Graph();
$ve1 = $graphExpected->createVertex(1);
$ve2 = $graphExpected->createVertex(2);
$ve3 = $graphExpected->createVertex(3);
$graphExpected->createEdgeUndirected($ve1, $ve2)->setWeight(4);
$graphExpected->createEdgeUndirected($ve2, $ve3)->setWeight(5);
$alg = $this->createAlg($v1);
$this->assertCount(2, $alg->getEdges());
$this->assertEquals(9, $alg->getWeight());
$this->assertGraphEquals($graphExpected, $alg->createGraph());
}
public function testMixedGraphDirectionIsIgnored()
{
// 1 --[6]-> 2 --[7]-- 3 --[8]-- 4 <-[9]-- 5
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$v3 = $graph->createVertex(3);
$v4 = $graph->createVertex(4);
$v5 = $graph->createVertex(5);
$graph->createEdgeDirected($v1, $v2)->setWeight(6);
$graph->createEdgeUndirected($v2, $v3)->setWeight(7);
$graph->createEdgeUndirected($v4, $v3)->setWeight(8);
$graph->createEdgeDirected($v5, $v4)->setWeight(9);
$alg = $this->createAlg($v1);
$this->assertCount(4, $alg->getEdges());
$this->assertEquals(30, $alg->getWeight());
$this->assertGraphEquals($graph, $alg->createGraph());
}
public function testMultipleComponentsFail()
{
// 1 --[1]-- 2, 3 --[1]-- 4
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$v3 = $graph->createVertex(3);
$v4 = $graph->createVertex(4);
$graph->createEdgeUndirected($v1, $v2)->setWeight(1);
$graph->createEdgeUndirected($v3, $v4)->setWeight(1);
$alg = $this->createAlg($v1);
$this->setExpectedException('UnexpectedValueException');
$alg->getEdges();
}
public function testMultipleIsolatedVerticesFormMultipleComponentsFail()
{
// 1, 2
$graph = new Graph();
$v1 = $graph->createVertex(1);
$graph->createVertex(2);
$alg = $this->createAlg($v1);
$this->setExpectedException('UnexpectedValueException');
$alg->getEdges();
}
} | php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/Property/PropertyGraphTest.php | tests/Property/PropertyGraphTest.php | <?php
namespace Graphp\Tests\Algorithms\Property;
use Graphp\Algorithms\Property\GraphProperty;
use Graphp\Graph\Graph;
use Graphp\Tests\Algorithms\TestCase;
class PropertyGraphTest extends TestCase
{
public function testEmptyIsEdgeless()
{
$graph = new Graph();
$alg = new GraphProperty($graph);
$this->assertTrue($alg->isNull());
$this->assertTrue($alg->isEdgeless());
$this->assertFalse($alg->isTrivial());
}
public function testSingleVertexIsTrivial()
{
$graph = new Graph();
$graph->createVertex(1);
$alg = new GraphProperty($graph);
$this->assertFalse($alg->isNull());
$this->assertTrue($alg->isEdgeless());
$this->assertTrue($alg->isTrivial());
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
graphp/algorithms | https://github.com/graphp/algorithms/blob/269389305c94ad9b72b35a9f798ed70c1f708fc2/tests/Property/WalkPropertyTest.php | tests/Property/WalkPropertyTest.php | <?php
namespace Graphp\Tests\Algorithms\Property;
use Graphp\Algorithms\Property\WalkProperty;
use Graphp\Graph\Graph;
use Graphp\Graph\Walk;
use Graphp\Tests\Algorithms\TestCase;
class WalkPropertyTest extends TestCase
{
public function testTrivialGraph()
{
$graph = new Graph();
$v1 = $graph->createVertex(1);
$walk = Walk::factoryFromEdges(array(), $v1);
$this->assertCount(1, $walk->getVertices());
$this->assertCount(0, $walk->getEdges());
$alg = new WalkProperty($walk);
$this->assertFalse($alg->isLoop());
$this->assertFalse($alg->hasLoop());
$this->assertFalse($alg->isCycle());
$this->assertFalse($alg->hasCycle());
$this->assertTrue($alg->isPath());
$this->assertTrue($alg->isSimple());
$this->assertTrue($alg->isEulerian());
$this->assertTrue($alg->isHamiltonian());
}
public function testLoop()
{
// 1 -- 1
$graph = new Graph();
$v1 = $graph->createVertex(1);
$e1 = $graph->createEdgeUndirected($v1, $v1);
$walk = Walk::factoryFromEdges(array($e1), $v1);
$alg = new WalkProperty($walk);
$this->assertTrue($alg->isLoop());
$this->assertTrue($alg->hasLoop());
$this->assertTrue($alg->isCycle());
$this->assertTrue($alg->hasCycle());
$this->assertTrue($alg->isPath());
$this->assertTrue($alg->isSimple());
$this->assertTrue($alg->isEulerian());
$this->assertTrue($alg->isHamiltonian());
}
public function testCycle()
{
// 1 -- 2 -- 1
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$e1 = $graph->createEdgeUndirected($v1, $v2);
$e2 = $graph->createEdgeUndirected($v2, $v1);
$walk = Walk::factoryFromEdges(array($e1, $e2), $v1);
$this->assertCount(3, $walk->getVertices());
$this->assertCount(2, $walk->getEdges());
$alg = new WalkProperty($walk);
$this->assertTrue($alg->isCycle());
$this->assertTrue($alg->hasCycle());
$this->assertTrue($alg->isPath());
$this->assertTrue($alg->isSimple());
$this->assertTrue($alg->isEulerian());
$this->assertTrue($alg->isHamiltonian());
}
public function testCircuit()
{
// 1 -> 2 -> 1, 2 -> 2
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$e1 = $graph->createEdgeDirected($v1, $v2);
$e2 = $graph->createEdgeDirected($v2, $v1);
$e3 = $graph->createEdgeDirected($v2, $v2);
// 1 -> 2 -> 2 -> 1
$walk = Walk::factoryFromEdges(array($e1, $e3, $e2), $v1);
$this->assertEquals(array(1, 2, 2, 1), $walk->getVertices()->getIds());
$alg = new WalkProperty($walk);
$this->assertTrue($alg->isCycle());
$this->assertTrue($alg->isCircuit());
}
public function testNonCircuit()
{
// 1 -> 2 -> 1, 2 -> 2
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$e1 = $graph->createEdgeDirected($v1, $v2);
$e2 = $graph->createEdgeDirected($v2, $v1);
$e3 = $graph->createEdgeDirected($v2, $v2);
// non-circuit: taking loop twice
// 1 -> 2 -> 2 -> 2 -> 1
$walk = Walk::factoryFromEdges(array($e1, $e3, $e3, $e2), $v1);
$this->assertEquals(array(1, 2, 2, 2, 1), $walk->getVertices()->getIds());
$alg = new WalkProperty($walk);
$this->assertTrue($alg->isCycle());
$this->assertFalse($alg->isCircuit());
}
public function testDigon()
{
// 1 -> 2 -> 1
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$e1 = $graph->createEdgeDirected($v1, $v2);
$e2 = $graph->createEdgeDirected($v2, $v1);
$walk = Walk::factoryFromEdges(array($e1, $e2), $v1);
$alg = new WalkProperty($walk);
$this->assertTrue($alg->isDigon());
}
public function testTriangle()
{
// 1 -> 2 -> 3 -> 1
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$v3 = $graph->createVertex(3);
$e1 = $graph->createEdgeDirected($v1, $v2);
$e2 = $graph->createEdgeDirected($v2, $v3);
$e3 = $graph->createEdgeDirected($v3, $v1);
$walk = Walk::factoryFromEdges(array($e1, $e2, $e3), $v1);
$alg = new WalkProperty($walk);
$this->assertTrue($alg->isTriangle());
}
public function testSimplePathWithinGraph()
{
// 1 -- 2 -- 2
$graph = new Graph();
$v1 = $graph->createVertex(1);
$v2 = $graph->createVertex(2);
$graph->createEdgeUndirected($v1, $v2);
$e2 = $graph->createEdgeUndirected($v2, $v2);
// only use "2 -- 2" part
$walk = Walk::factoryFromEdges(array($e2), $v2);
$this->assertCount(2, $walk->getVertices());
$this->assertCount(1, $walk->getEdges());
$alg = new WalkProperty($walk);
$this->assertTrue($alg->isCycle());
$this->assertTrue($alg->hasCycle());
$this->assertTrue($alg->isPath());
$this->assertTrue($alg->isSimple());
$this->assertFalse($alg->isEulerian());
$this->assertFalse($alg->isHamiltonian());
}
}
| php | MIT | 269389305c94ad9b72b35a9f798ed70c1f708fc2 | 2026-01-05T04:40:43.543752Z | false |
CoreSphere/ConsoleBundle | https://github.com/CoreSphere/ConsoleBundle/blob/19679d097fb9383d54804de8392d1bfd72307c4b/CoreSphereConsoleBundle.php | CoreSphereConsoleBundle.php | <?php
/*
* This file is part of the CoreSphereConsoleBundle.
*
* (c) Laszlo Korte <me@laszlokorte.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CoreSphere\ConsoleBundle;
use CoreSphere\ConsoleBundle\DependencyInjection\Extension\CoreSphereConsoleExtension;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class CoreSphereConsoleBundle extends Bundle
{
/**
* {@inheritdoc}
*/
public function getContainerExtension()
{
return new CoreSphereConsoleExtension();
}
}
| php | BSD-3-Clause | 19679d097fb9383d54804de8392d1bfd72307c4b | 2026-01-05T04:40:51.045098Z | false |
CoreSphere/ConsoleBundle | https://github.com/CoreSphere/ConsoleBundle/blob/19679d097fb9383d54804de8392d1bfd72307c4b/Routing/Loader.php | Routing/Loader.php | <?php
/*
* This file is part of the CoreSphereConsoleBundle.
*
* (c) Laszlo Korte <me@laszlokorte.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CoreSphere\ConsoleBundle\Routing;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Config\Loader\LoaderResolverInterface;
use Symfony\Component\Routing\Loader\YamlFileLoader;
use Symfony\Component\Routing\RouteCollection;
final class Loader implements LoaderInterface
{
/**
* @var YamlFileLoader
*/
private $yamlFileLoader;
public function __construct(YamlFileLoader $yamlFileLoader)
{
$this->yamlFileLoader = $yamlFileLoader;
}
/**
* {@inheritdoc}
*/
public function load($resource, $type = null)
{
$collection = new RouteCollection();
$collection->addCollection(
$this->yamlFileLoader->import(__DIR__.'/../Resources/config/routing.yml')
);
return $collection;
}
/**
* {@inheritdoc}
*/
public function supports($resource, $type = null)
{
return 'extra' === $type;
}
/**
* {@inheritdoc}
*/
public function getResolver()
{
}
/**
* {@inheritdoc}
*/
public function setResolver(LoaderResolverInterface $resolver)
{
}
}
| php | BSD-3-Clause | 19679d097fb9383d54804de8392d1bfd72307c4b | 2026-01-05T04:40:51.045098Z | false |
CoreSphere/ConsoleBundle | https://github.com/CoreSphere/ConsoleBundle/blob/19679d097fb9383d54804de8392d1bfd72307c4b/Formatter/HtmlOutputFormatterDecorator.php | Formatter/HtmlOutputFormatterDecorator.php | <?php
/*
* This file is part of the CoreSphereConsoleBundle.
*
* (c) Laszlo Korte <me@laszlokorte.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CoreSphere\ConsoleBundle\Formatter;
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
use Symfony\Component\Console\Formatter\OutputFormatterStyleInterface;
final class HtmlOutputFormatterDecorator implements OutputFormatterInterface
{
const CLI_COLORS_PATTERN = '/\033\[(([\d+];?)*)m(.*?)\033\[(([\d+];?)*)m/i';
/**
* @var string[]
*/
private $styles = [
'30' => 'color:rgba(0,0,0,1)',
'31' => 'color:rgba(230,50,50,1)',
'32' => 'color:rgba(50,230,50,1)',
'33' => 'color:rgba(230,230,50,1)',
'34' => 'color:rgba(50,50,230,1)',
'35' => 'color:rgba(230,50,150,1)',
'36' => 'color:rgba(50,230,230,1)',
'37' => 'color:rgba(250,250,250,1)',
'40' => 'color:rgba(0,0,0,1)',
'41' => 'background-color:rgba(230,50,50,1)',
'42' => 'background-color:rgba(50,230,50,1)',
'43' => 'background-color:rgba(230,230,50,1)',
'44' => 'background-color:rgba(50,50,230,1)',
'45' => 'background-color:rgba(230,50,150,1)',
'46' => 'background-color:rgba(50,230,230,1)',
'47' => 'background-color:rgba(250,250,250,1)',
'1' => 'font-weight:bold',
'4' => 'text-decoration:underline',
'8' => 'visibility:hidden',
];
/**
* @var OutputFormatterInterface
*/
private $formatter;
public function __construct(OutputFormatterInterface $formatter)
{
$this->formatter = $formatter;
}
/**
* {@inheritdoc}
*/
public function setDecorated($decorated)
{
return $this->formatter->setDecorated($decorated);
}
/**
* {@inheritdoc}
*/
public function isDecorated()
{
return $this->formatter->isDecorated();
}
/**
* {@inheritdoc}
*/
public function setStyle($name, OutputFormatterStyleInterface $style)
{
return $this->formatter->setStyle($name, $style);
}
/**
* {@inheritdoc}
*/
public function hasStyle($name)
{
return $this->formatter->hasStyle($name);
}
/**
* {@inheritdoc}
*/
public function getStyle($name)
{
return $this->formatter->getStyle($name);
}
/**
* {@inheritdoc}
*/
public function format($message)
{
if (!$this->isDecorated()) {
return $message;
}
$formatted = $this->formatter->format($message);
$escaped = htmlspecialchars($formatted, ENT_QUOTES, 'UTF-8');
$converted = preg_replace_callback(self::CLI_COLORS_PATTERN, function ($matches) {
return $this->replaceFormat($matches);
}, $escaped);
return $converted;
}
/**
* @return string
*/
private function replaceFormat(array $matches)
{
$text = $matches[3];
$styles = explode(';', $matches[1]);
$css = array_intersect_key($this->styles, array_flip($styles));
return sprintf(
'<span style="%s">%s</span>',
implode(';', $css),
$text
);
}
}
| php | BSD-3-Clause | 19679d097fb9383d54804de8392d1bfd72307c4b | 2026-01-05T04:40:51.045098Z | false |
CoreSphere/ConsoleBundle | https://github.com/CoreSphere/ConsoleBundle/blob/19679d097fb9383d54804de8392d1bfd72307c4b/Contract/Executer/CommandExecuterInterface.php | Contract/Executer/CommandExecuterInterface.php | <?php
/*
* This file is part of the CoreSphereConsoleBundle.
*
* (c) Laszlo Korte <me@laszlokorte.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CoreSphere\ConsoleBundle\Contract\Executer;
/**
* Takes a string to execute as console command.
*/
interface CommandExecuterInterface
{
/**
* @param string $commandString
*
* @return array
*/
public function execute($commandString);
}
| php | BSD-3-Clause | 19679d097fb9383d54804de8392d1bfd72307c4b | 2026-01-05T04:40:51.045098Z | false |
CoreSphere/ConsoleBundle | https://github.com/CoreSphere/ConsoleBundle/blob/19679d097fb9383d54804de8392d1bfd72307c4b/Output/StringOutput.php | Output/StringOutput.php | <?php
/*
* This file is part of the CoreSphereConsoleBundle.
*
* (c) Laszlo Korte <me@laszlokorte.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CoreSphere\ConsoleBundle\Output;
use Symfony\Component\Console\Output\Output;
/**
* Collects console output into a string.
*/
class StringOutput extends Output
{
/**
* @var string
*/
protected $buffer = '';
/**
* {@inheritdoc}
*/
public function doWrite($message, $newline)
{
$this->buffer .= $message.(true === $newline ? PHP_EOL : '');
}
/**
* @return string
*/
public function getBuffer()
{
return $this->buffer;
}
}
| php | BSD-3-Clause | 19679d097fb9383d54804de8392d1bfd72307c4b | 2026-01-05T04:40:51.045098Z | false |
CoreSphere/ConsoleBundle | https://github.com/CoreSphere/ConsoleBundle/blob/19679d097fb9383d54804de8392d1bfd72307c4b/Controller/ConsoleController.php | Controller/ConsoleController.php | <?php
/*
* This file is part of the CoreSphereConsoleBundle.
*
* (c) Laszlo Korte <me@laszlokorte.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CoreSphere\ConsoleBundle\Controller;
use CoreSphere\ConsoleBundle\Contract\Executer\CommandExecuterInterface;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Templating\EngineInterface;
class ConsoleController
{
/**
* @var EngineInterface
*/
private $templating;
/**
* @var CommandExecuterInterface
*/
private $commandExecuter;
/**
* @var Application
*/
private $application;
/**
* @var string
*/
private $environment;
public function __construct(
EngineInterface $templating,
CommandExecuterInterface $commandExecuter,
Application $application,
$environment
) {
$this->templating = $templating;
$this->commandExecuter = $commandExecuter;
$this->application = $application;
$this->environment = $environment;
}
public function consoleAction()
{
return new Response(
$this->templating->render('CoreSphereConsoleBundle:Console:console.html.twig', [
'working_dir' => getcwd(),
'environment' => $this->environment,
'commands' => $this->application->all(),
])
);
}
public function execAction(Request $request)
{
$commands = $request->request->get('commands');
$executedCommandsOutput = [];
foreach ($commands as $command) {
$result = $this->commandExecuter->execute($command);
$executedCommandsOutput[] = $result;
if (0 !== $result['error_code']) {
break;
}
}
return new Response(
$this->templating->render(
'CoreSphereConsoleBundle:Console:result.json.twig',
['commands' => $executedCommandsOutput]
)
);
}
}
| php | BSD-3-Clause | 19679d097fb9383d54804de8392d1bfd72307c4b | 2026-01-05T04:40:51.045098Z | false |
CoreSphere/ConsoleBundle | https://github.com/CoreSphere/ConsoleBundle/blob/19679d097fb9383d54804de8392d1bfd72307c4b/DependencyInjection/Extension/CoreSphereConsoleExtension.php | DependencyInjection/Extension/CoreSphereConsoleExtension.php | <?php
/*
* This file is part of the CoreSphereConsoleBundle.
*
* (c) Laszlo Korte <me@laszlokorte.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CoreSphere\ConsoleBundle\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\Config\FileLocator;
final class CoreSphereConsoleExtension extends Extension implements PrependExtensionInterface
{
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../../Resources/config'));
$loader->load('services.yml');
}
/**
* {@inheritdoc}
*/
public function prepend(ContainerBuilder $containerBuilder)
{
$containerBuilder->prependExtensionConfig($this->getAlias(), [
'resource' => '.',
'type' => 'extra',
]);
}
}
| php | BSD-3-Clause | 19679d097fb9383d54804de8392d1bfd72307c4b | 2026-01-05T04:40:51.045098Z | false |
CoreSphere/ConsoleBundle | https://github.com/CoreSphere/ConsoleBundle/blob/19679d097fb9383d54804de8392d1bfd72307c4b/DataCollector/DataCollector.php | DataCollector/DataCollector.php | <?php
/*
* This file is part of the CoreSphereConsoleBundle.
*
* (c) Laszlo Korte <me@laszlokorte.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CoreSphere\ConsoleBundle\DataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\DataCollector as DataCollectorBase;
final class DataCollector extends DataCollectorBase
{
/**
* {@inheritdoc}
*/
public function collect(Request $request, Response $response, \Exception $exception = null)
{
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'coresphere_console';
}
/**
* {@inheritdoc}
*/
public function reset()
{
$this->data = [];
}
}
| php | BSD-3-Clause | 19679d097fb9383d54804de8392d1bfd72307c4b | 2026-01-05T04:40:51.045098Z | false |
CoreSphere/ConsoleBundle | https://github.com/CoreSphere/ConsoleBundle/blob/19679d097fb9383d54804de8392d1bfd72307c4b/Console/ApplicationFactory.php | Console/ApplicationFactory.php | <?php
/*
* This file is part of the CoreSphereConsoleBundle.
*
* (c) Laszlo Korte <me@laszlokorte.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CoreSphere\ConsoleBundle\Console;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\HttpKernel\KernelInterface;
class ApplicationFactory
{
/**
* @return Application
*/
public function create(KernelInterface $kernel)
{
$application = new Application($kernel);
$application = $this->registerCommandsToApplication($application, $kernel);
return $application;
}
/**
* @return Application
*/
private function registerCommandsToApplication(Application $application, KernelInterface $kernel)
{
chdir($kernel->getRootDir().'/..');
foreach ($this->getBundlesFromKernel($kernel) as $bundle) {
$bundle->registerCommands($application);
}
return $application;
}
/**
* @return Bundle[]
*/
private function getBundlesFromKernel(KernelInterface $kernel)
{
if ($bundles = $kernel->getBundles()) {
return $bundles;
}
return $kernel->registerBundles();
}
}
| php | BSD-3-Clause | 19679d097fb9383d54804de8392d1bfd72307c4b | 2026-01-05T04:40:51.045098Z | false |
CoreSphere/ConsoleBundle | https://github.com/CoreSphere/ConsoleBundle/blob/19679d097fb9383d54804de8392d1bfd72307c4b/Tests/Routing/LoaderTest.php | Tests/Routing/LoaderTest.php | <?php
/*
* This file is part of the CoreSphereConsoleBundle.
*
* (c) Laszlo Korte <me@laszlokorte.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CoreSphere\ConsoleBundle\Tests\Routing;
use CoreSphere\ConsoleBundle\Routing\Loader;
use PHPUnit_Framework_TestCase;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Loader\LoaderResolverInterface;
use Symfony\Component\Routing\Loader\YamlFileLoader;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
final class LoaderTest extends PHPUnit_Framework_TestCase
{
/**
* @var Loader
*/
private $loader;
protected function setUp()
{
$this->loader = new Loader(new YamlFileLoader(new FileLocator()));
}
public function testLoading()
{
$routes = $this->loader->load(null, null);
$this->assertInstanceOf(RouteCollection::class, $routes);
/** @var Route $route */
$route = $routes->get('console');
$this->assertSame('/_console', $route->getPath());
$this->assertSame('coresphere_console.controller:consoleAction', $route->getDefault('_controller'));
/** @var Route $route */
$route = $routes->get('console_exec');
$this->assertSame('/_console/commands.{_format}', $route->getPath());
$this->assertSame('coresphere_console.controller:execAction', $route->getDefault('_controller'));
}
public function testSupports()
{
$this->assertTrue($this->loader->supports(null, 'extra'));
$this->assertFalse($this->loader->supports(null, 'other'));
}
public function testResolver()
{
$this->assertNull($this->loader->getResolver());
$resolverMock = $this->prophesize(LoaderResolverInterface::class);
$this->loader->setResolver($resolverMock->reveal());
}
}
| php | BSD-3-Clause | 19679d097fb9383d54804de8392d1bfd72307c4b | 2026-01-05T04:40:51.045098Z | false |
CoreSphere/ConsoleBundle | https://github.com/CoreSphere/ConsoleBundle/blob/19679d097fb9383d54804de8392d1bfd72307c4b/Tests/Formatter/HtmlOutputFormatterDecoratorTest.php | Tests/Formatter/HtmlOutputFormatterDecoratorTest.php | <?php
/*
* This file is part of the CoreSphereConsoleBundle.
*
* (c) Laszlo Korte <me@laszlokorte.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CoreSphere\ConsoleBundle\Tests\Formatter;
use CoreSphere\ConsoleBundle\Formatter\HtmlOutputFormatterDecorator;
use PHPUnit_Framework_TestCase;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
final class HtmlOutputFormatterDecoratorTest extends PHPUnit_Framework_TestCase
{
/**
* @var HtmlOutputFormatterDecorator
*/
private $decoratedFormatter;
protected function setUp()
{
$this->decoratedFormatter = new HtmlOutputFormatterDecorator(new OutputFormatter(true));
}
public function testEscapingOutput()
{
$this->decoratedFormatter->setStyle('error', new OutputFormatterStyle('white', 'red'));
$this->decoratedFormatter->setStyle('info', new OutputFormatterStyle('green'));
$this->decoratedFormatter->setStyle('comment', new OutputFormatterStyle('yellow'));
$this->decoratedFormatter->setStyle('question', new OutputFormatterStyle('black', 'cyan'));
$this->assertSame(
'a<script>evil();</script>a', $this->decoratedFormatter->format(
'a<script>evil();</script>a'
)
);
$this->assertSame(
'<script><span style="color:rgba(50,230,50,1)">evil();</span></script>', $this->decoratedFormatter->format(
'<script><info>evil();</info></script>'
)
);
$this->assertSame(
'<span style="color:rgba(50,230,50,1)">a</span>'.
'<span style="color:rgba(50,230,50,1)"><script></span>'.
'<span style="color:rgba(250,250,250,1);background-color:rgba(230,50,50,1)">evil();</span>'.
'<span style="color:rgba(50,230,50,1)"></script></span>', $this->decoratedFormatter->format(
'<info>a<script><error>evil();</error></script>'
)
);
$this->assertSame(
'<span style="color:rgba(50,230,50,1)">a&lt;</span>'.
'<span style="color:rgba(50,230,50,1)"><script></span>'.
'<span style="color:rgba(50,230,50,1)">evil();</span>'.
'<span style="color:rgba(50,230,50,1)"></script></span>', $this->decoratedFormatter->format(
'<info>a<<script><info>evil();</info></script>'
)
);
}
public function testDecorated()
{
$this->assertTrue($this->decoratedFormatter->isDecorated());
$this->decoratedFormatter->setDecorated(false);
$this->assertFalse($this->decoratedFormatter->isDecorated());
}
public function testUndecorated()
{
$this->decoratedFormatter->setStyle('info', new OutputFormatterStyle('green'));
$this->decoratedFormatter->setDecorated(false);
$this->assertSame(
'<info>Do not change</info>',
$this->decoratedFormatter->format(
'<info>Do not change</info>'
)
);
}
public function testStyle()
{
$this->assertFalse($this->decoratedFormatter->hasStyle('nonExisting'));
$outputFormatterStyle = new OutputFormatterStyle('blue');
$this->decoratedFormatter->setStyle('blue', $outputFormatterStyle);
$this->assertTrue($this->decoratedFormatter->hasStyle('blue'));
$this->assertSame($outputFormatterStyle, $this->decoratedFormatter->getStyle('blue'));
}
}
| php | BSD-3-Clause | 19679d097fb9383d54804de8392d1bfd72307c4b | 2026-01-05T04:40:51.045098Z | false |
CoreSphere/ConsoleBundle | https://github.com/CoreSphere/ConsoleBundle/blob/19679d097fb9383d54804de8392d1bfd72307c4b/Tests/Output/StringOutputTest.php | Tests/Output/StringOutputTest.php | <?php
/*
* This file is part of the CoreSphereConsoleBundle.
*
* (c) Laszlo Korte <me@laszlokorte.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CoreSphere\ConsoleBundle\Tests\Output;
use CoreSphere\ConsoleBundle\Output\StringOutput;
use PHPUnit_Framework_TestCase;
final class StringOutputTest extends PHPUnit_Framework_TestCase
{
public function testWriteRead()
{
$output = new StringOutput();
$text = 'foo';
$output->write($text);
$this->assertSame($text, $output->getBuffer());
$output->write($text, true);
$this->assertSame($text.$text.PHP_EOL, $output->getBuffer());
}
}
| php | BSD-3-Clause | 19679d097fb9383d54804de8392d1bfd72307c4b | 2026-01-05T04:40:51.045098Z | false |
CoreSphere/ConsoleBundle | https://github.com/CoreSphere/ConsoleBundle/blob/19679d097fb9383d54804de8392d1bfd72307c4b/Tests/Controller/ConsoleControllerTest.php | Tests/Controller/ConsoleControllerTest.php | <?php
/*
* This file is part of the CoreSphereConsoleBundle.
*
* (c) Laszlo Korte <me@laszlokorte.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CoreSphere\ConsoleBundle\Tests\Controller;
use CoreSphere\ConsoleBundle\Console\ApplicationFactory;
use CoreSphere\ConsoleBundle\Contract\Executer\CommandExecuterInterface;
use CoreSphere\ConsoleBundle\Controller\ConsoleController;
use CoreSphere\ConsoleBundle\Tests\Source\KernelWithBundlesWithCommands;
use PHPUnit_Framework_TestCase;
use Prophecy\Argument;
use Prophecy\Prophecy\ObjectProphecy;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Templating\EngineInterface;
final class ConsoleControllerTest extends PHPUnit_Framework_TestCase
{
/**
* @var array
*/
private $renderArguments = [];
public function testConsoleActionWorkingDir()
{
$controller = $this->createControllerWithEnvironment('prod');
$controller->consoleAction();
$this->assertSame(getcwd(), $this->renderArguments[1]['working_dir']);
}
public function testConsoleActionEnvironment()
{
$controller = $this->createControllerWithEnvironment('prod');
$controller->consoleAction();
$this->assertSame('prod', $this->renderArguments[1]['environment']);
$controller = $this->createControllerWithEnvironment('dev');
$controller->consoleAction();
$this->assertSame('dev', $this->renderArguments[1]['environment']);
}
public function testConsoleActionCommands()
{
$controller = $this->createControllerWithEnvironment('prod');
$controller->consoleAction();
$this->assertCount(9, $this->renderArguments[1]['commands']);
}
public function testExecAction()
{
$controller = $this->createControllerWithEnvironment('prod');
$request = new Request([], ['commands' => ['help', 'list']]);
$controller->execAction($request);
$commandsOutput = $this->renderArguments[1]['commands'];
$this->assertSame([
[
'output' => 'help-output',
'error_code' => 0,
],
[
'output' => 'list-output',
'error_code' => 0,
],
], $commandsOutput);
}
public function testExecActionWithError()
{
$controller = $this->createControllerWithEnvironment('prod');
$request = new Request([], ['commands' => ['error-command', 'help']]);
$controller->execAction($request);
$this->assertSame([[
'error_code' => 1,
]], $this->renderArguments[1]['commands']);
}
/**
* @param string $environment
*
* @return ConsoleController
*/
private function createControllerWithEnvironment($environment)
{
$templatingMock = $this->createTemplatingMock();
$commandExecuterMock = $this->createCommandExecuterMock();
$application = $this->createApplicationWithEnvironment($environment);
return new ConsoleController(
$templatingMock->reveal(),
$commandExecuterMock->reveal(),
$application,
$environment
);
}
/**
* @return ObjectProphecy
*/
private function createTemplatingMock()
{
$templatingMock = $this->prophesize(EngineInterface::class);
$that = $this;
$templatingMock->render(Argument::type('string'), Argument::type('array'))->will(
function ($args) use ($that) {
$that->renderArguments = $args;
}
);
return $templatingMock;
}
/**
* @return ObjectProphecy
*/
private function createCommandExecuterMock()
{
$commandExecuterMock = $this->prophesize(CommandExecuterInterface::class);
$commandExecuterMock->execute(Argument::exact('error-command'))
->willReturn([
'error_code' => 1,
]);
$commandExecuterMock->execute(Argument::exact('help'))
->willReturn([
'output' => 'help-output',
'error_code' => 0,
]);
$commandExecuterMock->execute(Argument::exact('list'))
->willReturn([
'output' => 'list-output',
'error_code' => 0,
]);
return $commandExecuterMock;
}
/**
* @param string $environment
*
* @return Application
*/
private function createApplicationWithEnvironment($environment)
{
$kernel = new KernelWithBundlesWithCommands($environment, true);
$application = (new ApplicationFactory())->create($kernel);
return $application;
}
}
| php | BSD-3-Clause | 19679d097fb9383d54804de8392d1bfd72307c4b | 2026-01-05T04:40:51.045098Z | false |
CoreSphere/ConsoleBundle | https://github.com/CoreSphere/ConsoleBundle/blob/19679d097fb9383d54804de8392d1bfd72307c4b/Tests/DependencyInjection/Extension/CoreSphereConsoleExtensionTest.php | Tests/DependencyInjection/Extension/CoreSphereConsoleExtensionTest.php | <?php
/*
* This file is part of the CoreSphereConsoleBundle.
*
* (c) Laszlo Korte <me@laszlokorte.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CoreSphere\ConsoleBundle\Tests\DependencyInjection\Extension;
use CoreSphere\ConsoleBundle\Contract\Executer\CommandExecuterInterface;
use CoreSphere\ConsoleBundle\DependencyInjection\Extension\CoreSphereConsoleExtension;
use CoreSphere\ConsoleBundle\Tests\Executer\CommandExecutorSource\SomeKernel;
use PHPUnit_Framework_TestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
final class CoreSphereConsoleExtensionTest extends PHPUnit_Framework_TestCase
{
public function testLoad()
{
$containerBuilder = $this->createAndPrepareContainerBuilder();
$extension = new CoreSphereConsoleExtension();
$extension->load([], $containerBuilder);
$commandExecuter = $containerBuilder->get('coresphere_console.executer');
$this->assertInstanceOf(CommandExecuterInterface::class, $commandExecuter);
}
public function testPrepend()
{
$containerBuilder = new ContainerBuilder();
$extension = new CoreSphereConsoleExtension();
$extension->prepend($containerBuilder);
$extensionConfig = $containerBuilder->getExtensionConfig($extension->getAlias());
$this->assertSame([
'resource' => '.',
'type' => 'extra',
], $extensionConfig[0]);
}
/**
* @return ContainerBuilder
*/
private function createAndPrepareContainerBuilder()
{
$containerBuilder = new ContainerBuilder();
$containerBuilder->setDefinition('kernel', new Definition(SomeKernel::class))
->setArguments(['prod', true]);
return $containerBuilder;
}
}
| php | BSD-3-Clause | 19679d097fb9383d54804de8392d1bfd72307c4b | 2026-01-05T04:40:51.045098Z | false |
CoreSphere/ConsoleBundle | https://github.com/CoreSphere/ConsoleBundle/blob/19679d097fb9383d54804de8392d1bfd72307c4b/Tests/Source/KernelWithBundlesWithCommands.php | Tests/Source/KernelWithBundlesWithCommands.php | <?php
/*
* This file is part of the CoreSphereConsoleBundle.
*
* (c) Laszlo Korte <me@laszlokorte.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CoreSphere\ConsoleBundle\Tests\Source;
use Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle;
use Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\HttpKernel\Kernel;
final class KernelWithBundlesWithCommands extends Kernel
{
/**
* {@inheritdoc}
*/
public function registerBundles()
{
$bundles = [];
if (in_array($this->getEnvironment(), ['prod'])) {
$bundles[] = new DoctrineMigrationsBundle();
}
if (in_array($this->getEnvironment(), ['dev'])) {
$bundles[] = new DoctrineFixturesBundle();
}
return $bundles;
}
/**
* {@inheritdoc}
*/
public function registerContainerConfiguration(LoaderInterface $loader)
{
}
/**
* {@inheritdoc}
*/
public function getCacheDir()
{
return sys_get_temp_dir().'/_console_tests/temp';
}
/**
* {@inheritdoc}
*/
public function getLogDir()
{
return sys_get_temp_dir().'/_console_tests/log';
}
}
| php | BSD-3-Clause | 19679d097fb9383d54804de8392d1bfd72307c4b | 2026-01-05T04:40:51.045098Z | false |
CoreSphere/ConsoleBundle | https://github.com/CoreSphere/ConsoleBundle/blob/19679d097fb9383d54804de8392d1bfd72307c4b/Tests/DataCollector/DataCollectorTest.php | Tests/DataCollector/DataCollectorTest.php | <?php
/*
* This file is part of the CoreSphereConsoleBundle.
*
* (c) Laszlo Korte <me@laszlokorte.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CoreSphere\ConsoleBundle\Tests\DataCollector;
use CoreSphere\ConsoleBundle\DataCollector\DataCollector;
use PHPUnit_Framework_TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
final class DataCollectorTest extends PHPUnit_Framework_TestCase
{
public function testWhole()
{
$dataCollector = new DataCollector();
$requestMock = $this->prophesize(Request::class);
$responseMock = $this->prophesize(Response::class);
$dataCollector->collect($requestMock->reveal(), $responseMock->reveal());
$this->assertSame('coresphere_console', $dataCollector->getName());
}
}
| php | BSD-3-Clause | 19679d097fb9383d54804de8392d1bfd72307c4b | 2026-01-05T04:40:51.045098Z | false |
CoreSphere/ConsoleBundle | https://github.com/CoreSphere/ConsoleBundle/blob/19679d097fb9383d54804de8392d1bfd72307c4b/Tests/Console/ApplicationFactoryTest.php | Tests/Console/ApplicationFactoryTest.php | <?php
/*
* This file is part of the CoreSphereConsoleBundle.
*
* (c) Laszlo Korte <me@laszlokorte.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CoreSphere\ConsoleBundle\Tests\Console;
use CoreSphere\ConsoleBundle\Console\ApplicationFactory;
use CoreSphere\ConsoleBundle\Tests\Source\KernelWithBundlesWithCommands;
use PHPUnit_Framework_TestCase;
use Symfony\Bundle\FrameworkBundle\Console\Application;
final class ApplicationFactoryTest extends PHPUnit_Framework_TestCase
{
public function testCreate()
{
$kernel = new KernelWithBundlesWithCommands('prod', true);
$this->assertInstanceOf(
Application::class,
(new ApplicationFactory())->create($kernel)
);
}
/**
* @dataProvider provideTestCommandRegistration()
*
* @param string $environment
* @param int $commandCount
*/
public function testCommandsRegistration($environment, $commandCount)
{
$kernel = new KernelWithBundlesWithCommands($environment, false);
$application = (new ApplicationFactory())->create($kernel);
$commands = $application->all();
$this->assertCount($commandCount, $commands);
}
/**
* @return string[]
*/
public function provideTestCommandRegistration()
{
return [
['prod', 9],
['dev', 3],
['test', 2],
];
}
public function testCommandsRegistrationWithAlreadyRegisteredCommands()
{
$kernel = new KernelWithBundlesWithCommands('prod', false);
$kernel->boot();
$application = (new ApplicationFactory())->create($kernel);
$this->assertCount(9, $application->all());
}
}
| php | BSD-3-Clause | 19679d097fb9383d54804de8392d1bfd72307c4b | 2026-01-05T04:40:51.045098Z | false |
CoreSphere/ConsoleBundle | https://github.com/CoreSphere/ConsoleBundle/blob/19679d097fb9383d54804de8392d1bfd72307c4b/Tests/Executer/CommandExecuterTest.php | Tests/Executer/CommandExecuterTest.php | <?php
/*
* This file is part of the CoreSphereConsoleBundle.
*
* (c) Laszlo Korte <me@laszlokorte.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CoreSphere\ConsoleBundle\Tests\Executer;
use CoreSphere\ConsoleBundle\Executer\CommandExecuter;
use CoreSphere\ConsoleBundle\Tests\Executer\CommandExecutorSource\SomeKernel;
use PHPUnit_Framework_TestCase;
class CommandExecuterTest extends PHPUnit_Framework_TestCase
{
public function testExecute()
{
$executer = $this->createExecuterWithKernel('prod', true);
$result = $executer->execute('list');
$this->assertSame('list', $result['input']);
$this->assertContains('Lists commands', $result['output']);
$this->assertSame('prod', $result['environment']);
$this->assertSame(0, $result['error_code']);
}
public function testExecuteWithExplicitEnvironment()
{
$executer = $this->createExecuterWithKernel('prod', true);
$result = $executer->execute('list --env=dev');
$this->assertSame('list --env=dev', $result['input']);
$this->assertContains('Lists commands', $result['output']);
$this->assertSame('dev', $result['environment']);
$this->assertSame(0, $result['error_code']);
}
public function testExecuteNonExistingCommand()
{
$executer = $this->createExecuterWithKernel('dev', true);
$result = $executer->execute('someNonExistingCommand');
$this->assertSame('someNonExistingCommand', $result['input']);
$this->assertContains('Command "someNonExistingCommand" is not defined.', $result['output']);
$this->assertSame('dev', $result['environment']);
$this->assertSame(1, $result['error_code']);
}
/**
* @param string $env
* @param bool $debug
*
* @return CommandExecuter
*/
private function createExecuterWithKernel($env, $debug)
{
$kernel = new SomeKernel($env, $debug);
return new CommandExecuter($kernel);
}
}
| php | BSD-3-Clause | 19679d097fb9383d54804de8392d1bfd72307c4b | 2026-01-05T04:40:51.045098Z | false |
CoreSphere/ConsoleBundle | https://github.com/CoreSphere/ConsoleBundle/blob/19679d097fb9383d54804de8392d1bfd72307c4b/Tests/Executer/CommandExecutorSource/SomeKernel.php | Tests/Executer/CommandExecutorSource/SomeKernel.php | <?php
/*
* This file is part of the CoreSphereConsoleBundle.
*
* (c) Laszlo Korte <me@laszlokorte.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CoreSphere\ConsoleBundle\Tests\Executer\CommandExecutorSource;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel;
final class SomeKernel extends Kernel
{
/**
* {@inheritdoc}
*/
public function registerBundles()
{
return [
new FrameworkBundle(),
];
}
/**
* {@inheritdoc}
*/
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(function (ContainerBuilder $containerBuilder) {
$containerBuilder->setParameter('kernel.secret', 123);
});
}
/**
* {@inheritdoc}
*/
public function getCacheDir()
{
return sys_get_temp_dir().'/_console_tests/temp';
}
/**
* {@inheritdoc}
*/
public function getLogDir()
{
return sys_get_temp_dir().'/_console_tests/log';
}
}
| php | BSD-3-Clause | 19679d097fb9383d54804de8392d1bfd72307c4b | 2026-01-05T04:40:51.045098Z | false |
CoreSphere/ConsoleBundle | https://github.com/CoreSphere/ConsoleBundle/blob/19679d097fb9383d54804de8392d1bfd72307c4b/Executer/CommandExecuter.php | Executer/CommandExecuter.php | <?php
/*
* This file is part of the CoreSphereConsoleBundle.
*
* (c) Laszlo Korte <me@laszlokorte.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CoreSphere\ConsoleBundle\Executer;
use CoreSphere\ConsoleBundle\Contract\Executer\CommandExecuterInterface;
use CoreSphere\ConsoleBundle\Output\StringOutput;
use CoreSphere\ConsoleBundle\Formatter\HtmlOutputFormatterDecorator;
use ReflectionClass;
use Symfony\Bundle\FrameworkBundle\Console\Application as FrameworkConsoleApplication;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\HttpKernel\KernelInterface;
final class CommandExecuter implements CommandExecuterInterface
{
/**
* @var KernelInterface
*/
private $baseKernel;
public function __construct(KernelInterface $baseKernel)
{
$this->baseKernel = $baseKernel;
}
/**
* {@inheritdoc}
*/
public function execute($commandString)
{
$input = new StringInput($commandString);
$output = new StringOutput();
$application = $this->getApplication($input);
$formatter = $output->getFormatter();
$kernel = $application->getKernel();
chdir($kernel->getRootDir().'/..');
$input->setInteractive(false);
$formatter->setDecorated(true);
$output->setFormatter(new HtmlOutputFormatterDecorator($formatter));
$application->setAutoExit(false);
$errorCode = $application->run($input, $output);
return [
'input' => $commandString,
'output' => $output->getBuffer(),
'environment' => $kernel->getEnvironment(),
'error_code' => $errorCode,
];
}
/**
* @return FrameworkConsoleApplication
*/
private function getApplication(InputInterface $input)
{
$kernel = $this->getKernel($input);
return new FrameworkConsoleApplication($kernel);
}
/**
* @return KernelInterface
*/
private function getKernel(InputInterface $input)
{
$env = $input->getParameterOption(['--env', '-e'], $this->baseKernel->getEnvironment());
$debug = !$input->hasParameterOption(['--no-debug', '']);
if ($env === $this->baseKernel->getEnvironment() && $debug === $this->baseKernel->isDebug()) {
return $this->baseKernel;
}
$kernelClass = new ReflectionClass($this->baseKernel);
return $kernelClass->newInstance($env, $debug);
}
}
| php | BSD-3-Clause | 19679d097fb9383d54804de8392d1bfd72307c4b | 2026-01-05T04:40:51.045098Z | false |
thomseddon/cakephp-oauth-server | https://github.com/thomseddon/cakephp-oauth-server/blob/88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324/Model/AuthCode.php | Model/AuthCode.php | <?php
App::uses('OAuthAppModel', 'OAuth.Model');
/**
* AuthCode Model
*
* @property Client $Client
* @property User $User
*/
class AuthCode extends OAuthAppModel {
/**
* Primary key field
*
* @var string
*/
public $primaryKey = 'code';
/**
* Display field
*
* @var string
*/
public $displayField = 'code';
/**
* Validation rules
*
* @var array
*/
public $validate = array(
'code' => array(
'notempty' => array(
'rule' => array('notempty'),
),
'isUnique' => array(
'rule' => array('isUnique'),
),
),
'client_id' => array(
'notempty' => array(
'rule' => array('notempty'),
),
),
'user_id' => array(
'notempty' => array(
'rule' => array('notempty'),
),
),
'redirect_uri' => array(
'notempty' => array(
'rule' => array('notempty'),
),
),
'expires' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
);
public $actsAs = array(
'OAuth.HashedField' => array(
'fields' => 'code',
),
);
/**
* belongsTo associations
*
* @var array
*/
public $belongsTo = array(
'Client' => array(
'className' => 'OAuth.Client',
'foreignKey' => 'client_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
| php | MIT | 88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324 | 2026-01-05T04:40:52.970980Z | false |
thomseddon/cakephp-oauth-server | https://github.com/thomseddon/cakephp-oauth-server/blob/88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324/Model/OAuthAppModel.php | Model/OAuthAppModel.php | <?php
/**
* Description of OAuthAppModel
*
* @author Thom
*/
class OAuthAppModel extends AppModel {
//put your code here
}
| php | MIT | 88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324 | 2026-01-05T04:40:52.970980Z | false |
thomseddon/cakephp-oauth-server | https://github.com/thomseddon/cakephp-oauth-server/blob/88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324/Model/Client.php | Model/Client.php | <?php
App::uses('OAuthAppModel', 'OAuth.Model');
App::uses('String', 'Utility');
/**
* Client Model
*
* @property AccessToken $AccessToken
* @property AuthCode $AuthCode
* @property RefreshToken $RefreshToken
*/
class Client extends OAuthAppModel {
/**
* Primary key field
*
* @var string
*/
public $primaryKey = 'client_id';
/**
* Display field
*
* @var string
*/
public $displayField = 'client_id';
/**
* Secret to distribute when using addClient
*
* @var type
*/
protected $addClientSecret = false;
/**
* Validation rules
*
* @var array
*/
public $validate = array(
'client_id' => array(
'isUnique' => array(
'rule' => array('isUnique'),
),
'notempty' => array(
'rule' => array('notempty'),
),
),
'redirect_uri' => array(
'notempty' => array(
'rule' => array('notempty'),
),
),
);
public $actsAs = array(
'OAuth.HashedField' => array(
'fields' => array(
'client_secret'
),
),
);
/**
* hasMany associations
*
* @var array
*/
public $hasMany = array(
'AccessToken' => array(
'className' => 'OAuth.AccessToken',
'foreignKey' => 'client_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'AuthCode' => array(
'className' => 'OAuth.AuthCode',
'foreignKey' => 'client_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'RefreshToken' => array(
'className' => 'OAuth.RefreshToken',
'foreignKey' => 'client_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
/**
* AddClient
*
* Convinience function for adding client, will create a uuid client_id and random secret
*
* @param mixed $data Either an array (e.g. $controller->request->data) or string redirect_uri
* @return booleen Success of failure
*/
public function add($data = null) {
$this->data['Client'] = array();
if (is_array($data) && is_array($data['Client']) && array_key_exists('redirect_uri', $data['Client'])) {
$this->data['Client']['redirect_uri'] = $data['Client']['redirect_uri'];
} elseif (is_string($data)) {
$this->data['Client']['redirect_uri'] = $data;
} else {
return false;
}
/**
* in case you have additional fields in the clients table such as name, description etc
* and you are using $data['Client']['name'], etc to save
**/
if (is_array($data['Client'])) {
$this->data['Client'] = array_merge($data['Client'], $this->data['Client']);
}
//You may wish to change this
$this->data['Client']['client_id'] = base64_encode(uniqid() . substr(uniqid(), 11, 2)); // e.g. NGYcZDRjODcxYzFkY2Rk (seems popular format)
//$this->data['Client']['client_id'] = uniqid(); // e.g. 4f3d4c8602346
//$this->data['Client']['client_id'] = str_replace('.', '', uniqid('', true)); // e.g. 4f3d4c860235a529118898
//$this->data['Client']['client_id'] = str_replace('-', '', String::uuid()); // e.g. 4f3d4c80cb204b6a8e580a006f97281a
$this->addClientSecret = $this->newClientSecret();
$this->data['Client']['client_secret'] = $this->addClientSecret;
return $this->save($this->data);
}
/**
* Create a new, pretty (as in moderately, not beautiful - that can't be guaranteed ;-) random client secret
*
* @return string
*/
public function newClientSecret() {
$length = 40;
$chars = '@#!%*+/-=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$str = '';
$count = strlen($chars);
while ($length--) {
$str .= $chars[mt_rand(0, $count - 1)];
}
return OAuthComponent::hash($str);
}
public function afterSave($created, $options = array()) {
if ($this->addClientSecret) {
$this->data['Client']['client_secret'] = $this->addClientSecret;
}
return true;
}
} | php | MIT | 88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324 | 2026-01-05T04:40:52.970980Z | false |
thomseddon/cakephp-oauth-server | https://github.com/thomseddon/cakephp-oauth-server/blob/88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324/Model/AccessToken.php | Model/AccessToken.php | <?php
App::uses('OAuthAppModel', 'OAuth.Model');
/**
* AccessToken Model
*
* @property Client $Client
* @property User $User
*/
class AccessToken extends OAuthAppModel {
/**
* Primary key field
*
* @var string
*/
public $primaryKey = 'oauth_token';
/**
* Display field
*
* @var string
*/
public $displayField = 'oauth_token';
/**
* Validation rules
*
* @var array
*/
public $validate = array(
'oauth_token' => array(
'notempty' => array(
'rule' => array('notempty'),
),
'isUnique' => array(
'rule' => array('isUnique'),
)
),
'client_id' => array(
'notempty' => array(
'rule' => array('notempty'),
),
),
'user_id' => array(
'notempty' => array(
'rule' => array('notempty'),
),
),
'expires' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
);
public $actsAs = array(
'OAuth.HashedField' => array(
'fields' => 'oauth_token',
),
);
/**
* belongsTo associations
*
* @var array
*/
public $belongsTo = array(
'Client' => array(
'className' => 'OAuth.Client',
'foreignKey' => 'client_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
| php | MIT | 88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324 | 2026-01-05T04:40:52.970980Z | false |
thomseddon/cakephp-oauth-server | https://github.com/thomseddon/cakephp-oauth-server/blob/88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324/Model/RefreshToken.php | Model/RefreshToken.php | <?php
App::uses('OAuthAppModel', 'OAuth.Model');
/**
* RefreshToken Model
*
* @property Client $Client
* @property User $User
*/
class RefreshToken extends OAuthAppModel {
/**
* Primary key field
*
* @var string
*/
public $primaryKey = 'refresh_token';
/**
* Display field
*
* @var string
*/
public $displayField = 'refresh_token';
/**
* Validation rules
*
* @var array
*/
public $validate = array(
'refresh_token' => array(
'notempty' => array(
'rule' => array('notempty'),
),
'isUnique' => array(
'rule' => array('isUnique'),
)
),
'client_id' => array(
'notempty' => array(
'rule' => array('notempty'),
),
),
'user_id' => array(
'notempty' => array(
'rule' => array('notempty'),
),
),
'expires' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
);
public $actsAs = array(
'OAuth.HashedField' => array(
'fields' => 'refresh_token',
),
);
/**
* belongsTo associations
*
* @var array
*/
public $belongsTo = array(
'Client' => array(
'className' => 'OAuth.Client',
'foreignKey' => 'client_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
| php | MIT | 88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324 | 2026-01-05T04:40:52.970980Z | false |
thomseddon/cakephp-oauth-server | https://github.com/thomseddon/cakephp-oauth-server/blob/88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324/Model/Behavior/HashedFieldBehavior.php | Model/Behavior/HashedFieldBehavior.php | <?php
App::uses('ModelBehavior', 'Model');
App::uses('Security', 'Utility');
/**
* Enable automatic field hashing when in Model::save() Model::find()
*/
class HashedFieldBehavior extends ModelBehavior {
/**
* Behavior defaults
*/
protected $_defaults = array(
'fields' => array(),
);
/**
* Setup behavior
*/
public function setup(Model $Model, $config = array()) {
parent::setup($Model, $config);
$this->settings[$Model->name] = Hash::merge($this->_defaults, $config);
}
/**
* Hash field when present in model data (POSTed data)
*/
public function beforeSave(Model $Model, $options = array()) {
$setting = $this->settings[$Model->name];
foreach ((array) $setting['fields'] as $field) {
if (array_key_exists($field, $Model->data[$Model->alias])) {
$data = $Model->data[$Model->alias][$field];
$Model->data[$Model->alias][$field] = Security::hash($data, null, true);
}
}
return true;
}
/**
* Hash condition when it contains a field specified in setting
*/
public function beforeFind(Model $Model, $queryData) {
$setting = $this->settings[$Model->name];
$conditions =& $queryData['conditions'];
foreach ((array) $setting['fields'] as $field) {
$escapeField = $Model->escapeField($field);
if (array_key_exists($field, (array)$conditions)) {
$queryField = $field;
} elseif (array_key_exists($escapeField, (array)$conditions)) {
$queryField = $escapeField;
}
if (isset($queryField)) {
$data = $conditions[$queryField];
$conditions[$queryField] = Security::hash($data, null, true);
}
}
return $queryData;
}
}
| php | MIT | 88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324 | 2026-01-05T04:40:52.970980Z | false |
thomseddon/cakephp-oauth-server | https://github.com/thomseddon/cakephp-oauth-server/blob/88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324/Controller/OAuthController.php | Controller/OAuthController.php | <?php
/**
* CakePHP OAuth Server Plugin
*
* This is an example controller providing the necessary endpoints
*
* @author Thom Seddon <thom@seddonmedia.co.uk>
* @see https://github.com/thomseddon/cakephp-oauth-server
*
*/
App::uses('OAuthAppController', 'OAuth.Controller');
/**
* OAuthController
*
*/
class OAuthController extends OAuthAppController {
public $components = array('OAuth.OAuth', 'Auth', 'Session', 'Security');
public $uses = array('Users');
public $helpers = array('Form');
private $blackHoled = false;
/**
* beforeFilter
*
*/
public function beforeFilter() {
parent::beforeFilter();
$this->OAuth->authenticate = array('fields' => array('username' => 'email'));
$this->Auth->allow($this->OAuth->allowedActions);
$this->Security->blackHoleCallback = 'blackHole';
}
/**
* Example Authorize Endpoint
*
* Send users here first for authorization_code grant mechanism
*
* Required params (GET or POST):
* - response_type = code
* - client_id
* - redirect_url
*
*/
public function authorize() {
if (!$this->Auth->loggedIn()) {
$this->redirect(array('action' => 'login', '?' => $this->request->query));
}
if ($this->request->is('post')) {
$this->validateRequest();
$userId = $this->Auth->user('id');
if ($this->Session->check('OAuth.logout')) {
$this->Auth->logout();
$this->Session->delete('OAuth.logout');
}
//Did they accept the form? Adjust accordingly
$accepted = $this->request->data['accept'] == 'Yep';
try {
$this->OAuth->finishClientAuthorization($accepted, $userId, $this->request->data['Authorize']);
} catch (OAuth2RedirectException $e) {
$e->sendHttpResponse();
}
}
// Clickjacking prevention (supported by IE8+, FF3.6.9+, Opera10.5+, Safari4+, Chrome 4.1.249.1042+)
$this->response->header('X-Frame-Options: DENY');
if ($this->Session->check('OAuth.params')) {
$OAuthParams = $this->Session->read('OAuth.params');
$this->Session->delete('OAuth.params');
} else {
try {
$OAuthParams = $this->OAuth->getAuthorizeParams();
} catch (Exception $e){
$e->sendHttpResponse();
}
}
$this->set(compact('OAuthParams'));
}
/**
* Example Login Action
*
* Users must authorize themselves before granting the app authorization
* Allows login state to be maintained after authorization
*
*/
public function login () {
$OAuthParams = $this->OAuth->getAuthorizeParams();
if ($this->request->is('post')) {
$this->validateRequest();
//Attempted login
if ($this->Auth->login()) {
//Write this to session so we can log them out after authenticating
$this->Session->write('OAuth.logout', true);
//Write the auth params to the session for later
$this->Session->write('OAuth.params', $OAuthParams);
//Off we go
$this->redirect(array('action' => 'authorize'));
} else {
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
$this->set(compact('OAuthParams'));
}
/**
* Example Token Endpoint - this is where clients can retrieve an access token
*
* Grant types and parameters:
* 1) authorization_code - exchange code for token
* - code
* - client_id
* - client_secret
*
* 2) refresh_token - exchange refresh_token for token
* - refresh_token
* - client_id
* - client_secret
*
* 3) password - exchange raw details for token
* - username
* - password
* - client_id
* - client_secret
*
*/
public function token() {
$this->autoRender = false;
try {
$this->OAuth->grantAccessToken();
} catch (OAuth2ServerException $e) {
$e->sendHttpResponse();
}
}
/**
* Quick and dirty example implementation for protecetd resource
*
* User accesible via $this->OAuth->user();
* Single fields avaliable via $this->OAuth->user("id");
*
*/
public function userinfo() {
$this->layout = null;
$user = $this->OAuth->user();
$this->set(compact('user'));
}
/**
* Blackhold callback
*
* OAuth requests will fail postValidation, so rather than disabling it completely
* if the request does fail this check we store it in $this->blackHoled and then
* when handling our forms we can use $this->validateRequest() to check if there
* were any errors and handle them with an exception.
* Requests that fail for reasons other than postValidation are handled here immediately
* using the best guess for if it was a form or OAuth
*
* @param string $type
*/
public function blackHole($type) {
$this->blackHoled = $type;
if ($type != 'auth') {
if (isset($this->request->data['_Token'])) {
//Probably our form
$this->validateRequest();
} else {
//Probably OAuth
$e = new OAuth2ServerException(OAuth2::HTTP_BAD_REQUEST, OAuth2::ERROR_INVALID_REQUEST, 'Request Invalid.');
$e->sendHttpResponse();
}
}
}
/**
* Check for any Security blackhole errors
*
* @throws BadRequestException
*/
private function validateRequest() {
if ($this->blackHoled) {
//Has been blackholed before - naughty
throw new BadRequestException(__d('OAuth', 'The request has been black-holed'));
}
}
}
| php | MIT | 88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324 | 2026-01-05T04:40:52.970980Z | false |
thomseddon/cakephp-oauth-server | https://github.com/thomseddon/cakephp-oauth-server/blob/88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324/Controller/OAuthAppController.php | Controller/OAuthAppController.php | <?php
App::uses('AppController', 'Controller');
App::import('Vendor', 'oauth2-php/lib/OAuth2');
App::import('Vendor', 'oauth2-php/lib/IOAuth2Storage');
App::import('Vendor', 'oauth2-php/lib/IOAuth2GrantCode');
App::import('Vendor', 'oauth2-php/lib/IOAuth2RefreshTokens');
/**
* Description of OAuthAppController
*
* @author Thom
*/
class OAuthAppController extends AppController {
//put your code here
}
| php | MIT | 88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324 | 2026-01-05T04:40:52.970980Z | false |
thomseddon/cakephp-oauth-server | https://github.com/thomseddon/cakephp-oauth-server/blob/88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324/Controller/Component/OAuthComponent.php | Controller/Component/OAuthComponent.php | <?php
/**
* CakePHP OAuth Server Plugin
*
* This is the main component.
*
* It provides:
* - Cakey interface to the OAuth2-php library
* - AuthComponent like action allow/deny's
* - Easy access to user associated to an access token
* - More!?
*
* @author Thom Seddon <thom@seddonmedia.co.uk>
* @see https://github.com/thomseddon/cakephp-oauth-server
*
*/
App::uses('Component', 'Controller');
App::uses('Router', 'Routing');
App::uses('Security', 'Utility');
App::uses('Hash', 'Utility');
App::uses('AuthComponent', 'Controller');
App::import('Vendor', 'oauth2-php/lib/OAuth2');
App::import('Vendor', 'oauth2-php/lib/IOAuth2Storage');
App::import('Vendor', 'oauth2-php/lib/IOAuth2RefreshTokens');
App::import('Vendor', 'oauth2-php/lib/IOAuth2GrantUser');
App::import('Vendor', 'oauth2-php/lib/IOAuth2GrantCode');
class OAuthComponent extends Component implements IOAuth2Storage, IOAuth2RefreshTokens, IOAuth2GrantUser, IOAuth2GrantCode {
/**
* AccessToken object.
*
* @var object
*/
public $AccessToken;
/**
* Array of allowed actions
*
* @var array
*/
protected $allowedActions = array('token', 'authorize', 'login');
/**
* An array containing the model and fields to authenticate users against
*
* Inherits theses defaults:
*
* $this->OAuth->authenticate = array(
* 'userModel' => 'User',
* 'fields' => array(
* 'username' => 'username',
* 'password' => 'password'
* )
* );
*
* Which can be overridden in your beforeFilter:
*
* $this->OAuth->authenticate = array(
* 'fields' => array(
* 'username' => 'email'
* )
* );
*
*
* $this->OAuth->authenticate
*
* @var array
*/
public $authenticate;
/**
* Defaults for $authenticate
*
* @var array
*/
protected $_authDefaults = array(
'userModel' => 'User',
'fields' => array('username' => 'username', 'password' => 'password')
);
/**
* AuthCode object.
*
* @var object
*/
public $AuthCode;
/**
* Clients object.
*
* @var object
*/
public $Client;
/**
* Array of globally supported grant types
*
* By default = array('authorization_code', 'refresh_token', 'password');
* Other grant mechanisms are not supported in the current release
*
* @var array
*/
public $grantTypes = array('authorization_code', 'refresh_token', 'password');
/**
* OAuth2 Object
*
* @var object
*/
public $OAuth2;
/**
* RefreshToken object.
*
* @var object
*/
public $RefreshToken;
/**
* User object
*
* @var object
*/
public $User;
/**
* Static storage for current user
*
* @var array
*/
protected $_user = false;
/**
* Constructor - Adds class associations
*
* @see OAuth2::__construct().
*/
public function __construct(ComponentCollection $collection, $settings = array()) {
parent::__construct($collection, $settings);
$this->OAuth2 = new OAuth2($this);
$this->AccessToken = ClassRegistry::init(array('class' => 'OAuth.AccessToken', 'alias' => 'AccessToken'));
$this->AuthCode = ClassRegistry::init(array('class' => 'OAuth.AuthCode', 'alias' => 'AuthCode'));
$this->Client = ClassRegistry::init(array('class' => 'OAuth.Client', 'alias' => 'Client'));
$this->RefreshToken = ClassRegistry::init(array('class' => 'OAuth.RefreshToken', 'alias' => 'RefreshToken'));
}
/**
* Initializes OAuthComponent for use in the controller
*
* @param Controller $controller A reference to the instantiating controller object
* @return void
*/
public function initialize(Controller $controller) {
$this->request = $controller->request;
$this->response = $controller->response;
$this->_methods = $controller->methods;
if (Configure::read('debug') > 0) {
Debugger::checkSecurityKeys();
}
}
/**
* Main engine that checks valid access_token and stores the associated user for retrival
*
* @see AuthComponent::startup()
*
* @param type $controller
* @return boolean
*/
public function startup(Controller $controller) {
$methods = array_flip(array_map('strtolower', $controller->methods));
$action = strtolower($controller->request->params['action']);
$this->authenticate = Hash::merge($this->_authDefaults, $this->authenticate);
$this->User = ClassRegistry::init(array(
'class' => $this->authenticate['userModel'],
'alias' => $this->authenticate['userModel']
));
$isMissingAction = (
$controller->scaffold === false &&
!isset($methods[$action])
);
if ($isMissingAction) {
return true;
}
$allowedActions = $this->allowedActions;
$isAllowed = (
$this->allowedActions == array('*') ||
in_array($action, array_map('strtolower', $allowedActions))
);
if ($isAllowed) {
return true;
}
try {
$this->isAuthorized();
$this->user(null, $this->AccessToken->id);
} catch (OAuth2AuthenticateException $e) {
$e->sendHttpResponse();
return false;
}
return true;
}
/**
* Checks if user is valid using OAuth2-php library
*
* @see OAuth2::getBearerToken()
* @see OAuth2::verifyAccessToken()
*
* @return boolean true if carrying valid token, false if not
*/
public function isAuthorized() {
try {
$this->AccessToken->id = $this->getBearerToken();
$this->verifyAccessToken($this->AccessToken->id);
} catch (OAuth2AuthenticateException $e) {
return false;
}
return true;
}
/**
* Takes a list of actions in the current controller for which authentication is not required, or
* no parameters to allow all actions.
*
* You can use allow with either an array, or var args.
*
* `$this->OAuth->allow(array('edit', 'add'));` or
* `$this->OAuth->allow('edit', 'add');` or
* `$this->OAuth->allow();` to allow all actions.
*
* @param string|array $action,... Controller action name or array of actions
* @return void
*/
public function allow($action = null) {
$args = func_get_args();
if (empty($args) || $action === null) {
$this->allowedActions = $this->_methods;
} else {
if (isset($args[0]) && is_array($args[0])) {
$args = $args[0];
}
$this->allowedActions = array_merge($this->allowedActions, $args);
}
}
/**
* Removes items from the list of allowed/no authentication required actions.
*
* You can use deny with either an array, or var args.
*
* `$this->OAuth->deny(array('edit', 'add'));` or
* `$this->OAuth->deny('edit', 'add');` or
* `$this->OAuth->deny();` to remove all items from the allowed list
*
* @param string|array $action,... Controller action name or array of actions
* @return void
* @see OAuthComponent::allow()
*/
public function deny($action = null) {
$args = func_get_args();
if (empty($args) || $action === null) {
$this->allowedActions = array();
} else {
if (isset($args[0]) && is_array($args[0])) {
$args = $args[0];
}
foreach ($args as $arg) {
$i = array_search($arg, $this->allowedActions);
if (is_int($i)) {
unset($this->allowedActions[$i]);
}
}
$this->allowedActions = array_values($this->allowedActions);
}
}
/**
* Gets the user associated to the current access token.
*
* Will return array of all user fields by default
* You can specify specific fields like so:
*
* $id = $this->OAuth->user('id');
*
* @param type $field
* @return mixed array of user fields if $field is blank, string value if $field is set and $fields is avaliable, false on failure
*/
public function user($field = null, $token = null) {
if (!$this->_user) {
$this->AccessToken->bindModel(array(
'belongsTo' => array(
'User' => array(
'className' => $this->authenticate['userModel'],
'foreignKey' => 'user_id'
)
)
));
$token = empty($token) ? $this->getBearerToken() : $token;
$data = $this->AccessToken->find('first', array(
'conditions' => array('oauth_token' => $token),
'recursive' => 1
));
if (!$data) {
return false;
}
$this->_user = $data['User'];
}
if (empty($field)) {
return $this->_user;
} elseif (isset($this->_user[$field])) {
return $this->_user[$field];
}
return false;
}
/**
* Convenience function for hashing client_secret (or whatever else)
*
* @param string $password
* @return string Hashed password
*/
public static function hash($password) {
return Security::hash($password, null, true);
}
/**
* Convenience function to invalidate all a users tokens, for example when they change their password
*
* @param int $user_id
* @param string $tokens 'both' (default) to remove both AccessTokens and RefreshTokens or remove just one type using 'access' or 'refresh'
*/
public function invalidateUserTokens($user_id, $tokens = 'both') {
if ($tokens == 'access' || $tokens == 'both') {
$this->AccessToken->deleteAll(array('user_id' => $user_id), false);
}
if ($tokens == 'refresh' || $tokens == 'both') {
$this->RefreshToken->deleteAll(array('user_id' => $user_id), false);
}
}
/**
* Fakes the OAuth2.php vendor class extension for variables
*
* @param string $name
* @return mixed
*/
public function __get($name) {
if (isset($this->OAuth2->{$name})) {
try {
return $this->OAuth2->{$name};
} catch (Exception $e) {
$e->sendHttpResponse();
}
}
}
/**
* Fakes the OAuth2.php vendor class extension for methods
*
* @param string $name
* @param mixed $arguments
* @return mixed
* @throws Exception
*/
public function __call($name, $arguments) {
if (method_exists($this->OAuth2, $name)) {
try {
return call_user_func_array(array($this->OAuth2, $name), $arguments);
} catch (Exception $e) {
if (method_exists($e, 'sendHttpResponse')) {
$e->sendHttpResponse();
}
throw $e;
}
}
}
/**
* Below are the library interface implementations
*
*/
/**
* Check client details are valid
*
* @see IOAuth2Storage::checkClientCredentials().
*
* @param string $client_id
* @param string $client_secret
* @return mixed array of client credentials if valid, false if not
*/
public function checkClientCredentials($client_id, $client_secret = null) {
$conditions = array('client_id' => $client_id);
if ($client_secret) {
$conditions['client_secret'] = $client_secret;
}
$client = $this->Client->find('first', array(
'conditions' => $conditions,
'recursive' => -1
));
if ($client) {
return $client['Client'];
};
return false;
}
/**
* Get client details
*
* @see IOAuth2Storage::getClientDetails().
*
* @param string $client_id
* @return boolean
*/
public function getClientDetails($client_id) {
$client = $this->Client->find('first', array(
'conditions' => array('client_id' => $client_id),
'fields' => array('client_id', 'redirect_uri'),
'recursive' => -1
));
if ($client) {
return $client['Client'];
}
return false;
}
/**
* Retrieve access token
*
* @see IOAuth2Storage::getAccessToken().
*
* @param string $oauth_token
* @return mixed AccessToken array if valid, null if not
*/
public function getAccessToken($oauth_token) {
$accessToken = $this->AccessToken->find('first', array(
'conditions' => array('oauth_token' => $oauth_token),
'recursive' => -1,
));
if ($accessToken) {
return $accessToken['AccessToken'];
}
return null;
}
/**
* Set access token
*
* @see IOAuth2Storage::setAccessToken().
*
* @param string $oauth_token
* @param string $client_id
* @param int $user_id
* @param string $expires
* @param string $scope
* @return boolean true if successfull, false if failed
*/
public function setAccessToken($oauth_token, $client_id, $user_id, $expires, $scope = null) {
$data = array(
'oauth_token' => $oauth_token,
'client_id' => $client_id,
'user_id' => $user_id,
'expires' => $expires,
'scope' => $scope
);
$this->AccessToken->create();
return $this->AccessToken->save(array('AccessToken' => $data));
}
/**
* Partial implementation, just checks globally avaliable grant types
*
* @see IOAuth2Storage::checkRestrictedGrantType()
*
* @param string $client_id
* @param string $grant_type
* @return boolean If grant type is availiable to client
*/
public function checkRestrictedGrantType($client_id, $grant_type) {
return in_array($grant_type, $this->grantTypes);
}
/**
* Grant type: refresh_token
*
* @see IOAuth2RefreshTokens::getRefreshToken()
*
* @param string $refresh_token
* @return mixed RefreshToken if valid, null if not
*/
public function getRefreshToken($refresh_token) {
$refreshToken = $this->RefreshToken->find('first', array(
'conditions' => array('refresh_token' => $refresh_token),
'recursive' => -1
));
if ($refreshToken) {
return $refreshToken['RefreshToken'];
}
return null;
}
/**
* Grant type: refresh_token
*
* @see IOAuth2RefreshTokens::setRefreshToken()
*
* @param string $refresh_token
* @param int $client_id
* @param string $user_id
* @param string $expires
* @param string $scope
* @return boolean true if successfull, false if fail
*/
public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null) {
$data = array(
'refresh_token' => $refresh_token,
'client_id' => $client_id,
'user_id' => $user_id,
'expires' => $expires,
'scope' => $scope
);
$this->RefreshToken->create();
return $this->RefreshToken->save(array('RefreshToken' => $data));
}
/**
* Grant type: refresh_token
*
* @see IOAuth2RefreshTokens::unsetRefreshToken()
*
* @param string $refresh_token
* @return boolean true if successfull, false if not
*/
public function unsetRefreshToken($refresh_token) {
return $this->RefreshToken->delete($refresh_token);
}
/**
* Grant type: user_credentials
*
* @see IOAuth2GrantUser::checkUserCredentials()
*
* @param type $client_id
* @param type $username
* @param type $password
*/
public function checkUserCredentials($client_id, $username, $password) {
$user = $this->User->find('first', array(
'conditions' => array(
$this->authenticate['fields']['username'] => $username,
$this->authenticate['fields']['password'] => AuthComponent::password($password)
),
'recursive' => -1
));
if ($user) {
return array('user_id' => $user['User'][$this->User->primaryKey]);
}
return false;
}
/**
* Grant type: authorization_code
*
* @see IOAuth2GrantCode::getAuthCode()
*
* @param string $code
* @return AuthCode if valid, null of not
*/
public function getAuthCode($code) {
$authCode = $this->AuthCode->find('first', array(
'conditions' => array('code' => $code),
'recursive' => -1
));
if ($authCode) {
return $authCode['AuthCode'];
}
return null;
}
/**
* Grant type: authorization_code
*
* @see IOAuth2GrantCode::setAuthCode().
*
* @param string $code
* @param string $client_id
* @param int $user_id
* @param string $redirect_uri
* @param string $expires
* @param string $scope
* @return boolean true if successfull, otherwise false
*/
public function setAuthCode($code, $client_id, $user_id, $redirect_uri, $expires, $scope = null) {
$data = array(
'code' => $code,
'client_id' => $client_id,
'user_id' => $user_id,
'redirect_uri' => $redirect_uri,
'expires' => $expires,
'scope' => $scope
);
$this->AuthCode->create();
return $this->AuthCode->save(array('AuthCode' => $data));
}
}
| php | MIT | 88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324 | 2026-01-05T04:40:52.970980Z | false |
thomseddon/cakephp-oauth-server | https://github.com/thomseddon/cakephp-oauth-server/blob/88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324/Test/Case/AllOAuthTestsTest.php | Test/Case/AllOAuthTestsTest.php | <?php
class AllOAuthTestsTest extends PHPUnit_Framework_TestSuite {
public static function suite() {
$suite = new CakeTestSuite('OAuth Tests');
$path = CakePlugin::path('OAuth') . 'Test' . DS . 'Case' . DS;
$suite->addTestDirectory($path . 'Model' . DS . 'Behavior');
return $suite;
}
}
| php | MIT | 88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324 | 2026-01-05T04:40:52.970980Z | false |
thomseddon/cakephp-oauth-server | https://github.com/thomseddon/cakephp-oauth-server/blob/88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324/Test/Case/Model/Behavior/HashedFieldBehaviorTest.php | Test/Case/Model/Behavior/HashedFieldBehaviorTest.php | <?php
App::uses('CakeTestCase', 'TestSuite');
class HashedFieldBehaviorTest extends CakeTestCase {
public $fixtures = array(
'plugin.o_auth.access_token',
);
protected $_clientId = '1234567890';
protected $_token = '0123456789abcdefghijklmnopqrstuvwxyz';
public function setUp() {
$this->AccessToken = ClassRegistry::init('OAuth.AccessToken');
$this->AccessToken->recursive = -1;
}
protected function _createToken() {
$this->AccessToken->create(array(
'client_id' => $this->_clientId,
'oauth_token' => $this->_token,
'user_id' => 69,
'expires' => time() + 86400,
));
$this->AccessToken->save();
}
public function testBeforeSave() {
$this->_createToken();
$result = $this->AccessToken->findByClientId($this->_clientId);
$expected = Security::hash($this->_token, null, true);
$this->assertEquals($expected, $result['AccessToken']['oauth_token']);
}
public function testBeforeFind() {
$this->_createToken();
$result = $this->AccessToken->find('first', array(
'conditions' => array(
'oauth_token' => $this->_token,
),
));
$this->assertEquals($this->_clientId, $result['AccessToken']['client_id']);
$this->assertNotEquals($this->_token, $result['AccessToken']['oauth_token']);
}
/**
* test saving with missing oauth_token in POSTed data does not corrupt value
*/
public function testSavingWithMissingToken() {
$this->_createToken();
$baseline = $this->AccessToken->find('first');
$this->assertNull($baseline['AccessToken']['scope']);
$updated = $baseline;
$updated['AccessToken']['scope'] = 'all';
unset($updated['AccessToken']['oauth_token']);
$this->assertFalse(array_key_exists('oauth_token', $updated));
$this->AccessToken->save($updated);
$result = $this->AccessToken->findByClientId($baseline['AccessToken']['client_id']);
$this->assertEquals('all', $result['AccessToken']['scope']);
$expected = Security::hash($this->_token, null, true);
$this->assertEquals($expected, $result['AccessToken']['oauth_token']);
}
}
| php | MIT | 88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324 | 2026-01-05T04:40:52.970980Z | false |
thomseddon/cakephp-oauth-server | https://github.com/thomseddon/cakephp-oauth-server/blob/88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324/Test/Fixture/AccessTokenFixture.php | Test/Fixture/AccessTokenFixture.php | <?php
/**
* AccessTokenFixture
*
*/
class AccessTokenFixture extends CakeTestFixture {
/**
* Fields
*
* @var array
*/
public $fields = array(
'oauth_token' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 40, 'key' => 'primary', 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
'client_id' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 36, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
'user_id' => array('type' => 'integer', 'null' => false, 'default' => null),
'expires' => array('type' => 'integer', 'null' => false, 'default' => null),
'scope' => array('type' => 'string', 'null' => true, 'default' => null, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
'indexes' => array(
'PRIMARY' => array('column' => 'oauth_token', 'unique' => 1)
),
'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'MyISAM')
);
/**
* Records
*
* @var array
*/
public $records = array(
);
}
| php | MIT | 88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324 | 2026-01-05T04:40:52.970980Z | false |
thomseddon/cakephp-oauth-server | https://github.com/thomseddon/cakephp-oauth-server/blob/88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324/Config/routes.php | Config/routes.php | <?php
Router::connect('/oauth/:action/*', array('controller' => 'OAuth', 'plugin' => 'o_auth'));
| php | MIT | 88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324 | 2026-01-05T04:40:52.970980Z | false |
thomseddon/cakephp-oauth-server | https://github.com/thomseddon/cakephp-oauth-server/blob/88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324/Config/Migration/1339124026_firstmigrationoauth.php | Config/Migration/1339124026_firstmigrationoauth.php | <?php
class FirstMigrationOAuth extends CakeMigration {
/**
* Migration description
*
* @var string
* @access public
*/
public $description = '';
/**
* Actions to be performed
*
* @var array $migration
* @access public
*/
public $migration = array(
'up' => array(
'create_table' => array(
'access_tokens' => array(
'oauth_token' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 40, 'key' => 'primary', 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
'client_id' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 36, 'collate' => 'utf8_general_ci', 'charset' => 'utf8', 'after' => 'oauth_token'),
'user_id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'after' => 'client_id'),
'expires' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'after' => 'user_id'),
'scope' => array('type' => 'string', 'null' => true, 'default' => NULL, 'collate' => 'utf8_general_ci', 'charset' => 'utf8', 'after' => 'expires'),
'indexes' => array(
'PRIMARY' => array('column' => 'oauth_token', 'unique' => 1),
),
'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'MyISAM'),
),
'auth_codes' => array(
'code' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 40, 'key' => 'primary', 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
'client_id' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 36, 'collate' => 'utf8_general_ci', 'charset' => 'utf8', 'after' => 'code'),
'user_id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'after' => 'client_id'),
'redirect_uri' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 200, 'collate' => 'utf8_general_ci', 'charset' => 'utf8', 'after' => 'user_id'),
'expires' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'after' => 'redirect_uri'),
'scope' => array('type' => 'string', 'null' => true, 'default' => NULL, 'collate' => 'utf8_general_ci', 'charset' => 'utf8', 'after' => 'expires'),
'indexes' => array(
'PRIMARY' => array('column' => 'code', 'unique' => 1),
),
'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'MyISAM'),
),
'clients' => array(
'client_id' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 20, 'key' => 'primary', 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
'client_secret' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 40, 'collate' => 'utf8_general_ci', 'charset' => 'utf8', 'after' => 'client_id'),
'redirect_uri' => array('type' => 'string', 'null' => false, 'default' => NULL, 'collate' => 'utf8_general_ci', 'charset' => 'utf8', 'after' => 'client_secret'),
'user_id' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'after' => 'redirect_uri'),
'indexes' => array(
'PRIMARY' => array('column' => 'client_id', 'unique' => 1),
),
'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'MyISAM'),
),
'refresh_tokens' => array(
'refresh_token' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 40, 'key' => 'primary', 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
'client_id' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 36, 'collate' => 'utf8_general_ci', 'charset' => 'utf8', 'after' => 'refresh_token'),
'user_id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'after' => 'client_id'),
'expires' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'after' => 'user_id'),
'scope' => array('type' => 'string', 'null' => true, 'default' => NULL, 'collate' => 'utf8_general_ci', 'charset' => 'utf8', 'after' => 'expires'),
'indexes' => array(
'PRIMARY' => array('column' => 'refresh_token', 'unique' => 1),
),
'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'MyISAM'),
),
),
),
'down' => array(
'drop_table' => array(
'access_tokens', 'auth_codes', 'clients', 'refresh_tokens'
),
),
);
/**
* Before migration callback
*
* @param string $direction, up or down direction of migration process
* @return boolean Should process continue
* @access public
*/
public function before($direction) {
return true;
}
/**
* After migration callback
*
* @param string $direction, up or down direction of migration process
* @return boolean Should process continue
* @access public
*/
public function after($direction) {
return true;
}
}
| php | MIT | 88d1daa9a35892c8b73ef1ddc5fb67ac9ec70324 | 2026-01-05T04:40:52.970980Z | false |
awcodes/filament-badgeable-column | https://github.com/awcodes/filament-badgeable-column/blob/993c1ac7667ad4fffefba0e0e087598264d53b92/rector.php | rector.php | <?php
declare(strict_types=1);
use Rector\Config\RectorConfig;
return RectorConfig::configure()
->withPaths([
__DIR__.'/src',
])
->withPreparedSets(
deadCode: true,
codeQuality: true,
typeDeclarations: true,
privatization: true,
earlyReturn: true,
strictBooleans: true,
)
->withPhpSets();
| php | MIT | 993c1ac7667ad4fffefba0e0e087598264d53b92 | 2026-01-05T04:41:05.841685Z | false |
awcodes/filament-badgeable-column | https://github.com/awcodes/filament-badgeable-column/blob/993c1ac7667ad4fffefba0e0e087598264d53b92/src/BadgeableColumnServiceProvider.php | src/BadgeableColumnServiceProvider.php | <?php
declare(strict_types=1);
namespace Awcodes\BadgeableColumn;
use Spatie\LaravelPackageTools\Package;
use Spatie\LaravelPackageTools\PackageServiceProvider;
class BadgeableColumnServiceProvider extends PackageServiceProvider
{
public function configurePackage(Package $package): void
{
$package->name('badgeable-column')
->hasAssets()
->hasViews();
}
}
| php | MIT | 993c1ac7667ad4fffefba0e0e087598264d53b92 | 2026-01-05T04:41:05.841685Z | false |
awcodes/filament-badgeable-column | https://github.com/awcodes/filament-badgeable-column/blob/993c1ac7667ad4fffefba0e0e087598264d53b92/src/Components/BadgeableColumn.php | src/Components/BadgeableColumn.php | <?php
declare(strict_types=1);
namespace Awcodes\BadgeableColumn\Components;
use Awcodes\BadgeableColumn\Concerns\HasBadges;
use Filament\Tables\Columns\TextColumn;
class BadgeableColumn extends TextColumn
{
use HasBadges;
}
| php | MIT | 993c1ac7667ad4fffefba0e0e087598264d53b92 | 2026-01-05T04:41:05.841685Z | false |
awcodes/filament-badgeable-column | https://github.com/awcodes/filament-badgeable-column/blob/993c1ac7667ad4fffefba0e0e087598264d53b92/src/Components/Badge.php | src/Components/Badge.php | <?php
declare(strict_types=1);
namespace Awcodes\BadgeableColumn\Components;
use Closure;
use Filament\Infolists\Components\Entry;
use Filament\Support\Components\ViewComponent;
use Filament\Support\Concerns\HasColor;
use Filament\Support\Concerns\HasFontFamily;
use Filament\Support\Concerns\HasWeight;
use Filament\Support\Enums\Size;
use Filament\Tables\Columns\Column;
use Filament\Tables\Columns\Concerns\CanBeHidden;
use Filament\Tables\Columns\Concerns\HasLabel;
use Filament\Tables\Columns\Concerns\HasName;
use Filament\Tables\Columns\Concerns\HasRecord;
use Illuminate\Database\Eloquent\Model;
class Badge extends ViewComponent
{
use CanBeHidden;
use HasColor;
use HasFontFamily;
use HasLabel;
use HasName;
use HasRecord;
use HasWeight;
protected string $view = 'badgeable-column::components.badge';
protected Column|Entry $column;
protected bool|Closure|null $shouldBePill = true;
protected Size|string|Closure|null $size = null;
final public function __construct(string $name)
{
$this->name($name);
}
public static function make(string $name): static
{
$static = app(static::class, ['name' => $name]);
$static->configure();
return $static;
}
public function isPill(bool|Closure|null $condition): static
{
$this->shouldBePill = $condition;
return $this;
}
public function size(Size|string|Closure|null $size): static
{
$this->size = $size;
return $this;
}
public function column(Column|Entry $column): static
{
$this->column = $column;
return $this;
}
public function getSize(): Size|string|null
{
$size = $this->evaluate($this->size);
if (! is_string($size)) {
return $size;
}
return Size::tryFrom($size) ?? $size;
}
public function getRecord(): ?Model
{
return $this->column->getRecord();
}
public function shouldBePill(): bool
{
return (bool) $this->evaluate($this->shouldBePill);
}
protected function resolveDefaultClosureDependencyForEvaluationByName(string $parameterName): array
{
return match ($parameterName) {
'record' => [$this->getRecord()],
'state' => [$this->getLabel()],
default => parent::resolveDefaultClosureDependencyForEvaluationByName($parameterName),
};
}
}
| php | MIT | 993c1ac7667ad4fffefba0e0e087598264d53b92 | 2026-01-05T04:41:05.841685Z | false |
awcodes/filament-badgeable-column | https://github.com/awcodes/filament-badgeable-column/blob/993c1ac7667ad4fffefba0e0e087598264d53b92/src/Components/BadgeableEntry.php | src/Components/BadgeableEntry.php | <?php
declare(strict_types=1);
namespace Awcodes\BadgeableColumn\Components;
use Awcodes\BadgeableColumn\Concerns\HasBadges;
use Filament\Infolists\Components\TextEntry;
class BadgeableEntry extends TextEntry
{
use HasBadges;
}
| php | MIT | 993c1ac7667ad4fffefba0e0e087598264d53b92 | 2026-01-05T04:41:05.841685Z | false |
awcodes/filament-badgeable-column | https://github.com/awcodes/filament-badgeable-column/blob/993c1ac7667ad4fffefba0e0e087598264d53b92/src/Concerns/HasBadges.php | src/Concerns/HasBadges.php | <?php
declare(strict_types=1);
namespace Awcodes\BadgeableColumn\Concerns;
use Closure;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\HtmlString;
use Illuminate\Support\Str;
trait HasBadges
{
protected array|Closure $prefixBadges = [];
protected array|Closure $suffixBadges = [];
protected bool|Closure $asPills = false;
public function asPills(bool|Closure $condition = true): static
{
$this->asPills = $condition;
return $this;
}
public function getBadges(array|Closure $badges): string
{
$badges = $this->evaluate($badges);
$badgesHtml = '';
foreach ($badges as $badge) {
$badgeHtml = $badge
->column($this)
->isPill($this->shouldBePills())
->render();
$badgesHtml .= Str::of($badgeHtml)
->replace('<!-- __BLOCK__ --> ', '')
->replace('<!-- __ENDBLOCK__ -->', '')
->replace('<!--[if BLOCK]><![endif]-->', '')
->replace('<!--[if ENDBLOCK]><![endif]-->', '')
->replace('/n', '')
->trim();
}
return $badgesHtml;
}
public function getPrefix(): string|Htmlable|null
{
$badges = $this->getPrefixBadges();
if ($badges) {
return new HtmlString('<span style="display:inline-flex;gap:0.375rem;margin-inline-end:0.25rem;">'.$badges.'</span><span style="opacity: 0.375;">'.$this->getSeparator().'</span> '.parent::getPrefix());
}
return parent::getPrefix();
}
public function getPrefixBadges(): string
{
return $this->getBadges($this->prefixBadges);
}
public function getSuffix(): string|Htmlable|null
{
$badges = $this->getSuffixBadges();
if ($badges) {
return new HtmlString(parent::getSuffix().' <span style="opacity: 0.375;">'.$this->getSeparator().'</span><span style="display:inline-flex;gap:0.375rem;margin-inline-start:0.25rem;">'.$badges.'</span>');
}
return parent::getSuffix();
}
public function getSuffixBadges(): string
{
return $this->getBadges($this->suffixBadges);
}
public function prefixBadges(array|Closure $badges): static
{
$this->prefixBadges = $badges;
return $this;
}
public function shouldBePills(): bool
{
return (bool) $this->evaluate($this->asPills);
}
public function suffixBadges(array|Closure $badges): static
{
$this->suffixBadges = $badges;
return $this;
}
public function getSeparator(): ?string
{
return $this->evaluate($this->separator) ?? '—';
}
}
| php | MIT | 993c1ac7667ad4fffefba0e0e087598264d53b92 | 2026-01-05T04:41:05.841685Z | false |
awcodes/filament-badgeable-column | https://github.com/awcodes/filament-badgeable-column/blob/993c1ac7667ad4fffefba0e0e087598264d53b92/tests/Pest.php | tests/Pest.php | <?php
declare(strict_types=1);
| php | MIT | 993c1ac7667ad4fffefba0e0e087598264d53b92 | 2026-01-05T04:41:05.841685Z | false |
awcodes/filament-badgeable-column | https://github.com/awcodes/filament-badgeable-column/blob/993c1ac7667ad4fffefba0e0e087598264d53b92/tests/src/TestCase.php | tests/src/TestCase.php | <?php
declare(strict_types=1);
namespace Awcodes\BadgeableColumn\Tests;
use Awcodes\BadgeableColumn\BadgeableColumnServiceProvider;
use Awcodes\BadgeableColumn\Tests\Providers\PostsTableServiceProvider;
use BladeUI\Heroicons\BladeHeroiconsServiceProvider;
use BladeUI\Icons\BladeIconsServiceProvider;
use Filament\Actions\ActionsServiceProvider;
use Filament\FilamentServiceProvider;
use Filament\Forms\FormsServiceProvider;
use Filament\Infolists\InfolistsServiceProvider;
use Filament\Notifications\NotificationsServiceProvider;
use Filament\Schemas\SchemasServiceProvider;
use Filament\Support\SupportServiceProvider;
use Filament\Tables\TablesServiceProvider;
use Filament\Widgets\WidgetsServiceProvider;
use Illuminate\Foundation\Testing\LazilyRefreshDatabase;
use Livewire\LivewireServiceProvider;
use Orchestra\Testbench\Concerns\WithWorkbench;
use Orchestra\Testbench\TestCase as Orchestra;
use RyanChandler\BladeCaptureDirective\BladeCaptureDirectiveServiceProvider;
abstract class TestCase extends Orchestra
{
use LazilyRefreshDatabase;
use WithWorkbench;
protected function getPackageProviders($app): array
{
$providers = [
ActionsServiceProvider::class,
BladeCaptureDirectiveServiceProvider::class,
BladeHeroiconsServiceProvider::class,
BladeIconsServiceProvider::class,
FilamentServiceProvider::class,
FormsServiceProvider::class,
InfolistsServiceProvider::class,
LivewireServiceProvider::class,
NotificationsServiceProvider::class,
SchemasServiceProvider::class,
SupportServiceProvider::class,
TablesServiceProvider::class,
WidgetsServiceProvider::class,
BadgeableColumnServiceProvider::class,
PostsTableServiceProvider::class,
];
sort($providers);
return $providers;
}
}
| php | MIT | 993c1ac7667ad4fffefba0e0e087598264d53b92 | 2026-01-05T04:41:05.841685Z | false |
awcodes/filament-badgeable-column | https://github.com/awcodes/filament-badgeable-column/blob/993c1ac7667ad4fffefba0e0e087598264d53b92/tests/src/Fixtures/Livewire/PostsTable.php | tests/src/Fixtures/Livewire/PostsTable.php | <?php
declare(strict_types=1);
namespace Awcodes\BadgeableColumn\Tests\Fixtures\Livewire;
use Awcodes\BadgeableColumn\Components\Badge;
use Awcodes\BadgeableColumn\Components\BadgeableColumn;
use Awcodes\BadgeableColumn\Tests\Fixtures\Models\Post;
use Exception;
use Filament\Actions\Concerns\InteractsWithActions;
use Filament\Actions\Contracts\HasActions;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Schemas\Concerns\InteractsWithSchemas;
use Filament\Schemas\Contracts\HasSchemas;
use Filament\Tables;
use Filament\Tables\Table;
use Livewire\Component;
class PostsTable extends Component implements HasActions, HasSchemas, Tables\Contracts\HasTable
{
use InteractsWithActions;
use InteractsWithSchemas;
use Tables\Concerns\InteractsWithTable;
/** @throws Exception */
public function table(Table $table): Table
{
return $table
->query(Post::query())
->columns([
BadgeableColumn::make('title')
->searchable()
->prefixBadges([
Badge::make('featured')
->color('primary'),
])
->suffixBadges([
Badge::make('status')
->color('primary'),
]),
Tables\Columns\TextColumn::make('content')
->words(10)
->searchable(isIndividual: true, isGlobal: false),
Tables\Columns\IconColumn::make('is_published')
->boolean(),
])
->recordActions([
EditAction::make(),
DeleteAction::make(),
]);
}
public function render(): string
{
return <<<'BLADE'
{{ $this->table }}
BLADE;
}
}
| php | MIT | 993c1ac7667ad4fffefba0e0e087598264d53b92 | 2026-01-05T04:41:05.841685Z | false |
awcodes/filament-badgeable-column | https://github.com/awcodes/filament-badgeable-column/blob/993c1ac7667ad4fffefba0e0e087598264d53b92/tests/src/Fixtures/Livewire/InfolistPage.php | tests/src/Fixtures/Livewire/InfolistPage.php | <?php
declare(strict_types=1);
namespace Awcodes\BadgeableColumn\Tests\Fixtures\Livewire;
use Awcodes\BadgeableColumn\Components\Badge;
use Awcodes\BadgeableColumn\Components\BadgeableEntry;
use Exception;
use Filament\Schemas\Concerns\InteractsWithSchemas;
use Filament\Schemas\Contracts\HasSchemas;
use Filament\Schemas\Schema;
use Livewire\Component;
class InfolistPage extends Component implements HasSchemas
{
use InteractsWithSchemas;
public $post;
public static function make(): static
{
return new static;
}
public function mount(): void
{
//
}
/** @throws Exception */
public function infolist(Schema $schema): Schema
{
return $schema
->record($this->post)
->components([
BadgeableEntry::make('title')
->prefixBadges([
Badge::make('featured')
->color('primary'),
])
->suffixBadges([
Badge::make('status')
->color('primary'),
]),
]);
}
public function render(): string
{
return <<<'BLADE'
{{ $this->infolist }}
BLADE;
}
}
| php | MIT | 993c1ac7667ad4fffefba0e0e087598264d53b92 | 2026-01-05T04:41:05.841685Z | false |
awcodes/filament-badgeable-column | https://github.com/awcodes/filament-badgeable-column/blob/993c1ac7667ad4fffefba0e0e087598264d53b92/tests/src/Fixtures/Models/Post.php | tests/src/Fixtures/Models/Post.php | <?php
declare(strict_types=1);
namespace Awcodes\BadgeableColumn\Tests\Fixtures\Models;
use Awcodes\BadgeableColumn\Tests\Database\Factories\PostFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $casts = [
'is_published' => 'boolean',
];
protected $guarded = [];
protected static function newFactory(): PostFactory
{
return PostFactory::new();
}
}
| php | MIT | 993c1ac7667ad4fffefba0e0e087598264d53b92 | 2026-01-05T04:41:05.841685Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.