#!/bin/bash

# Runs automated test suites for local development


# Run behat suites
function test_behat() {
  local BEHAT_BIN="${1}/behat";

  if [ -x "${BEHAT_BIN}" ]; then
    echo 'Running behat...';
    eval "${BEHAT_BIN} --stop-on-failure" || exit 1;
  fi;
}

# Run phpspec suites
function test_phpspec() {
  local PHPSPEC_BIN="${1}/phpspec";

  if [ -x "${PHPSPEC_BIN}" ]; then
    echo 'Running phpspec...';
    eval "${PHPSPEC_BIN} run --no-code-generation --quiet --stop-on-failure" || exit 1;
  fi;
}

# Analyse code against agreed rulesets
function test_phpcs() {
  local PHPCS_BIN="${1}/phpcs";
  local SRC_DIR="${2}";

  if [ -x "${PHPCS_BIN}" ]; then
    echo 'Running CodeSniffer...';
    eval "${PHPCS_BIN} --extensions=php -q ${SRC_DIR}" || exit 1;
  fi;
}

# Check code for smells and complexity
function test_phpmd() {
  local PHPMD_BIN="${1}/phpmd";
  local SRC_DIR="${2}";

  if [ -x "${PHPMD_BIN}" ]; then
    echo 'Running Mess Detector...';
    eval "${PHPMD_BIN} ${SRC_DIR} text phpmd.xml" || exit 1;
  fi;
}
# Update composer
function test_composer_update() {
  composer update \
  --prefer-dist \
  --optimize-autoloader \
  --no-suggest \
  --quiet;
}

# Run all local automated code checks
function test_all() {
  local SRC_DIR="${PWD}/src";
  local BIN_DIR="${PWD}/bin";
  clear;

  echo 'Validating composer...';
  composer validate || exit 1;

  test_composer_update;

  test_behat    "${BIN_DIR}";
  test_phpspec  "${BIN_DIR}";
  test_phpcs    "${BIN_DIR}" "${SRC_DIR}";
  test_phpmd    "${BIN_DIR}" "${SRC_DIR}";
}

test_all;
