<?php

/**
 * Publishes Web Assets for sfBugTracker plugin
 *
 * @package    symfony
 * @subpackage task
 * @author
 * @version    SVN: $Id: sfBugTrackerPublishAssetsTask.class.php 23922 2018-08-02 20:23:38Z fabien $
 */
class sfBugTrackerPublishAssetsTask extends sfBaseTask
{
  /**
   * @see sfTask
   */
  protected function configure()
  {
    $this->namespace = 'bugtracker';
    $this->name = 'publish-assets';

    $this->briefDescription = 'Publishes web assets for sfBugTracker plugin';

    $this->addOptions(array(
      new sfCommandOption('name', null, sfCommandOption::PARAMETER_OPTIONAL, 'Publish the plugin as', null)
    ));
  }

  /**
   * @see sfTask
   */
  protected function execute($arguments = array(), $options = array())
  {
    $plugin = 'sfBugTrackerPlugin';
    $enabledPlugins = $this->configuration->getPlugins();

    if ($diff = array_diff(array($plugin), $enabledPlugins))
    {
      throw new InvalidArgumentException('Plugin(s) not found: '.join(', ', $diff));
    }

    $pluginConfiguration = $this->configuration->getPluginConfiguration($plugin);

    $this->logSection('plugin', 'Configuring plugin - '.$plugin);
    $this->installPluginAssets($plugin, $pluginConfiguration->getRootDir(), $options['name']);

  }

  /**
   * Installs web content for a plugin.
   *
   * @param string $plugin The plugin name
   * @param string $dir    The plugin directory
   */
  protected function installPluginAssets($plugin, $dir, $name)
  {
    $pluginWebDir = $dir.DIRECTORY_SEPARATOR.'web';
    $webDir = sfConfig::get('sf_web_dir');

    if (is_dir($pluginWebDir))
    {
      foreach( $this->scandir($pluginWebDir) as $path ){
        $lpath = str_replace($pluginWebDir, '', $path);
        $dpath = dirname($lpath);
        $fname = basename($lpath);
        $linkpath = $webDir.$dpath.($name?DIRECTORY_SEPARATOR.$name:'');
        $linkname = $linkpath.DIRECTORY_SEPARATOR.$fname;
        if( $name ){
          if( !file_exists($linkpath) )
            $this->getFilesystem()->relativeSymlink($pluginWebDir.$dpath, $linkpath, true);
        }else if( !file_exists($linkname) ){
          $linkdir = dirname($linkname);
          if( !file_exists($linkdir) )
            mkdir($linkdir, 0777, true);
          $this->getFilesystem()->relativeSymlink($path, $linkname, true);
        }
      }
    }
  }
  protected function scandir($dir)
  {
    $paths = array();
    foreach( scandir($dir) as $fname ){
      if( $fname[0] == '.' )
        continue;
      $next = $dir.DIRECTORY_SEPARATOR.$fname;
      if( is_link($next) )
        $next = readlink($next);
      if( is_dir($next) ){
        $paths = array_merge($paths, $this->scandir($next));
      }else if( is_file($next) ){
        $paths[] = $next;
      }
    }
    return $paths;
  }
}
