<?php
/**
 * @author  hakre <http://codex.wordpress.org/User:Hakre>
 * @see     http://core.trac.wordpress.org/ticket/7092
 * @license GPL v3
 * @version 0.1.2
 * 
 * @-wp-plugin Plugin Name: commentsfeedlength
 * @-wp-plugin Plugin URI: http://core.trac.wordpress.org/ticket/7092
 * @-wp-plugin Description: separate setting for limiting comments feed
 * @-wp-plugin Author: hakre
 * @-wp-plugin Version: 0.1
 * @-wp-plugin Author URI: http://codex.wordpress.org/User:Hakre
 */

commentsfeedlengthPlugin::bootstrap();

/**
 * commentsfeed length plugin class
 */
class commentsfeedlengthPlugin {	
	/**
	 * instance local store
	 * @var rssfeedlengthPlugin
	 */
	static $_instance = null;

	protected $_option = 'comments_per_rss';
	
	/**
	 * option getter - local helper
	 * 
	 * @return int option value
	 */
	private function _get_option() {		
		$value = abs(intval(get_option($this->_option)));
		return (int) $value;
	}

	/**
	 * plugin bootstrap to reduce interference with the global symbol table 
	 * @return void
	 */
	public static function bootstrap() {
		if( null == commentsfeedlengthPlugin::$_instance ) {
			commentsfeedlengthPlugin::$_instance = new commentsfeedlengthPlugin();
		} 
	}

	/**
	 * plugin constructor
	 */
	public function __construct() {
		add_action('admin_init', array($this, 'admin_init'));
		add_filter('comment_feed_limits', array($this, 'comment_feed_limits'));		
	}

	/**
	 * admin_init
	 * 
	 * @-wp-action admin_init
	 * @return void
	 */
	public function admin_init() {

		if (false === get_option($this->_option)) {			
			update_option($this->_option, get_option('posts_per_rss'));	
		}
		
		$key   = $this->_option;
		$title = __('Syndication feeds show the most recent');
		$callb = array($this, 'settings_field_input_callback');
		$args  = array(
				'label_for' => $key,
				'for_text' => __('comments')
		);

		add_settings_field($key, $title, $callb, 'reading', 'default', $args);
		register_setting('reading', $key);
	}

	/**
	 * comment_feed_limits
	 * 
	 * @-wp-action comment_feed_limits
	 * @param  string $limit LIMIT clause for SQL query
	 * @return string filtered $limit parameter
	 */
	public function comment_feed_limits($limit) {		
		return sprintf('LIMIT %d', $this->_get_option());
	}

	/**
	 * field input callback 
	 * 
	 * used by self::admin_init()
	 * 
	 * @param  array $args
	 * @return void
	 */
	public function settings_field_input_callback($args) {		
		extract($args);		
		printf(
			'<input name="%1$s" type="text" id="%1$s" value="%2$d" class="small-text" /> %3$s'
			, $label_for, $this->_get_option(), $for_text
		);
	}

} // class commentsfeedlengthPlugin
