Example #1
0
File: Solver.php Project: fieg/csp
 /**
  * @return mixed
  */
 public function solve()
 {
     $features = $this->features;
     $rootNode = $this->createNodes(new Node('root'), $features);
     $graph = new Graph(new DepthFirstStrategy());
     $graph->setRoot($rootNode);
     $constraint = $this->constraint;
     $goal = function (Node $n) use($constraint) {
         $values = array();
         $path = $n->getPath();
         array_shift($path);
         // shift the root
         foreach ($path as $node) {
             $values[] = $node->getValue();
         }
         foreach ($values as $v) {
             list($feature, $value) = $v;
             $feature->setValue($value);
         }
         if ($values) {
             $result = $constraint->evaluate();
             if ($result) {
                 return true;
             }
         }
         return false;
     };
     $solutions = $graph->searchAll($goal);
     return $solutions;
 }
Example #2
0
 /**
  * @param Graph $graph
  * @dataProvider graphProvider
  */
 public function testSearch($graph)
 {
     $goalNode = new Node("some value");
     $node2 = new Node("n2");
     $node3 = new Node("n3");
     $node4 = new Node("n4");
     $node5 = new Node("n5");
     $node6 = new Node("n6");
     $node7 = new Node("n7");
     $node8 = new Node("n8");
     $node9 = new Node("n9");
     $rootNode = new Node('root');
     $rootNode->addNode($node2, rand(1, 4))->addNode($node5, rand(1, 4))->addNode($node7, rand(1, 4))->end()->addNode($node8, rand(1, 4))->end()->addNode($node9, rand(1, 4))->end()->addNode($node7, rand(1, 4))->end()->addNode($node3, rand(1, 4))->end()->end()->addNode($node6, rand(1, 4))->end()->end()->addNode($node3, rand(1, 4))->addNode($node4, rand(1, 4))->addNode($goalNode, rand(1, 4))->end()->end()->end();
     $graph->setRoot($rootNode);
     $goal = function (Node $n) use($graph) {
         return 'some value' === $n->getValue();
     };
     $path = $graph->search($goal);
     $this->assertEquals(array($rootNode, $node3, $node4, $goalNode), $path);
 }