<commit_before><?php

use Behat\Behat\Context\ClosuredContextInterface,
    Behat\Behat\Context\TranslatedContextInterface,
    Behat\Behat\Context\BehatContext,
    Behat\Behat\Exception\PendingException;
use Behat\Gherkin\Node\PyStringNode,
    Behat\Gherkin\Node\TableNode;

require "bootstrap.php";
/**
 * Features context.
 */
class FeatureContext extends BehatContext
{

    private $baseUrl;
    private static $db;
    private $restObject = null;
    private $response = null;
    private $requestUrl = null;
    private $requestData;

    /**
     * Initializes context.
     * Every scenario gets its own context object.
     *
     * @param array $parameters context parameters (set them up through behat.yml)
     */
    public function __construct(array $parameters)
    {
        $this->baseUrl = rtrim(
            $parameters['web_host'].":".$parameters['web_port']."/".$parameters['web_path'],
            '/'
        );

        self::log("New Test Starting: ".date('m/d/Y h:i:s'));
        $dsn = "mysql:dbname={$parameters['db_name']};host={$parameters['db_host']};port={$parameters['db_port']}";
        self::log("DSN is: $dsn");

        self::$db = new \PDO($dsn, 'test', '');
        self::$db->setAttribute(
            \PDO::ATTR_DEFAULT_FETCH_MODE,
            \PDO::FETCH_ASSOC
        );

        $this->restObject = new stdClass();
        $this->client = new Guzzle\Service\Client();

        $this->requestData = array();
    }

    private static function log($msg)
    {
        error_log("$msg\n", 3, "/tmp/simpleRoles-bdd.log");
    }

    /**
     * @BeforeScenario
     */
    public static function setUpScenario()
    {
        self::$db->exec(
            'delete from role;'
            .'delete from users;'
            .'delete from user_roles;'
        );
    }

    private function dbRows($table)
    {
        $sql = "select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where
            TABLE_SCHEMA = 'simpleRoles' and TABLE_NAME = '$table'";

        self::log($sql);
        $stmt = self::$db->prepare($sql);
        $stmt->execute();
        $res = $stmt->fetchAll();
        $ret =array();
        foreach ($res as $r) {
            $ret[] = $r['COLUMN_NAME'];
        }
        return $ret;

    }

    /**
     * @Given /^There are no "([^"]*)" in the system$/
     */
    public function thereAreNoInTheSystem($table)
    {
        if ($table == 'roles') {
            $table = 'role';
        }

        self::$db->exec("delete from $table");
    }


    /**
     * @Given /^I have this information in my "([^"]*)" table$/
     */
    public function iHaveThisInformationInMyTable($dbTable, TableNode $tableData)
    {

        $cols = $this->dbRows($dbTable);
        foreach ($tableData->getHash() as $row) {

            $tableKeys = array_keys($row);
            if ($cols != $tableKeys) {
                throw new Exception("Test and DB Data Mismatch");
            }

            $colDef = implode(",", $cols);
            $valDef = implode(", :", $tableKeys);

            $sql = "insert into $dbTable ($colDef)
              values(:$valDef)";

            self::log($sql);

            $stmt = self::$db->prepare($sql);

            foreach ($row as $k => &$v) {
                if (strlen($v) <= 0 || $v == 'null') {
                    $row[$k] = null;
                }
            }
            if (!$stmt->execute($row)) {
                $err = $stmt->errorInfo();
                self::log("DB Insert Error!");
                self::log(print_r($err, true));
            }
        }
        //throw new PendingException();
    }

