<?php
require('xapian.php'); // adjust the path to Xapian php library

echo 'PHP version ', PHP_VERSION, ', Xapian version ', Xapian::version_string(), "\n\n";

// Create a dummy database
$db=Xapian::inmemory_open();
$doc = new XapianDocument();
echo 'Creating a new db containing a document with terms : ';
foreach(array('test','tester','testable','user') as $term)
{
    $doc->add_term(utf8_encode($term));
    echo $term, ', ';
}
echo "\n\n";
$db->add_document($doc);

// Stopper
$stopper=new XapianSimpleStopper();
$stopwords=explode(',', 'this,is,a');
foreach($stopwords as $stopword)
    $stopper->add($stopword);

// QueryParser
$queryParser = new XapianQueryParser();
$queryParser->set_stopper($stopper);

// Flags
$flags = XapianQueryParser::FLAG_WILDCARD;

// Pass db to the query parser    
$queryParser->set_database($db);

// Tests. One time with defaulOp=OR, one time with defaultOp=AND
foreach (array(XapianQuery::OP_OR=>'OR', XapianQuery::OP_AND=>'AND') as $defaultOp=>$name)
{
    echo '-------------- DefaultOp=', $name, "--------------\n";
    $queryParser->set_default_op($defaultOp);

    $tests = array  // 'query' => 'expected result'
    (
        // no wildcards : OK
        'this is a test' => 'Xapian::Query(test:(pos=4))',
        
        // One wildcard : OK
        'test*'=> 'Xapian::Query((test:(pos=1) OR testable:(pos=1) OR tester:(pos=1)))',
        
        // One stopword + one wildcard : OK
        'a test*' => 'Xapian::Query((test:(pos=2) OR testable:(pos=2) OR tester:(pos=2)))',
        
        // Two stopwords + one wildcard : FAILS
        'is a test*' => 'Xapian::Query((test:(pos=3) OR testable:(pos=3) OR tester:(pos=3)))',
        
        // Three stopwords + one wildcard : FAILS
        'this is a test*' => 'Xapian::Query((test:(pos=4) OR testable:(pos=4) OR tester:(pos=4)))',
        
        // Three stopwords + two wildcard : FAILS
        'this is a us* test*' => 'Xapian::Query((test:(pos=4) OR testable:(pos=4) OR tester:(pos=4)))',
        
        // Three stopwords + one wildcard + another term : OK
        'this is a user test*' => 'Xapian::Query((user:(pos=4) OR test:(pos=5) OR testable:(pos=5) OR tester:(pos=5)))',
    );

    foreach($tests as $test=>$expected)
    {
        $query = $queryParser->parse_query(utf8_encode($test), $flags);
        echo 'query: ', $test, "\n";
        $result = $query->get_description();
        echo 'result: ', $result, "\n";
        if ($result === 'Xapian::Query()') echo "FAILS.\n";
        echo "\n";
    }
}