Dave Jarvis' Repositories

git clone https://repo.autonoma.ca/repo/treetrek.git
<?php
class UrlBuilder {
  private const REPO_PREFIX = '/repo/';
  private const HEAD_REF    = '/HEAD';
  private const ACT_TREE    = 'tree';

  private $repo;
  private $action;
  private $hash;
  private $name;
  private $switcher;

  public function withRepo( $repo ) {
    $this->repo = $repo;

    return $this;
  }

  public function withAction( $action ) {
    $this->action = $action;

    return $this;
  }

  public function withHash( $hash ) {
    $this->hash = $hash;

    return $this;
  }

  public function withName( $name ) {
    $this->name = $name;

    return $this;
  }

  public function withSwitcher( $jsValue ) {
    $this->switcher = $jsValue;

    return $this;
  }

  public function build() {
    return $this->switcher
      ? "window.location.href='" . self::REPO_PREFIX . "' + " . $this->switcher
      : ($this->repo ? $this->assembleUrl() : '/');
  }

  private function assembleUrl() {
    $url = self::REPO_PREFIX . $this->repo;
    $act = !$this->action && $this->name ? self::ACT_TREE : $this->action;

    if( $act ) {
      $url .= '/' . $act . $this->resolveHashSegment( $act );
    }

    if( $this->name ) {
      $url .= '/' . ltrim( $this->name, '/' );
    }

    return $url;
  }

  private function resolveHashSegment( $act ) {
    return $this->hash
      ? '/' . $this->hash
      : (in_array( $act, ['tree', 'blob', 'raw', 'commits'] )
        ? self::HEAD_REF
        : '');
  }
}