    /**
     * @When /^I issue a "([^"]*)" request to "([^"]*)"$/
     */
    public function iIssueARequestTo($verb, $page)
    {
        $this->requestUrl = $this->baseUrl.$page;
        self::log("URL: {$this->requestUrl}");

        switch (strtolower($verb)) {
            case 'get':
                $resp = $this->client
                    ->get($this->requestUrl)
                    ->send();
                break;
            case 'delete':
                try {
                    $resp = $this->client
                        ->delete($this->requestUrl)
                        ->send();
                } catch (\Guzzle\Http\Exception\BadResponseException $e) {
                    $resp = $e->getResponse();
                }
                break;
            case 'put':
                try {
                    $resp = $this->client->put($this->requestUrl)
                        ->send();
                } catch (\Guzzle\Http\Exception\BadResponseException $e) {
                    $resp = $e->getResponse();
                }
                break;
            case 'post':
                try {
                    $resp = $this->client
                        ->post($this->requestUrl, array(), json_encode($this->requestData))
                        ->send();
                } catch (\Guzzle\Http\Exception\BadResponseException $e) {
                    $resp = $e->getResponse();
                }
            break;
        }
        $this->response = $resp;
    }

    /**
     * @Given /^I want to create a new role named "([^"]*)" with description "([^"]*)"$/
     */
    public function iWantToCreateANewRoleNamedWithDescription($name, $desc)
    {
        $arr = array('name' => $name, 'description' => $desc);
        $this->requestData[] = $arr;
    }

    /**
     * Test Compliment for added in a new user
     * @Given /^I want to create a new user named "([^"]*)" with username of "([^"]*)" and a reference of "([^"]*)"$/
     */
    public function iWantToCreateANewUserNamedWithUsernameOfAndAReferenceOf($user, $username, $ref)<commit_msg>Add new End to End test for behat<commit_after><?php

use Behat\Behat\Context\ClosuredContextInterface,
    Behat\Behat\Context\TranslatedContextInterface,
    Behat\Behat\Context\BehatContext,
    Behat\Behat\Exception\PendingException;
use Behat\Gherkin\Node\PyStringNode,
    Behat\Gherkin\Node\TableNode;

require "bootstrap.php";
/**
 * Features context.
 */
class FeatureContext extends BehatContext
{

    private $baseUrl;
    private static $db;
    private $restObject = null;
    private $response = null;
    private $requestUrl = null;
    private $requestData;

    /**
     * Initializes context.
     * Every scenario gets its own context object.
     *
     * @param array $parameters context parameters (set them up through behat.yml)
     */
    public function __construct(array $parameters)
    {
        $this->baseUrl = rtrim(
            $parameters['web_host'].":".$parameters['web_port']."/".$parameters['web_path'],
            '/'
        );

        self::log("New Test Starting: ".date('m/d/Y h:i:s'));
        $dsn = "mysql:dbname={$parameters['db_name']};host={$parameters['db_host']};port={$parameters['db_port']}";
        self::log("DSN is: $dsn");

        self::$db = new \PDO($dsn, 'test', '');
        self::$db->setAttribute(
            \PDO::ATTR_DEFAULT_FETCH_MODE,
            \PDO::FETCH_ASSOC
        );

        $this->restObject = new stdClass();
        $this->client = new Guzzle\Service\Client();

        $this->requestData = array();
    }

    private static function log($msg)
    {
        error_log("$msg\n", 3, "/tmp/simpleRoles-bdd.log");
    }

    /**
     * @BeforeScenario
     */
    public static function setUpScenario()
    {
        self::$db->exec(
            'delete from role;'
            .'delete from users;'
            .'delete from user_roles;'
        );
    }

    private function dbRows($table)
    {
        $sql = "select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where
            TABLE_SCHEMA = 'simpleRoles' and TABLE_NAME = '$table'";

        self::log($sql);
        $stmt = self::$db->prepare($sql);
        $stmt->execute();
        $res = $stmt->fetchAll();
        $ret =array();
        foreach ($res as $r) {
            $ret[] = $r['COLUMN_NAME'];
        }
        return $ret;

    }

    /**
     * @Given /^There are no "([^"]*)" in the system$/
     */
    public function thereAreNoInTheSystem($table)
    {
        if ($table == 'roles') {
            $table = 'role';
        }

        self::$db->exec("delete from $table");
    }


