<?php

/**
 * @file
 * Tweeper - some logic to allow tweeper to run with or without composer.
 *
 * Copyright (C) 2016-2018  Antonio Ospite <ao2@ao2.it>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

$package_name = 'ao2/tweeper';

if (file_exists(__DIR__ . '/vendor/autoload.php')) {
  /*
   * If "composer install" has been executed, use the composer autoloader.
   *
   * Using __DIR__ is OK as long as this file is on the same level of the
   * project "vendor/" directory (usually the project root directory).
   */
  require __DIR__ . '/vendor/autoload.php';
}
elseif (preg_match('/' . preg_quote('/vendor/' . $package_name, '/') . '$/', __DIR__)) {
  /*
   * If running from a "vendor/" directory of another project use the
   * autoloader of the parent project.
   *
   * This covers the case of running from a symlink in ./vendor/bin/ because
   * __DIR__ contains the *real path* of this file.
   *
   * Note that using __DIR__ here and going back two levels is OK under the
   * assumptions that this file is in the project root directory, and that the
   * package name has the structure VENDOR/PROJECT_NAME.
   */
  require __DIR__ . '/../../autoload.php';
}
else {
  /*
   * Otherwise, run without composer:
   *
   *  1. register our own autoloader function for the Tweeper class
   *
   * The implementation follows the one suggested in:
   * http://www.php-fig.org/psr/psr-4/
   */
  spl_autoload_register(function ($fully_qualified_class_name) {
    /* This matches the data defined for the PSR-4 autoloader in composer.json */
    $namespace_prefix = 'Tweeper\\';
    $base_directory = 'src/';

    $len = strlen($namespace_prefix);
    if (strncmp($namespace_prefix, $fully_qualified_class_name, $len) !== 0) {
      return;
    }

    $class_relative = substr($fully_qualified_class_name, $len);

    $file_path = $base_directory . str_replace('\\', '/', $class_relative) . '.php';

    require_once $file_path;
  });

  /*
   *  2. load the system-wide autoloader from php-symphony-serializer
   *
   * This allows to run tweeper without composer, as long as the Symphony
   * dependencies are available system-wide.
   *
   * For example, the Debian package takes care of that.
   */
  require_once 'Symfony/Component/Serializer/autoload.php';
}