    /**
     * @Given /^I have this information in my "([^"]*)" table$/
     */
    public function iHaveThisInformationInMyTable($dbTable, TableNode $tableData)
    {

        $cols = $this->dbRows($dbTable);
        foreach ($tableData->getHash() as $row) {

            $tableKeys = array_keys($row);
            if ($cols != $tableKeys) {
                throw new Exception("Test and DB Data Mismatch");
            }

            $colDef = implode(",", $cols);
            $valDef = implode(", :", $tableKeys);

            $sql = "insert into $dbTable ($colDef)
              values(:$valDef)";

            self::log($sql);

            $stmt = self::$db->prepare($sql);

            foreach ($row as $k => &$v) {
                if (strlen($v) <= 0 || $v == 'null') {
                    $row[$k] = null;
                }
            }
            if (!$stmt->execute($row)) {
                $err = $stmt->errorInfo();
                self::log("DB Insert Error!");
                self::log(print_r($err, true));
            }
        }
        //throw new PendingException();
    }

    /**
     * @When /^I issue a "([^"]*)" request to "([^"]*)"$/
     */
    public function iIssueARequestTo($verb, $page)
    {
        $this->requestUrl = $this->baseUrl.$page;
        self::log("URL: {$this->requestUrl}");

        switch (strtolower($verb)) {
            case 'get':
                $resp = $this->client
                    ->get($this->requestUrl)
                    ->send();
                break;
            case 'delete':
                try {
                    $resp = $this->client
                        ->delete($this->requestUrl)
                        ->send();
                } catch (\Guzzle\Http\Exception\BadResponseException $e) {
                    $resp = $e->getResponse();
                }
                break;
            case 'put':
                try {
                    $resp = $this->client->put($this->requestUrl, array(), json_encode($this->requestData))
                        ->send();
                } catch (\Guzzle\Http\Exception\BadResponseException $e) {
                    $resp = $e->getResponse();
                }
                break;
            case 'post':
                try {
                    $resp = $this->client
                        ->post($this->requestUrl, array(), json_encode($this->requestData))
                        ->send();
                } catch (\Guzzle\Http\Exception\BadResponseException $e) {
                    $resp = $e->getResponse();
                }
            break;
        }
        $this->response = $resp;
    }

    /**
     * @Given /^I want to create a new role named "([^"]*)" with description "([^"]*)"$/
     */
    public function iWantToCreateANewRoleNamedWithDescription($name, $desc)
    {
        $arr = array('name' => $name, 'description' => $desc);
        $this->requestData[] = $arr;
    }

    /**
     * @Given /^I want to create a new role named "([^"]*)" with a description of "([^"]*)"$/
     */
    public function iWantToCreateANewRoleNamedWithADescriptionOf($name, $desc)
    {
        $arr = array('name' => $name, 'description' => $desc);
        $this->requestData[] = $arr;
    }

    /**
     * @Given /^I want to add user "([^"]*)" to the role "([^"]*)"$/
     */
    public function iWantToAddUserToTheRole($user, $role)
    {
        $arr = array('user' => $user, 'role' => $role);
        $this->requestData[] = $arr;
    }

    /**
     * Test Compliment for added in a new user
     * @Given /^I want to create a new user named "([^"]*)" with username of "([^"]*)" and a reference of "([^"]*)"$/
     */
    public function iWantToCreateANewUserNamedWithUsernameOfAndAReferenceOf($user, $username, $ref)
{'fraction_non_alphanumeric': 0.16301175685816727, 'fraction_numerical': 0.00033352789126990745, 'mean_word_length': 1.715417704324202, 'pattern_counts': {'":': 2, '<': 7, '<?xml version=': 0, '>': 96, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '16285', 'n_tokens_mistral': 3649, 'n_tokens_neox': 3477, 'n_words': 732}