<?php namespace Aedart\Scaffold\Collections\Utility;

use Aedart\Scaffold\Containers\IoC;
use Aedart\Scaffold\Contracts\Collections\TemplateProperties;

/**
 * Properties Collection Parser Trait
 *
 * Utility that is able to parse an array into a
 * template properties collection
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Collections\Utility
 */
trait PropertiesCollectionParser
{
    /**
     * Parse the given properties list and return a collection
     *
     * @param array $properties
     *
     * @return TemplateProperties
     */
    public function parsePropertiesCollection(array $properties = [])
    {
        $ioc = IoC::getInstance();

        return $ioc->make(TemplateProperties::class, $properties);
    }
}

Add template properties collection parser utility

Method is needed across multiple tasks, which is why this trait has
been created.


<?php
 /**
 * @category  RCM
 * @author    James Jervis <jjervis@relivinc.com>
 * @copyright 2012 Reliv International
 * @license   License.txt New BSD License
 * @version   GIT: reliv
 * @link      http://ci.reliv.com/confluence
 */

namespace RcmUser\Acl\Service;

class AclDataService {

    // ROLES

    public function fetchAllRoles(){

    }

    public function createRole(){

    }

    public function readRole(){

    }

    public function updateRole(){

    }

    public function deleteRole(){

    }

    // RULES
    public function createRule(){

    }

    public function readRule(){

    }

    public function updateRule(){

    }

    public function deleteRule(){

    }
}

Update Config to be proerly namespaced

Update Config to be proerly namespaced


<?php

namespace Ivory\GoogleMapBundle\Model;

/**
 * Marker shape which describes a google map marker shape
 *
 * @see http://code.google.com/apis/maps/documentation/javascript/reference.html#MarkerShape
 * @author GeLo <geloen.eric@gmail.com>
 */
class MarkerShape extends AbstractAsset
{
    /**
     * @var string Maker shape type (circle | poly | rect)
     */
    protected $type = null;

    /**
     * @var array Marker shape coordinates
     */
    protected $coordinates = array();

    /**
     * Create a marker shape
     */
    public function __construct()
    {
        parent::__construct();

        $this->setPrefixJavascriptVariable('marker_shape_');
    }

    /**
     * Gets the marker shape type
     *
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Sets the marker shape type
     *
     * @param string $type
     */
    public function setType($type)
    {
        $this->type = $type;
    }

    /**
     * Gets the marker shape coordinates
     *
     * @return array
     */
    public function getCoordinates()
    {
        return $this->coordinates;
    }

    /**
     * Sets the marker shape coordinates
     *
     * @param array $coordinates
     */
    public function setCoordinates($coordinates)
    {
        $this->coordinates = $coordinates;
    }

    /**
     * Add a coordinate to the marker shape
     *
     * @param integer $coordinate
     */
    public function addCoordinate($coordinate)
    {
        $this->coordinates[] = $coordinate;
    }
}

?>

Add marker shape model class

Add marker shape model class


<?php
//script to edit and delete cases
session_start();
require('../auth/session_check.php');
require('../../../db.php');

$action = $_POST['action'];

if (isset($_POST['id']))
	{$id = $_POST['id'];}

switch ($action) {
	case 'delete':

	$q = $dbh->prepare("DELETE FROM cm WHERE id = ?");

	$q->bindParam(1, $id);

	$q->execute();

	$error = $q->errorInfo();

	break;

}

if ($error[1])
{
	$return = array('message' => 'Sorry, there was an error. Please try again.','error' => true);
	echo json_encode($return);
}
else
{
	switch ($action) {

		case 'delete':

			$return = array('message' => 'Case deleted.','error' => false);
			echo json_encode($return);

		break;
	}
}

Add server side code to delete case

Add server side code to delete case


<?php

namespace Oro\Bundle\CalendarBundle\Tests\Unit\Provider;

use Oro\Bundle\CalendarBundle\Entity\Repository\AttendeeRepository;
use Oro\Bundle\CalendarBundle\Provider\AttendeeEmailRecipientsProvider;
use Oro\Bundle\EmailBundle\Model\EmailRecipientsProviderArgs;
use Oro\Bundle\EmailBundle\Provider\EmailRecipientsHelper;

class AttendeeEmailRecipientsProviderTest extends \PHPUnit_Framework_TestCase
{
    /** @var AttendeeEmailRecipientsProvider */
    protected $provider;

    /** @var AttendeeRepository */
    protected $attendeeRepository;

    /** @var EmailRecipientsHelper */
    protected $emailRecipientsHelper;

    public function setUp()
    {
        $this->attendeeRepository = $this->getMockBuilder('Oro\Bundle\CalendarBundle\Entity\Repository\AttendeeRepository')
            ->disableOriginalConstructor()
            ->getMock();

        $registry = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry');
        $registry->expects($this->any())
            ->method('getRepository')
            ->with('Oro\Bundle\CalendarBundle\Entity\Attendee')
            ->will($this->returnValue($this->attendeeRepository));

        $this->emailRecipientsHelper = $this->getMockBuilder('Oro\Bundle\EmailBundle\Provider\EmailRecipientsHelper')
            ->disableOriginalConstructor()
            ->getMock();

        $this->provider = new AttendeeEmailRecipientsProvider(
            $registry,
            $this->emailRecipientsHelper
        );
    }

    public function testGetSection()
    {
        $this->assertEquals('oro.calendar.autocomplete.attendees', $this->provider->getSection());
    }

    public function testGetRecipients()
    {
        $args = new EmailRecipientsProviderArgs(null, 'query', 100);

        $this->attendeeRepository->expects($this->once())
            ->method('getEmailRecipients')
            ->with(null, 'query', 100)
            ->will($this->returnValue([]));

        $this->emailRecipientsHelper->expects($this->once())
            ->method('recipientsFromResult')
            ->with([], 'Oro\Bundle\CalendarBundle\Entity\Attendee')
            ->will($this->returnValue([]));

        $this->assertEquals([], $this->provider->getRecipients($args));
    }
}

AEIV-574: Add "Calendar event Attendees" into recipients autocompletion when sending emails


<?php

require __DIR__ . '/../../vendor/autoload.php';
require __DIR__ . '/../../vendor/dekuan/delib/src/CLib.php';
require __DIR__ . '/../../src/CConst.php';
require __DIR__ . '/../../src/CCors.php';
require __DIR__ . '/../../src/CVData.php';
require __DIR__ . '/../../src/CRequest.php';
require __DIR__ . '/../../src/CResponse.php';

use dekuan\vdata\CConst;
use dekuan\vdata\CRequest;

/**
 * Created by PhpStorm.
 * User: xing
 * Date: 02/11/2016
 * Time: 12:09 PM
 */
class TestRequestRaw extends PHPUnit_Framework_TestCase
{
	public function testRawRequest()
	{
		$cRequest	= CRequest::GetInstance();

		echo "\r\n";

		$nCall		= $cRequest->HttpRaw
		(
			[
				'method'	=> 'GET',
				'url'		=> "http://127.0.0.1:9916",
			],
			$arrResp
		);
		if ( CConst::ERROR_SUCCESS == $nCall &&
			$cRequest->IsValidRawResponse( $arrResp ) )
		{
			var_dump( $arrResp[ 'status' ], $arrResp[ 'headers' ] );
		}

	}
}

Optimize HttpRaw, respond http headers in array


<?php
/**
 * Script to delete any Northstar users in the delete queue.
 *
 * to run:
 * drush --script-path=../scripts/ php-script delete-bad-users-in-northstar.php
 */

include_once('../lib/modules/dosomething/dosomething_northstar/dosomething_northstar.module');

$records = db_query('SELECT id, uid, northstar_id FROM dosomething_northstar_delete_queue');

foreach ($records as $record) {
  $client = _dosomething_northstar_build_http_client();
  $response = drupal_http_request($client['base_url'] . '/users/' . $record->northstar_id, [
    'headers' => $client['headers'],
    'method' => 'DELETE',
  ]);

  // Output progress to stdout & log request details for later review.
  dosomething_northstar_log_request('delete', $record, [], $response);
  echo 'Deleted Northstar user ' . $record->northstar_id . ' from ' . $record->uid . ' [' . $response->code . ']' . PHP_EOL;

  // If a user cannot be migrated due to an index conflict, add that Northstar ID to the delete queue.
  if ($response->code == '200') {
    db_delete('dosomething_northstar_delete_queue')->condition('id', $record->id)->execute();
  }
}

Add script to delete users in the delete queue.


<?php

/**
 * Migration:   8
 * Started:     07/11/2019
 *
 * @package     Nails
 * @subpackage  module-admin
 * @category    Database Migration
 * @author      Nails Dev Team
 * @link
 */

namespace Nails\Database\Migration\Nails\ModuleAdmin;

use Nails\Common\Console\Migrate\Base;

class Migration8 extends Base
{
    /**
     * Execute the migration
     * @return Void
     */
    public function execute()
    {
        $this->query('
            CREATE TABLE `{{NAILS_DB_PREFIX}}admin_dashboard_widget` (
            `id` int unsigned NOT NULL AUTO_INCREMENT,
            `slug` varchar(255) NOT NULL DEFAULT \'\',
            `x` int unsigned NOT NULL,
            `y` int unsigned NOT NULL,
            `w` int unsigned NOT NULL,
            `h` int unsigned NOT NULL,
            `config` json DEFAULT NULL,
            `created` datetime NOT NULL,
            `created_by` int unsigned DEFAULT NULL,
            `modified` datetime DEFAULT NULL,
            `modified_by` int unsigned DEFAULT NULL,
            PRIMARY KEY (`id`),
            KEY `created_by` (`created_by`),
            KEY `modified_by` (`modified_by`),
            CONSTRAINT `{{NAILS_DB_PREFIX}}admin_dashboard_widget_ibfk_1` FOREIGN KEY (`created_by`) REFERENCES `{{NAILS_DB_PREFIX}}user` (`id`) ON DELETE SET NULL,
            CONSTRAINT `{{NAILS_DB_PREFIX}}admin_dashboard_widget_ibfk_2` FOREIGN KEY (`modified_by`) REFERENCES `{{NAILS_DB_PREFIX}}user` (`id`) ON DELETE SET NULL
            ) ENGINE=InnoDB AUTO_INCREMENTDEFAULT CHARSET=utf8;
        ');
    }
}

Add migration for dash widgets

Add migration for dash widgets


<?php namespace App\Commands;

use App\Commands\Command;

use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldBeQueued;

class SendEmail extends Command implements SelfHandling, ShouldBeQueued {

	use InteractsWithQueue, SerializesModels;

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		//
	}

	/**
	 * Execute the command.
	 *
	 * @return void
	 */
	public function handle()
	{
		//
	}

}

Add the laravel queues functionality to do the jobs later.


<?php
/**
 * Normalise a HXL dataset.
 *
 * Usage:
 *
 * php hxlnorm.php < INFILE.csv > OUTFILE.csv
 *
 * Started by David Megginson, 2014-09-26
 */

require_once(__DIR__ . '/../HXL/HXL.php');

/**
 * Write the header and tag rows.
 */
function write_headers(HXLRow $row) {

  // header row
  $row_out = array();
  foreach ($row as $value) {
    if ($value->column->tag) {
      array_push($row_out, $value->column->source_text);
    }
  }
  fputcsv(STDOUT, $row_out);

  // tag row
  $row_out = array();
  foreach ($row as $value) {
    if ($value->column->tag) {
      array_push($row_out, $value->column->tag);
    }
  }
  fputcsv(STDOUT, $row_out);
}

/**
 * Write a row of data.
 */
function write_data(HXLRow $row) {
  $row_out = array();
  foreach ($row as $value) {
    if ($value->column->tag) {
      array_push($row_out, $value->content);
    }
  }
  fputcsv(STDOUT, $row_out);
}

//
// Main loop
//
$hxl = new HXLReader(STDIN);
$done_headers = false;

foreach ($hxl as $row) {
  if (!$done_headers) {
    // We haven't written the header rows yet
    write_headers($row);
    $done_headers = true;
  }
  write_data($row);
}

exit(0);

// end

Add first tool: a simple normalisation script.


<?php
/*
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

require_once '../../src/apiClient.php';
session_start();

$client = new apiClient();
$client->setApplicationName('Google Contacts PHP Sample');
$client->setScopes("http://www.google.com/m8/feeds/");
// Documentation: http://code.google.com/apis/gdata/docs/2.0/basics.html
// Visit https://code.google.com/apis/console?api=contacts to generate your
// oauth2_client_id, oauth2_client_secret, and register your oauth2_redirect_uri.
// $client->setClientId('insert_your_oauth2_client_id');
// $client->setClientSecret('insert_your_oauth2_client_secret');
// $client->setRedirectUri('insert_your_redirect_uri');
// $client->setDeveloperKey('insert_your_developer_key');

if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['token'])) {
 $client->setAccessToken($_SESSION['token']);
}

if (isset($_REQUEST['logout'])) {
  unset($_SESSION['token']);
  $client->revokeToken();
}

if ($client->getAccessToken()) {
  $req = new apiHttpRequest("https://www.google.com/m8/feeds/contacts/default/full");
  $val = $client->getIo()->authenticatedRequest($req);

  // The contacts api only returns XML responses.
  $response = json_encode(simplexml_load_string($val->getResponseBody()));
  print "
" . print_r(json_decode($response, true), true) . "
";

  // The access token may have been updated lazily.
  $_SESSION['token'] = $client->getAccessToken();
} else {
  $auth = $client->createAuthUrl();
}

if (isset($auth)) {
    print "Connect Me!";
  } else {
    print "Logout";
}

Add an (unsupported) sample application for the Google Contacts API.


<?php

/**
 * Copyright 2016 SURFnet B.V.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Surfnet\StepupRa\RaBundle\Service;

use Surfnet\StepupRa\RaBundle\Assert;
use Symfony\Component\Translation\TranslatorInterface;

final class GlobalViewParameters
{
    /**
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @var string[]
     */
    private $locales;

    /**
     * @var array
     */
    private $manualUrl;

    public function __construct(TranslatorInterface $translator, array $locales, array $manualUrl)
    {
        Assert::keysAre($manualUrl, $locales);

        $this->translator = $translator;
        $this->locales = $locales;
        $this->manualUrl = $manualUrl;
    }

    /**
     * @return string
     */
    public function getManualUrl()
    {
        return $this->manualUrl[$this->translator->getLocale()];
    }
}

Introduce global view parameters service


<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateSocialPostsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('social_posts', function(Blueprint $table)
		{
			$table->increments('id');

			$table->string('type');
			$table->string('title')->nullable();
			$table->text('text');
			$table->string('social_id');
			$table->string('url');
			$table->string('image_url')->nullable();
			$table->boolean('show_on_page');
			$table->timestamp('published_at');

			$table->timestamps();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('social_posts');
	}

}

Add migration for social posts table

Add migration for social posts table


<?php
/**
 * Slim Framework (http://slimframework.com)
 *
 * @license   https://github.com/slimphp/Twig-View/blob/master/LICENSE.md (MIT License)
 */

declare(strict_types=1);

namespace Slim\Tests;

use Psr\Http\Message\UriInterface;
use ReflectionProperty;
use Slim\Interfaces\RouteParserInterface;
use Slim\Views\TwigRuntimeExtension;
use Slim\Views\TwigRuntimeLoader;

class TwigRuntimeLoaderTest extends TestCase
{
    public function testConstructor()
    {
        $routeParser = $this->createMock(RouteParserInterface::class);
        $uri = $this->createMock(UriInterface::class);
        $basePath = '';

        // Create the twig runtime loader.
        $twigRuntimeLoader = new TwigRuntimeLoader($routeParser, $uri, $basePath);

        // Make `TwigRuntimeLoader->routeParser` accessible.
        $routeParserProperty = new ReflectionProperty(TwigRuntimeLoader::class, 'routeParser');
        $routeParserProperty->setAccessible(true);

        // Make `TwigRuntimeLoader->uri` accessible.
        $uriProperty = new ReflectionProperty(TwigRuntimeLoader::class, 'uri');
        $uriProperty->setAccessible(true);

        // Make `TwigRuntimeLoader->basePath` accessible.
        $basePathProperty = new ReflectionProperty(TwigRuntimeLoader::class, 'basePath');
        $basePathProperty->setAccessible(true);

        $this->assertSame($routeParser, $routeParserProperty->getValue($twigRuntimeLoader));
        $this->assertSame($uri, $uriProperty->getValue($twigRuntimeLoader));
        $this->assertSame($basePath, $basePathProperty->getValue($twigRuntimeLoader));
    }

    public function testLoad()
    {
        $routeParser = $this->createMock(RouteParserInterface::class);
        $uri = $this->createMock(UriInterface::class);
        $basePath = '';

        // Create the twig runtime loader.
        $twigRuntimeLoader = new TwigRuntimeLoader($routeParser, $uri, $basePath);

        $runtimeExtension = $twigRuntimeLoader->load(TwigRuntimeExtension::class);
        $this->assertInstanceOf(TwigRuntimeExtension::class, $runtimeExtension);
    }

    public function testLoadUnsupportedRuntimeExtension()
    {
        $routeParser = $this->createMock(RouteParserInterface::class);
        $uri = $this->createMock(UriInterface::class);
        $basePath = '';

        // Create the twig runtime loader.
        $twigRuntimeLoader = new TwigRuntimeLoader($routeParser, $uri, $basePath);

        $runtimeExtension = $twigRuntimeLoader->load('UnsupportedRuntimeExtension');
        $this->assertNull($runtimeExtension);
    }
}

Add test cases for `TwigRuntimeLoader`

Add test cases for `TwigRuntimeLoader`


<?php

require_once('tests/php/base.php');
require_once('framework/php/classes/elements/TourDates.php');

class ElementTests extends UnitTestCase {
	function testTourDates(){
		$e = new TourDates('blarg',1);
		$this->assertIsa($e, 'TourDates');
	}
}
?>

Add basic TourDates element test

Add basic TourDates element test


<?php
/**
 * Hook to add the OpenID provider to the authentication tab.
 *
 * @param array &$links  The links on the frontpage, split into sections.
 */
function openidProvider_hook_frontpage(&$links) {
	assert('is_array($links)');
	assert('array_key_exists("links", $links)');

	$links['auth'][] = array(
		'href' => SimpleSAML_Module::getModuleURL('openidProvider/user.php'),
		'text' => '{openidProvider:op:title_no_user}',
	);
}

openidProvider: Add frontpage hook with link to user page.

Fixes issue 227


<?php
use PhpBrew\Testing\CommandTestCase;

class DownloadCommandTest extends CommandTestCase
{

    public function versionDataProvider() {
        return array(
            array('5.5'),
            array('5.5.15'),
        );
    }

    /**
     * @outputBuffering enabled
     * @dataProvider versionDataProvider
     */
    public function testDownloadCommand($versionName) {
        ob_start();
        $this->assertTrue($this->runCommand("phpbrew download $versionName"));
        $this->assertTrue($this->runCommand("phpbrew download $versionName")); // redownload should just check the checksum instead of extracting it.
        $this->assertTrue($this->runCommand("phpbrew download -f $versionName"));
        ob_end_clean();
    }

}

<?php
use PhpBrew\Testing\CommandTestCase;

class DownloadCommandTest extends CommandTestCase
{

    public function versionDataProvider() {
        return array(
            array('5.5'),
            array('5.5.15'),
        );
    }

    /**
     * @outputBuffering enabled
     * @dataProvider versionDataProvider
     */
    public function testDownloadCommand($versionName) {
        ob_start();
        $this->assertTrue($this->runCommand("phpbrew -q download $versionName"));
        $this->assertTrue($this->runCommand("phpbrew -q download $versionName")); // redownload should just check the checksum instead of extracting it.
        $this->assertTrue($this->runCommand("phpbrew -q download -f $versionName"));
        ob_end_clean();
    }

}

Add --quiet option to avoid log limitation


<?php defined('SYSPATH') or die('No direct access allowed.');
/**
 * Init for Anqh
 *
 * @package    Anqh
 * @author     Antti Qvickström
 * @copyright  (c) 2010 Antti Qvickström
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 */

Route::set('404', '<file>.<ext>', array('ext' => 'ico|png|jpg|gif|txt|avi|flv|sql|js|css'))
	->defaults(array(
		'controller' => 'static',
		'action'     => '404'
	));
Route::set('sign', 'sign/<action>', array('action' => 'up|in|out'))
	->defaults(array(
		'controller' => 'sign',
		'action'     => 'up'
	));
Route::set('shouts', 'shouts(/<action>)', array('action' => 'index|shout'))
	->defaults(array(
		'controller' => 'shouts',
		'action'     => 'index'
	));
Route::set('roles', 'roles')
	->defaults(array(
		'controller' => 'roles',
		'action'     => 'index',
	));
Route::set('role', 'role(/<id>(/<action>))', array('action' => 'delete|edit'))
	->defaults(array(
		'controller' => 'roles',
		'action'     => 'edit',
	));
Route::set('tag_group_add', 'tags/addgroup')
	->defaults(array(
		'controller' => 'tags',
		'action'     => 'addgroup',
	));
Route::set('tag_group', 'tags/<id>(/<action>)', array('action' => 'group|add|deletegroup|editgroup'))
	->defaults(array(
		'controller' => 'tags',
		'action'     => 'group',
	));
Route::set('tag', 'tag/<id>(/<action>)', array('action' => 'tag|edit|delete'))
	->defaults(array(
		'controller' => 'tags',
		'action'     => 'tag',
	));
Route::set('tags', 'tags')
	->defaults(array(
		'controller' => 'tags',
		'action'     => 'index',
	));
/*
Route::set('index', '')
	->defaults(array(
		'controller' => 'index',
		'action'     => 'index',
	));
Route::set('catch_all', '(<path>)', array('path' => '.+'))
	->defaults(array(
		'controller' => 'error',
		'action' => '404'
	));
*/

Move Anqh specific routes from bootstrap


#!/usr/bin/env php
<?php
include("NudeDetector.php");

$method = 'HSV';

if ($argc == 1)
	exit;

$input_file = $argv[1];

$detector = new NudeDetector($input_file, $method);
$detector->calculate_everything();

$img = $detector->skin_map;

imagegif($img, $argv[2]);

Add an example program to view "bounding polygon"


<?php

return [

	"test_mode" => env('LB_TEST_MODE', true),
	"auth_userid" => env('LB_AUTH_USERID', ''),
	"api_key" => env('LB_API_KEY', ''),

];

Add logic boxes config file.

Add logic boxes config file.


<?php get_header(); ?>

				<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
				<article id="post-<?php the_ID(); ?>" <?php post_class( 'cf' ); ?> role="article" itemscope itemtype="http://schema.org/BlogPosting">

<?php the_title(); ?>

						<?php get_template_part('social'); ?>

Operating hours:

                                <?php echo apply_filters( 'the_content',get_option('hours_of_operation')); ?>

Address & Contact:

                                    <address>1506 E. Commercial Blvd Oakland Park, FL, 33334</address>

Give us a call at: (754)-206-4116

						<?php
							the_content();
							wp_link_pages( array(
								'before'      => '
' . __( 'Pages:', 'bonestheme' ) . '',
								'after'       => '
',
								'link_before' => '',
								'link_after'  => '',
							) );
						?>

				<?php endwhile; endif; ?>

<?php get_footer(); ?>

Set template for contact us page - Display the information from the hours of operations admin configuration


<?php

header('Location: https://docs.google.com/spreadsheets/d/1t_sxZH7jvzOluM8tILO-m4LGJ8op-Uqwp5MM4vlVgQ0/pubhtml?widget=true&headers=false');

?>

Add Redirect to Library Catalog

Add Redirect to Library Catalog


<?php
namespace yiiunit\framework\caching;
use yii\caching\ApcCache;
use yiiunit\TestCase;

/**
 * Class for testing APC cache backend
 */
class ApcCacheTest extends CacheTest
{
	private $_cacheInstance = null;

	/**
	 * @return ApcCache
	 */
	protected function getCacheInstance()
	{
		if(!extension_loaded("apc")) {
			$this->markTestSkipped("APC not installed. Skipping.");
		}

		if($this->_cacheInstance === null) {
			$this->_cacheInstance = new ApcCache();
		}
		return $this->_cacheInstance;
	}
}

<?php
namespace yiiunit\framework\caching;
use yii\caching\ApcCache;
use yiiunit\TestCase;

/**
 * Class for testing APC cache backend
 */
class ApcCacheTest extends CacheTest
{
	private $_cacheInstance = null;

	/**
	 * @return ApcCache
	 */
	protected function getCacheInstance()
	{
		if(!extension_loaded("apc")) {
			$this->markTestSkipped("APC not installed. Skipping.");
		} else if ('cli' === PHP_SAPI && !ini_get('apc.enable_cli')) {
			$this->markTestSkipped("APC cli is not enabled. Skipping.");
		}

		if($this->_cacheInstance === null) {
			$this->_cacheInstance = new ApcCache();
		}
		return $this->_cacheInstance;
	}
}

Check apc.enable_cli for ApcTestCase unit tests


<?php
require_once __DIR__ . '/../../../TestCase.php';

require_once CM_Util::getNamespacePath('CM') . 'library/CM/SmartyPlugins/function.money.php';

class smarty_function_moneyTest extends TestCase {

	/**
	 * @var Smarty_Internal_Template
	 */
	private $_template;

	public function setUp() {
		$smarty = new Smarty();
		$render = new CM_Render($this->_getSite());
		$this->_template = $smarty->createTemplate('string:');
		$this->_template->assignGlobal('render', $render);
	}

	public function testFormat() {
		$this->_assertSame("$23.33", array('amount' => 23.33333));
		$this->_assertSame("$23.00", array('amount' => 23));
	}

	public function testCurrency() {
		$this->_assertSame("CHF23.35", array('amount' => 23.33333, 'currency' => 'CHF'));
		$this->_assertSame("£23.33", array('amount' => 23.33333, 'currency' => 'GBP'));
	}

	/**
	 * @param string $expected
	 * @param array  $params
	 */
	private function _assertSame($expected, array $params) {
		$this->assertSame($expected, smarty_function_money($params, $this->_template));
	}
}

Add test for money function

Add test for money function


<?php
App::uses('Wall', 'Model');

class WallTest extends CakeTestCase {

    public $fixtures = array(
        'app.wall',
    );

    public function setUp() {
        parent::setUp();
        $this->Wall = ClassRegistry::init('Wall');
    }

    public function tearDown() {
        unset($this->Wall);

        parent::tearDown();
    }

    public function testSave_createsPost() {
        $newPost = array(
            'owner' => 2,
            'date' => '2018-01-02 03:04:05',
            'content' => 'Hi everyone!',
        );
        $expected = array('Wall' => array(
            'owner' => 2,
            'date' => '2018-01-02 03:04:05',
            'content' => 'Hi everyone!',
//            'modified' => date(),
            'lft' => 5,
            'rght' => 6,
            'id' => 3,
        ));

        $before = $this->Wall->find('count');
        $saved = $this->Wall->save($newPost);
        $after = $this->Wall->find('count');

        $this->assertEquals(1, $after - $before);
        unset($saved['Wall']['modified']);
        $this->assertEquals($expected, $saved);
    }
}

Add a first test for the Wall model

Add a first test for the Wall model


<?php
namespace OC\Migrations;

use OCP\Migration\ISimpleMigration;
use OCP\Migration\IOutput;

/**
 * Disable enterprise_key app during the upgrade to 10.5.0
 */
class Version20200610110817 implements ISimpleMigration {

	/**
	 * @param IOutput $out
	 */
	public function run(IOutput $out) {
		$appManager = \OC::$server->getAppManager();
		if ($appManager->isInstalled('enterprise_key')) {
			$appManager->disableApp('enterprise_key');
			$out->warning('The enterprise_key app is deprecated and obsolete. It has been disabled.');
		}
	}
}

Include a migration to disable the enterprise_key app if present


<?php

namespace OpsWay\ZohoBooks\Api;

use GuzzleHttp\Psr7\Stream;

class ContactPersons extends BaseApi
{
    const API_PATH = 'contacts/contactpersons';
    const GET_API_PATH = 'contacts/{:contact_id}/contactpersons';
    const API_KEY = 'contact_person';

    /**
     * {@inheritdoc}
     *
     * @param int|null $contactId This parameter is required. The null value is allowed only to avoid warning message
     *
     * @throws \InvalidArgumentException when `$contactId` is null
     */
    public function getList(array $filters = [], $contactId = null)
    {
        if (null === $contactId) {
            throw new \InvalidArgumentException(sprintf('Argument 2 passed to `%s()` must be an integer, `null` given', __METHOD__));
        }

        $response = $this->client->getList(strtr(self::GET_API_PATH, ['{:contact_id}' => $contactId]), $this->organizationId, $filters);

        return new ItemList($response[static::API_KEY.'s'], $response['page_context']);
    }

    /**
     * {@inheritdoc}
     *
     * @param int|null $contactId This parameter is required. The null value is allowed only to avoid warning message
     *
     * @throws \InvalidArgumentException when `$contactId` is null
     */
    public function get($id, array $params = [], $contactId = null)
    {
        if (null === $contactId) {
            throw new \InvalidArgumentException(sprintf('Argument 3 passed to `%s()` must be an integer, `null` given', __METHOD__));
        }

        $response = $this->client->get(strtr(self::GET_API_PATH, ['{:contact_id}' => $contactId]), $this->organizationId, $id, $params);
        if ($response instanceof Stream) {
            return $response;
        }

        return $response[static::API_KEY];
    }

    /**
     * @param int $contactPersonId
     *
     * @return bool
     */
    public function markAsPrimary($contactPersonId)
    {
        $this->client->post(static::API_PATH.'/'.$contactPersonId.'/primary', $this->organizationId);

        return true;
    }
}

Add support for contact persons endpoints

| Q             | A
| ------------- | ---
| Branch        | master
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | n/a
| License       | MIT
| Doc PR        | n/a


<?php

use yii\db\Migration;

/**
 * Handles the creation for table `profile`.
 */
class m160622_095150_create_profile extends Migration
{
    /**
     * @inheritdoc
     */
    public function up()
    {

        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }

        $this->createTable('profile', [
            'id' => $this->primaryKey(),
            'sex' => $this->string(),
        ]);
        $this->addForeignKey('FK_profile_user', 'profile', 'id', 'user', 'id');;
    }

    /**
     * @inheritdoc
     */
    public function down()
    {
        // drops foreign key for table `profile`
        $this->dropForeignKey(
            'FK_profile_user',
            'profile'
        );
        $this->dropTable('profile');
    }
}

Add migration file for creating profile table


<?php

namespace LastCall\Patterns\Twig\Tests\Renderer;

use LastCall\Patterns\Core\Pattern\PatternInterface;
use LastCall\Patterns\Core\Variable\VariableSet;
use LastCall\Patterns\Twig\Pattern\TwigPattern;
use LastCall\Patterns\Twig\Render\TwigRenderer;
use PHPUnit\Framework\TestCase;

class TwigRendererTest extends TestCase {

  private function getTwig() {
    $twig = $this->prophesize(\Twig_Environment::class);
    return $twig;
  }

  public function testDoesntSupportOtherPatterns() {
    $twig = $this->getTwig();
    $pattern = $this->prophesize(PatternInterface::class)->reveal();
    $renderer = new TwigRenderer($twig->reveal(), new VariableSet());
    $this->assertFalse($renderer->supports($pattern));
  }

  public function testSupportsTwigPatterns() {
    $twig = $this->getTwig();
    $pattern = $this->prophesize(TwigPattern::class)->reveal();
    $renderer = new TwigRenderer($twig->reveal(), new VariableSet());
    $this->assertTrue($renderer->supports($pattern));
  }

  public function testRendersTwigPattern() {
    $scripts = ['foo', 'bar'];
    $styles = ['bar', 'baz'];
    $variables = new VariableSet([]);

    $twig = $this->getTwig();
    $twig->render('foo', [])->willReturn('rendered');
    $pattern = new TwigPattern(
      'foo',
      'Foo',
      'foo',
      $variables
    );
    $renderer = new TwigRenderer($twig->reveal(), new VariableSet(), $styles, $scripts);
    $rendered = $renderer->render($pattern);
    $this->assertEquals('rendered', $rendered->getMarkup());
    $this->assertEquals($pattern, $rendered->getPattern());
    $this->assertEquals($scripts, $rendered->getScripts());
    $this->assertEquals($styles, $rendered->getStyles());
  }
}

Add test for twig rendering

Add test for twig rendering


<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class FixGameForeignKey extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		// This deletes all servers when a game is deleted
		Schema::table('servers', function($table)
		{
			$table->dropForeign('servers_game_id_foreign');
			$table->foreign('game_id')
				->references('id')
				->on('games')
				->onDelete('cascade');
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		//
		Schema::table('servers', function($table)
		{
			$table->dropForeign('servers_game_id_foreign');
			$table->foreign('game_id')
				->references('id')
				->on('games');
		});
	}

}

Fix issue: Can't delete game which has active servers.


<?php
/**
 * Simple tests for now, to verify basic functionality.
 * This should soon be PHPUnit.
 */

require_once __DIR__ . '/../vendor/autoload.php';

use Qaribou\Collection\ImmArray;
use Qaribou\Collection\CallbackHeap;

$numberSet = ImmArray::fromArray([1, 2, 3, 4, 5]);

echo '
List of items

' . $numberSet->join('
', '
') . '
', PHP_EOL;
echo 'Doubled: ' . $numberSet->map(function($num) { return $num * 2; })->join(), PHP_EOL;
echo 'Odds: ' . $numberSet->filter(function($num) { return (bool) $num % 2; })->join(), PHP_EOL;

$unsorted = ImmArray::fromArray(['f', 'c', 'a', 'b', 'e', 'd']);
$sorted = $unsorted->sort(function($a, $b) { return strcmp($a, $b); });
echo 'Sorted: ' . $sorted->join(', '), PHP_EOL;

// Big
$bigSet = ImmArray::fromArray(array_map(function($el) { return md5($el); }, range(0, 100000)));

// Time the map function
$t = microtime(true);
$mapped = $bigSet->map(function($el) { return $el * $el; });
echo 'map: ' . (microtime(true) - $t) . 's', PHP_EOL;

// Time the sort function
$t = microtime(true);
$bigSet->sort(function($a, $b) { return strcmp($a, $b); });
echo 'mergeSort: ' . (microtime(true) - $t) . 's', PHP_EOL;

// Time the sort function without a callback
$t = microtime(true);
$bigSet->sort();
echo 'arraySort: ' . (microtime(true) - $t) . 's', PHP_EOL;

// Build a heap and sort from that
class BasicHeap extends \SplHeap
{
    public function compare($a, $b)
    {
        return strcmp($a, $b);
    }
}
$t = microtime(true);
$sorted = $bigSet->sortHeap(new BasicHeap());
echo 'sortHeap: ' . (microtime(true) - $t) . 's', PHP_EOL;

Add a basic test suite

Add a basic test suite


<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateFailedJobsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('failed_jobs', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->text('connection');
            $table->text('queue');
            $table->longText('payload');
            $table->longText('exception');
            $table->timestamp('failed_at')->useCurrent();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('failed_jobs');
    }
}

Add failed jobs table migration

Add failed jobs table migration


<?php namespace BaunPlugin\Categories;

use Baun\Plugin;

class Categories extends Plugin
{
    public function init()
    {
        $this->events->addListener('baun.afterGlobals', function($event, $theme) {
            $theme->addGlobal('category_url', $this->config->get('categories.category_url'));
        });
    }
}

Add category_url to theme globals.

Add category_url to theme globals.


<?php

namespace ImguBox\Tests\Integrated\UserSettings;

use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use ImguBox\Jobs\DeleteFavorites;
use ImguBox\Log;
use ImguBox\Tests\Support\FactoryTools;
use ImguBox\Tests\TestCase;
use ImguBox\User;

class FavoritesTest extends TestCase
{
    use DatabaseMigrations, DatabaseTransactions;
    use FactoryTools;

    public function testItListsUserFavorites()
    {
        $user = $this->user();
        $logs = $this->logs($user, 10);

        $this->actingAs($user)->visit('favorites')->see($logs->first()->imgur_id);
    }

    public function testItShowsMessageIfNoFavoritesAreAvailable()
    {
        $user = $this->user();

        $this->actingAs($user)->visit('favorites')->see("We haven't synced your favorites yet or you just purged your log.");
    }

    public function testItPurgesSingleFavorite()
    {
        $user = $this->user();
        $log = $this->logs($user);

        $this->actingAs($user)
                ->visit('favorites')
                ->see("Instead")
                ->press("redownload-{$log->id}")
                ->seePageIs('/favorites')
                ->dontSee($log->imgur_id);

        $log = Log::whereId($log->id)->withTrashed()->first();

        $this->assertTrue($log->trashed());
    }

    public function testItPurgesAllFavorites()
    {
        $this->expectsJobs(DeleteFavorites::class);

        $user = $this->user();
        $this->logs($user, 10);

        $this->actingAs($user)
                ->visit('favorites')
                ->see("Instead")
                ->click("Yes, redownload everything")
                ->seePageIs('/favorites');
    }

}

Add Integration Test for Favorites

Add Integration Test for Favorites


<?php

namespace SitemapGenerator\Tests\Entity;

use SitemapGenerator\Routing\SymfonyUrlGenerator;
use SitemapGenerator\UrlGenerator;

class SymfonyUrlGeneratorTest extends \PHPUnit_Framework_TestCase
{
    public function testGenerateDelegatesToTheUrlGenerator()
    {
        $route = 'route_name';
        $routeParameters = ['foo' => 'bar'];

        $generatorMock = $this->getMock('Symfony\Component\Routing\Generator\UrlGeneratorInterface');
        $generatorMock
            ->expects($this->once())
            ->method('generate')
            ->with($route, $routeParameters)
            ->will($this->returnValue('/some/url'));

        $urlGenerator = new SymfonyUrlGenerator($generatorMock);

        $this->assertSame('/some/url', $urlGenerator->generate($route, $routeParameters));
    }
}

Add tests for the SymfonyUrlGenerator

Add tests for the SymfonyUrlGenerator


Add hello world script by php

Add hello world script by php


<?php

/**
 * Copyright (c) 2009, Brad Griffith <griffbrad@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * - Neither the name of Brad Griffith nor the names of other contributors may
 *   be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * Ensure that the SMTP server responds to HELO
 */
class Minion_Task_Smtpstatus extends Minion_Task_Abstract_Domain
{
    /**
     * Configuration defaults.  Options for this task in your configuration
     * file with override these defaults.
     *
     * @var array
     */
    protected $_defaults = array(
        'options' => array(
            'timeout' => 30,
            'port'    => 25
        )
    );

    /**
     * Check the provided domain to ensure it returns a 200-level status.
     *
     * @param string $domain The domain to check.
     *
     * @return boolean Whether HTTP status is 200-level.
     */
    public function main()
    {
        $fp = fsockopen(
            $this->getParent()->getName(),
            $this->_defaults['options']['port'],
            $errno,
            $errstr,
            $this->_defaults['options']['timeout']
        );

        if (! $fp) {
            return false;
        } else {
            fwrite($fp, 'HELO');

            $banner = fgets($fp);

            fclose($fp);

            return false !== strpos($banner, '220 ' . $this->getParent()->getName());
        }
    }
}

Add check for SMTP status.

Add check for SMTP status.


<?php

namespace PhpTabsTest\Component;

use Exception;
use PHPUnit_Framework_TestCase;
use PhpTabs\PhpTabs;

/**
 * Tests PhpTabs component
 */
class PhpTabsTest extends PHPUnit_Framework_TestCase
{
  /**
   * @expectedException PHPUnit_Framework_Error
   */
  public function testException()
  {
    # Not a valid number of params
    (new PhpTabs())->dump('param1', 'param2', 'param3');
  }
}

Add test for PhpTabs error

Add test for PhpTabs error


<?php

namespace Tests\Helpers;

use Carbon\Carbon,
    GuzzleHttp\Client,
    Mediatoolkit\Mediatoolkit,
    Mediatoolkit\Helpers\GroupHelper,
    PHPUnit\Framework\TestCase;

/**
 * A test class against the Group Helper CRUD functionalities
 */
class GroupHelperTest extends TestCase
{
    public function setUp()
    {
        $dotenv = new \Dotenv\Dotenv(__DIR__ . '/../../');
        $dotenv->load();

        $this->mediatoolkit = new Mediatoolkit(
            getenv('TESTS_MEDIATOOLKIT_ORGANISATION'),
            getenv('TESTS_MEDIATOOLKIT_TOKEN')
        );

        $this->helper = $this->mediatoolkit->getGroupHelper();
    }

    public function testHelperInstanceType()
    {
        $this->assertInstanceOf(GroupHelper::class, $this->helper);
    }

    public function testRead()
    {
        $ret = $this->helper->read();
        $this->assertTrue(is_array($ret));
    }
}

Test the Read method for an array in return


<?php

namespace Tests\Feature;

use Sijot\User;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class EventsTest extends TestCase
{
    use DatabaseMigrations, DatabaseTransactions;

    /**
     * Test the backend routes for the events section.
     *
     * @test
     * @group all
     */
    public function testIndexRoute()
    {
        $user = factory(User::class)->create();

        $this->actingAs($user)
            ->seeIsAuthenticatedAs($user)
            ->get(route('events.index'))
            ->assertStatus(200);
    }
}

Add test for index events

Add test for index events


<?php

// This example utilizes SplQueue and is therefor in memory only
// It will produce 20 jobs and then consume every job in the queue
// and when done it idles.

use Raekke\Consumer;
use Raekke\Message\DefaultMessage;
use Raekke\Producer;
use Raekke\ServiceResolver;
use Raekke\QueueFactory\InMemoryQueueFactory;

require __DIR__ . '/../vendor/autoload.php';
require 'EchoTimeService.php';

$queues = new InMemoryQueueFactory();
$producer = new Producer($queues);

for ($i = 0; $i < 20;$i++) {
    $message = new DefaultMessage('EchoTime', array(
        'time' => time(),
    ));

    $producer->produce($message);
}

$resolver = new ServiceResolver;
$resolver->register('EchoTime', new EchoTimeService());

$consumer = new Consumer($resolver);
$consumer->consume($queues->create('echo-time'));

Add example of in memory queue

Add example of in memory queue


<?php

namespace Ob\Unspread\Spreadsheet;

class Spreadsheet
{
    private $columns;
    private $rows;

    public function __construct()
    {
        $this->rows = array();
    }

    public function fromArray($array)
    {
        $this->rows = $array;
    }

    public function toArray()
    {
        return $this->rows;
    }

    /**
     * @param array $columns
     */
    public function setColumns($columns)
    {
        $this->columns = $columns;
    }

    /**
     * Inserts a new column at the given postion with an optional default value for the cells
     *
     * @param string $columnName
     * @param int    $position
     */
    public function insertColumn($columnName, $position, $defaultValue = "")
    {
        $this->columns = array_splice($this->columns, $position, 0, $columnName);

        foreach($this->rows as $key => $value)
        {
            $this->rows[$key] = array_splice($value, $position, 0, $defaultValue);
        }
    }

    /**
     * Appends a row to the spreadsheet
     *
     * @param $row
     */
    public function addRow($row)
    {

    }
}

Create a spreadsheet value object

Create a spreadsheet value object

This object will be used by readers and writers to hold a common
spreadsheet representation in-memory. It'll then be easier to mix-
match reading and writing formats.


<?php
/**
 * Changes the default login redirect URL to the previous page instead of the current page.
 *
 * @param array  $output    The output array of shortcode attributes.
 * @param array  $pairs     The supported attributes and their defaults.
 * @param array  $atts      The user defined shortcode attributes.
 * @param string $shortcode The shortcode name.
 *
 * @return array Modified default shortcode attributes.
 */
function ag_rcp_login_form_redirect_to_previous( $output, $pairs, $atts, $shortcode ) {

	$referer = wp_get_referer();

	if ( ! empty( $referer ) ) {
		$output['redirect'] = $referer;
	}

	return $output;

}
add_filter( 'shortcode_atts_login_form', 'ag_rcp_login_form_redirect_to_previous', 10, 4 );

Add snippet for changing default login redirect URL to previous page.


<?php
/**
 * Database migration class
 *
 * @author David Vandemaele <david@tigron.be>
 */

use \Skeleton\Database\Database;

class Migration_20201013_152946_Default_value extends \Skeleton\Database\Migration {

	/**
	 * Migrate up
	 *
	 * @access public
	 */
	public function up() {
		$db = Database::get();
		$db->query("
			ALTER TABLE `bank_account_statement_transaction`
			CHANGE `message` `message` varchar(255) COLLATE 'utf8_unicode_ci' NULL AFTER `amount`,
			CHANGE `structured_message` `structured_message` varchar(128) COLLATE 'utf8_unicode_ci' NULL AFTER `message`;
		", []);
		$db->query("UPDATE bank_account_statement_transaction SET message = NULL WHERE message = '';", []);
		$db->query("UPDATE bank_account_statement_transaction SET structured_message = NULL WHERE structured_message = '';", []);
	}

	/**
	 * Migrate down
	 *
	 * @access public
	 */
	public function down() {

	}
}

Fix default message in bank account statement transaction (message, structured_message)


<?php
/**
 * Created by PhpStorm.
 * User: Faramarz Salehpour
 */

use PHPUnit\Framework\TestCase;

class SampleClassTest extends TestCase
{
    /**
     * @test
     */
    public function itReturnsTrue()
    {
        $this->assertTrue(true);
    }
}

Add tests folder with a sample Test

Add tests folder with a sample Test


<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

/**
 * Unit Test for without Mimic library function.
 *
 * @since 0.1.0
 */
class WithoutFuncTest extends PHPUnit_Framework_TestCase {
	public function dataProvider() {
		$collection = array(
			'index1' => 1,
			'index2' => 2,
			'index3' => 3,
			'index4' => 4,
		);
		return array(
			array($collection, array('index2' => 2, 'index3' => 3, 'index4' => 4), array(1)),
			array($collection, array('index2' => 2, 'index4' => 4), array(1, 3)),
			array($collection, array('index1' => 1, 'index3' => 3), array(2, 4)),
		);
	}

	/**
	 * @dataProvider dataProvider
	 * @covers ::Mimic\Functional\without
	 */
	public function testResults($collection, $expected, $parameters) {
		$this->assertEquals($expected, F\without($collection));
		$this->assertEquals($expected, call_user_func_array('F\without', array_merge(array($collection), $parameters)));
	}
}

Add without function test suite.

Add without function test suite.


<?php

/**
 * Shows lint messages to the user.
 *
 * @group lint
 */
final class ArcanistLintSummaryRenderer extends ArcanistLintRenderer {
  public function renderLintResult(ArcanistLintResult $result) {
    $messages = $result->getMessages();
    $path = $result->getPath();

    $text = array();
    $text[] = $path.":";
    foreach ($messages as $message) {
      $name = $message->getName();
      $severity = ArcanistLintSeverity::getStringForSeverity(
        $message->getSeverity());
      $line = $message->getLine();

      $text[] = "    {$severity} on line {$line}: {$name}";
    }
    $text[] = null;

    return implode("\n", $text);
  }

  public function renderOkayResult() {
    return
      phutil_console_format("<bg:green>** OKAY **</bg> No lint warnings.\n");
  }
}

<?php

/**
 * Shows lint messages to the user.
 *
 * @group lint
 */
final class ArcanistLintSummaryRenderer extends ArcanistLintRenderer {
  public function renderLintResult(ArcanistLintResult $result) {
    $messages = $result->getMessages();
    $path = $result->getPath();

    $text = array();
    foreach ($messages as $message) {
      $name = $message->getName();
      $severity = ArcanistLintSeverity::getStringForSeverity(
        $message->getSeverity());
      $line = $message->getLine();

      $text[] = "{$path}:{$line}:{$severity}: {$name}\n";
    }

    return implode("", $text);
  }

  public function renderOkayResult() {
    return
      phutil_console_format("<bg:green>** OKAY **</bg> No lint warnings.\n");
  }
}

Improve `arc lint --output summary`

Improve `arc lint --output summary`

Summary:
This currently output like this:

  file_a:
  file_b:
  file_c:
    Warning on line 29: blah blah

This isn't especially useful and can't be piped to other tools. Instead, emit output like:

  file_c:29:Warning: blah blah

This is greppable / pipeable.

Test Plan: Ran `arc lint --output summary`.

Reviewers: btrahan

Reviewed By: btrahan

CC: aran

Differential Revision: https://secure.phabricator.com/D7788


<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 * @package   Zend_Stdlib
 */

namespace ZendTest\Stdlib\Strategy;

use PHPUnit_Framework_TestCase as TestCase;
use Zend\Stdlib\Hydrator\Strategy\SerializableStrategy;
use Zend\Serializer\Serializer;

class SerializableStrategyTest extends TestCase
{
    public function testCannotUseBadArgumentSerilizer()
    {
        $this->setExpectedException('Zend\Stdlib\Exception\InvalidArgumentException');
        $serializerStrategy = new SerializableStrategy(false);
    }

    public function testUseBadSerilizerObject()
    {
        $serializer = Serializer::factory('phpserialize');
        $serializerStrategy = new SerializableStrategy($serializer);
        $this->assertEquals($serializer, $serializerStrategy->getSerializer());
    }

    public function testUseBadSerilizerString()
    {
        $serializerStrategy = new SerializableStrategy('phpserialize');
        $this->assertEquals('Zend\Serializer\Adapter\PhpSerialize', get_class($serializerStrategy->getSerializer()));
    }

    public function testCanSerialize()
    {
        $serializer = Serializer::factory('phpserialize');
        $serializerStrategy = new SerializableStrategy($serializer);
        $serialized = $serializerStrategy->extract('foo');
        $this->assertEquals($serialized, 's:3:"foo";');
    }

    public function testCanUnserialize()
    {
        $serializer = Serializer::factory('phpserialize');
        $serializerStrategy = new SerializableStrategy($serializer);
        $serialized = $serializerStrategy->hydrate('s:3:"foo";');
        $this->assertEquals($serialized, 'foo');
    }
}

Add unit tests for serializable strategy

Add unit tests for serializable strategy


<?php

namespace Ms\OauthBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class RegistrationController extends Controller {

    public function clientAction($name) {
        return $this->render(
            'MsOathBundle:Registration:client.html.twig'
        );
    }

}

?>

Create the Client Registration controller.

Signed-off-by: Marios Sotiropoulos <d835cc3d5a582fb720c036e3ecd99881c51ab932@uom.gr>


<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class IncreaseTokenFieldLength extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('access_token', 2048)->change();
            $table->string('refresh_token', 2048)->change();
        });

        Schema::table('clients', function (Blueprint $table) {
            $table->string('access_token', 2048)->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('access_token', 1024)->change();
            $table->string('refresh_token', 1024)->change();
        });

        Schema::table('clients', function (Blueprint $table) {
            $table->string('access_token', 1024)->change();
        });
    }
}

Increase access token column length.

Increase access token column length.


<?php

defined("_VALID_ACCESS") || die('Direct access forbidden');

DB::Execute('UPDATE phonecall_field SET type=%s WHERE field=%s AND type=%s', array('text', 'Customer', 'select'));

Add patch to fix customer field type in phonecalls


<?php

    include_once(QFRAMEWORK_CLASS_PATH . "qframework/class/data/qregexprule.class.php");

    define(IP_CIDR_FORMAT_RULE_REG_EXP, "^([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})/([0-9]{1,2})$");
    define(ERROR_RULE_IP_CIDR_FORMAT_WRONG, "error_rule_ip_cidr_format_wrong");

    /**
     * This is an implementation of the 'Strategy' pattern as it can be seen
     * http://www.phppatterns.com/index.php/article/articleview/13/1/1/. Here we use
     * this pattern to validate data received from forms. Its is useful since for example
     * we check in many places if a 'postId' is valid or not. We can put the
     * checkings inside the class and simply reuse this class wherever we want. If we ever
     *`change the format of the postId parameter, we only have to change the code of the
     * class that validates it and it will be automatically used everywhere.
     */
    class qIpCidrFormatRule extends qRegExpRule
    {
        /**
         * The constructor does nothing.
         */
        function qIpCidrFormatRule()
        {
            $this->qRegExpRule(IP_CIDR_FORMAT_RULE_REG_EXP, false);
        }

        /**
         * Validates the data. Does nothing here and it must be reimplemented by
         * every child class.
         */
        function validate($value)
        {
            if (!ereg($this->_regExp, $value, $regs))
            {
                $this->_setError(ERROR_RULE_IP_CIDR_FORMAT_WRONG);
                return false;
            }
            else if ($regs[1] > 255 || $regs[2] > 255 || $regs[3] > 255 || $regs[4] > 255 || $regs[5] > 32)
            {
                $this->_setError(ERROR_RULE_IP_CIDR_FORMAT_WRONG);
                return false;
            }
            else
            {
                $this->_setError(false);
                return true;
            }
        }
    }
?>

Add qIpCidrFormatRule for validate a value with CIDR format (192.168.0.1/24 for example)


<?php

/**
 * Main class to filter requirements.
 */
class Whip_RequirementsFilter {

	/**
	 * @var int
	 */
	private $expirationDate;

	/**
	 * @var array
	 */
	private $requirementsToFilter;

	/**
	 * Whip_RequirementsChecker constructor.=
	 *
	 * @param integer $expirationDate       The expiration date.
	 * @param array   $requirementsToFilter The requirements to filter.
	 */
	public function __construct( $expirationDate, array $requirementsToFilter = array() ) {
		$this->expirationDate       = $expirationDate;
		$this->requirementsToFilter = $requirementsToFilter;
	}

	/**
	 * Filters the requirements.
	 * @param array $requirements The requirements.
	 *
	 * @return array The filtered requirements.
	 */
	public function filter( $requirements ) {
		return array_filter( $requirements, array( $this, 'filterRequirement' ), ARRAY_FILTER_USE_BOTH );
	}

	/**
	 * Filters the requirement based on the requirements to filter.
	 *
	 * @param string $versionComparison The version comparison.
	 * @param string $component         The component name.
	 *
	 * @return bool
	 */
	public function filterRequirement( $versionComparison, $component ) {
		if ( ! isset( $this->requirementsToFilter[ $component ] ) ) {
			return true;
		}

		if ( ! isset( $this->requirementsToFilter[ $component ][ $versionComparison ] ) ) {
			return true;
		}

		return $this->requirementsToFilter[ $component ][ $versionComparison ] > $this->expirationDate;
	}

}

Add class for filtering requirements.

Add class for filtering requirements.


<?php

if ($GLOBALS['Session']->hasAccountLevel('Staff')) {
    Slate\UI\Tools::$tools['Student Progress'] = [
        'Narrative Reports' => [
            '_href' => '/manage#progress/narratives',
            '_icon' => 'documents'
        ]
    ];
}

Add narrative reports link to default tools


<?php

$data = <<<EOD
<feed xmlns="http://www.w3.org/2005/Atom">
	<entry>
		<title type="xhtml" xml:base="http://example.com/">

Link

</title>
	</entry>
</feed>
EOD;

$expected = '
Link
';

?>

Add overly complex xml:base test

Add overly complex xml:base test


<?php

use yii\db\Schema;
use yii\db\Migration;

class m141216_145733_create_faculty_table extends Migration
{
    public function up()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }

        $this->createTable('{{%faculty}}', [
            'id' => Schema::TYPE_PK,
            'name' => Schema::TYPE_STRING . ' NOT NULL',
        ], $tableOptions);

        $this->createIndex('NAME', '{{%faculty}}', 'name', true);

    }

    public function down()
    {
        $this->dropTable('{{%faculty}}');
    }
}

Add migration for Faculty entity

Add migration for Faculty entity


<?php namespace Larapress\Tests\Services;

use Larapress\Tests\TestCase;
use Log;
use Mail;
use Narrator;

class NarratorTest extends TestCase
{

    protected $log_message;

    /*
    |--------------------------------------------------------------------------
    | Helpers::sendMail() Tests
    |--------------------------------------------------------------------------
    |
    | Here is where you can test the Helpers::sendMail() method
    |
    */

    /**
     * @expectedException \Larapress\Exceptions\MailException
     * @expectedExceptionMessage foo
     */
    public function test_can_throw_a_mail_exception_with_error_message()
    {
        $to = array('address' => 'example@domain.com', 'name' => null);
        $subject = 'Test';
        $data = array();
        $view = array();
        $mail_error_message = 'foo';

        Mail::shouldReceive('send')->once()->andReturn(false);

        Narrator::sendMail($to, $subject, $data, $view, $mail_error_message);
    }

    /**
     * @expectedException \Larapress\Exceptions\MailException
     * @expectedExceptionMessage Cannot send message without a sender address
     */
    public function test_can_throw_a_mail_exception_warning_about_missing_sender_address()
    {
        $to = array('address' => 'example@domain.com', 'name' => null);
        $subject = 'Test';
        $data = array();
        $view = array();
        $mail_error_message = 'foo';

        Mail::shouldReceive('send')->once()->andThrow(
            'Swift_TransportException',
            'Cannot send message without a sender address'
        );

        Narrator::sendMail($to, $subject, $data, $view, $mail_error_message);
    }

    /**
     * @expectedException \Larapress\Exceptions\MailException
     * @expectedExceptionMessage foo
     */
    public function test_can_fall_back_to_the_provided_error_message_on_unknown_swift_transport_exception_messages()
    {
        $to = array('address' => 'example@domain.com', 'name' => null);
        $subject = 'Test';
        $data = array();
        $view = array();
        $mail_error_message = 'foo';

        Mail::shouldReceive('send')->once()->andThrow(
            'Swift_TransportException',
            'bar'
        );

        Narrator::sendMail($to, $subject, $data, $view, $mail_error_message);
    }

    public function test_can_send_an_email()
    {
        $to = array('address' => 'example@domain.com', 'name' => null);
        $subject = 'Test';
        $data = array();
        $view = array();
        $mail_error_message = '';

        Log::listen(function($level, $message, $context)
        {
            $this->log_message = $message;
        });

        Narrator::sendMail($to, $subject, $data, $view, $mail_error_message);
        $this->assertEquals('Pretending to mail message to: example@domain.com', $this->log_message);
    }

}

Add partial tests for narrator service

Add partial tests for narrator service


<?php

namespace CommerceGuys\Platform\Cli\Tests;

use CommerceGuys\Platform\Cli\Helper\ShellHelper;

class ShellHelperTest extends \PHPUnit_Framework_TestCase
{

    /** @var ShellHelper */
    protected $shellHelper;

    public function setUp()
    {
        $this->shellHelper = new ShellHelper();
    }

    /**
     * Test ShellHelper::execute();
     */
    public function testExecute()
    {
        $this->assertNotEmpty($this->shellHelper->execute('which git'));
        $this->assertEmpty($this->shellHelper->execute('which nonexistent'));
        $this->assertEmpty($this->shellHelper->execute('nonexistent command test'));
    }

    /**
     * Test ShellHelper::executeArgs().
     */
    public function testExecuteArgs()
    {
        $this->assertNotEmpty($this->shellHelper->executeArgs(array('which', 'git')), false);
        $this->assertEmpty($this->shellHelper->executeArgs(array('which', 'nonexistent'), false));

        $this->assertNotEmpty($this->shellHelper->executeArgs(array('which', 'git')), true);
        $this->setExpectedException('Symfony\\Component\\Process\\Exception\\ProcessFailedException');
        $this->shellHelper->executeArgs(array('which', 'nonexistent'), true);
    }

}

<?php

namespace CommerceGuys\Platform\Cli\Tests;

use CommerceGuys\Platform\Cli\Helper\ShellHelper;

class ShellHelperTest extends \PHPUnit_Framework_TestCase
{

    /** @var ShellHelper */
    protected $shellHelper;

    public function setUp()
    {
        $this->shellHelper = new ShellHelper();
    }

    /**
     * Test ShellHelper::execute();
     */
    public function testExecute()
    {
        $this->assertNotEmpty($this->shellHelper->execute('help'));
        $this->assertEmpty($this->shellHelper->execute('which nonexistent'));
        $this->assertEmpty($this->shellHelper->execute('nonexistent command test'));
    }

    /**
     * Test ShellHelper::executeArgs().
     */
    public function testExecuteArgs()
    {
        $this->assertNotEmpty($this->shellHelper->executeArgs(array('help')), false);
        $this->assertEmpty($this->shellHelper->executeArgs(array('which', 'nonexistent'), false));

        $this->assertNotEmpty($this->shellHelper->executeArgs(array('help')), true);
        $this->setExpectedException('Symfony\\Component\\Process\\Exception\\ProcessFailedException');
        $this->shellHelper->executeArgs(array('which', 'nonexistent'), true);
    }

}

Test shell with a command that will work on Windows too.


<?php

declare(strict_types=1);

/**
 * This file is part of phpDocumentor.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @link      http://phpdoc.org
 */

namespace phpDocumentor\Reflection\Types;

use phpDocumentor\Reflection\Types\Boolean;
use PHPUnit\Framework\TestCase;

/**
 * @coversDefaultClass \phpDocumentor\Reflection\Types\Boolean
 */
final class BooleanTest extends TestCase
{
    /**
     * @covers ::__toString
     */
    public function testBooleanStringifyCorrectly() : void
    {
        $type = new Boolean();

        $this->assertSame('bool', (string) $type);
    }
}

Add test for Boolean type too

Add test for Boolean type too


<?php

namespace Tooly\Tests\Script\Decision;

use Tooly\Model\Tool;
use Tooly\Script\Configuration;
use Tooly\Script\Decision\OnlyDevDecision;
use Tooly\Script\Helper;

/**
 * @package Tooly\Tests\Script\Decision
 */
class OnlyDevDecisionTest extends \PHPUnit_Framework_TestCase
{
    private $helper;

    private $configuration;

    public function setUp()
    {
        $this->helper = $this
            ->getMockBuilder(Helper::class)
            ->disableOriginalConstructor()
            ->getMock();

        $this->configuration = $this
            ->getMockBuilder(Configuration::class)
            ->disableOriginalConstructor()
            ->getMock();
    }

    public function testOnlyDevToolInNonDevModeReturnsFalse()
    {
        $helper = clone $this->helper;
        $configuration = clone $this->configuration;

        $configuration
            ->expects($this->once())
            ->method('isDevMode')
            ->willReturn(false);

        $tool = $this
            ->getMockBuilder(Tool::class)
            ->disableOriginalConstructor()
            ->getMock();

        $tool
            ->expects($this->once())
            ->method('isOnlyDev')
            ->willReturn(true);

        $decision = new OnlyDevDecision($configuration, $helper);
        $this->assertFalse($decision->canProceed($tool));
    }

    public function testNonOnlyDevToolInNonDevModeReturnsTrue()
    {
        $helper = clone $this->helper;
        $configuration = clone $this->configuration;

        $configuration
            ->expects($this->once())
            ->method('isDevMode')
            ->willReturn(false);

        $tool = $this
            ->getMockBuilder(Tool::class)
            ->disableOriginalConstructor()
            ->getMock();

        $tool
            ->expects($this->once())
            ->method('isOnlyDev')
            ->willReturn(false);

        $decision = new OnlyDevDecision($configuration, $helper);
        $this->assertTrue($decision->canProceed($tool));
    }

    public function testNonOnlyDevToolInDevModeReturnsTrue()
    {
        $helper = clone $this->helper;
        $configuration = clone $this->configuration;

        $configuration
            ->expects($this->once())
            ->method('isDevMode')
            ->willReturn(true);

        $tool = $this
            ->getMockBuilder(Tool::class)
            ->disableOriginalConstructor()
            ->getMock();

        $tool
            ->expects($this->never())
            ->method('isOnlyDev');

        $decision = new OnlyDevDecision($configuration, $helper);
        $this->assertTrue($decision->canProceed($tool));
    }
}

Add tests for only-dev decision

Add tests for only-dev decision


<?php

namespace Doctrine\Tests\EventListener;

use Doctrine\Common\Persistence\Event\LoadClassMetadataEventArgs;
use Doctrine\ORM\Mapping\ClassMetadata;

class CacheMetadataListener
{
    /**
     * @param \Doctrine\Common\Persistence\Event\LoadClassMetadataEventArgs $event
     */
    public function loadClassMetadata(LoadClassMetadataEventArgs $event)
    {
        $metadata = $event->getClassMetadata();
        $cache    = array(
            'usage' => ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE
        );

        /** @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */
        if (strstr($metadata->name, 'Doctrine\Tests\Models\Cache')) {
            return;
        }

        if ($metadata->isVersioned) {
            return;
        }

        $metadata->enableCache($cache);

        foreach ($metadata->associationMappings as $mapping) {
            $metadata->enableAssociationCache($mapping['fieldName'], $cache);
        }
    }
}

<?php

namespace Doctrine\Tests\EventListener;

use Doctrine\Common\Persistence\Event\LoadClassMetadataEventArgs;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\ClassMetadata;

class CacheMetadataListener
{

    /**
     * Tracks which entities we have already forced caching enabled on. This is
     * important to avoid some potential infinite-recursion issues.
     * @var array
     */
    protected $enabledItems = array();

    /**
     * @param \Doctrine\Common\Persistence\Event\LoadClassMetadataEventArgs $event
     */
    public function loadClassMetadata(LoadClassMetadataEventArgs $event)
    {
        $metadata = $event->getClassMetadata();
        $em = $event->getObjectManager();

        /** @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */
        if (strstr($metadata->name, 'Doctrine\Tests\Models\Cache')) {
            return;
        }

        if( ! $em instanceof EntityManager){
            return;
        }

        $this->enableCaching($metadata, $em);
    }

    /**
     * @param ClassMetadata $metadata
     * @param EntityManager $em
     */
    protected function enableCaching(ClassMetadata $metadata, EntityManager $em){

        if(array_key_exists($metadata->getName(), $this->enabledItems)){
            return; // Already handled in the past
        }

        $cache    = array(
            'usage' => ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE
        );

        if ($metadata->isVersioned) {
            return;
        }

        $metadata->enableCache($cache);

        $this->enabledItems[$metadata->getName()] = $metadata;

        /*
         * Only enable association-caching when the target has already been
         * given caching settings
         */
        foreach ($metadata->associationMappings as $mapping) {

            $targetMeta = $em->getClassMetadata($mapping['targetEntity']);
            $this->enableCaching($targetMeta, $em);

            if(array_key_exists($targetMeta->getName(), $this->enabledItems)){
                $metadata->enableAssociationCache($mapping['fieldName'], $cache);
            }
        }
    }
}

Change the test listener than layers on second-level-caching so that it is more conservative, only turning on caching-associations when it knows the target entity is cache-able.


<?php

/*
 * This file is part of the Monolog package.
 *
 * (c) Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Monolog\Handler\Slack;

use Monolog\Logger;
use Monolog\TestCase;

/**
 * @coversDefaultClass Monolog\Handler\Slack\SlackRecord
 */
class SlackRecordTest extends TestCase
{
    public function dataGetAttachmentColor()
    {
        return array(
            array(Logger::DEBUG, SlackRecord::COLOR_DEFAULT),
            array(Logger::INFO, SlackRecord::COLOR_GOOD),
            array(Logger::NOTICE, SlackRecord::COLOR_GOOD),
            array(Logger::WARNING, SlackRecord::COLOR_WARNING),
            array(Logger::ERROR, SlackRecord::COLOR_DANGER),
            array(Logger::CRITICAL, SlackRecord::COLOR_DANGER),
            array(Logger::ALERT, SlackRecord::COLOR_DANGER),
            array(Logger::EMERGENCY, SlackRecord::COLOR_DANGER),
        );
    }
    /**
     * @dataProvider dataGetAttachmentColor
     * @param  int $logLevel
     * @param  string $expectedColour RGB hex color or name of Slack color
     * @covers ::getAttachmentColor
     */
    public function testGetAttachmentColor($logLevel, $expectedColour)
    {
        $slackRecord = new SlackRecord('#test');
        $this->assertSame(
            $expectedColour,
            $slackRecord->getAttachmentColor($logLevel)
        );
    }

    public function testStringifyReturnsNullWithNoLineFormatter()
    {
        $slackRecord = new SlackRecord('#test');
        $this->assertNull($slackRecord->stringify(array('foo' => 'bar')));
    }

    /**
     * @return array
     */
    public function dataStringify()
    {
        return array(
            array(array(), ''),
            array(array('foo' => 'bar'), 'foo: bar'),
            array(array('Foo' => 'bAr'), 'Foo: bAr'),
        );
    }

    /**
     * @dataProvider dataStringify
     */
    public function testStringifyWithLineFormatter($fields, $expectedResult)
    {
        $slackRecord = new SlackRecord(
            '#test',
            'test',
            true,
            null,
            true,
            true
        );

        $this->assertSame($expectedResult, $slackRecord->stringify($fields));
    }
}

Add initial tests for SlackRecord

Add initial tests for SlackRecord


<?php

namespace Tests\Regis\Infrastructure\PhpMd;

use Regis\Infrastructure\Phpstan\Phpstan;

class PhpstanTest extends \PHPUnit_Framework_TestCase
{
    private $filename;

    public function setUp()
    {
        $source = <<<CODE
<?php

\$foo = 42;
\$f = function () use (\$foo) {
};
CODE
        ;

        $this->filename = tempnam(sys_get_temp_dir(), 'regis_');
        file_put_contents($this->filename, $source);
    }

    public function tearDown()
    {
        unlink($this->filename);
    }

    public function testReportsAreGenerated()
    {
        $phpstan = new Phpstan(APP_ROOT_DIR.'/vendor/bin/phpstan');

        $this->assertSame([
            [
                'file' => $this->filename,
                'line' => 4,
                'column' => 1,
                'severity' => 'error',
                'message' => 'Anonymous function has an unused use $foo.',
            ],
        ], iterator_to_array($phpstan->execute($this->filename)));
    }
}

Add tests for the phpstan runner

Add tests for the phpstan runner


<?php

namespace Sleeti\Logging;

class Logger {
	protected $container;

	protected $handler;

	protected $loggers;

	public function __construct($container) {
		$this->container = $container;

		$logfile       = $this->container['settings']['logging']['path'] . 'sleeti.log';
		$this->handler = new \Monolog\Handler\RotatingFileHandler($logfile, $container['settings']['logging']['maxFiles'] ?? 0);

		$dateFormat   = 'H:i:s';
		$outputFormat = "[%datetime%] [%level_name%] %channel%: %message% %context%\n";
		$formatter    = new \Monolog\Formatter\LineFormatter($outputFormat, $dateFormat);

		$this->handler->setFormatter($formatter);
	}

	private function addLogger($name) {
		$logger = new \Monolog\Logger($name);
		$logger->pushHandler($this->handler, $this->container['settings']['logging']['level'] ?? \Monolog\Logger::INFO);
		$this->loggers[$name] = $logger;
	}

	public function log($name, $level, $message, array $context = []) {
		if (!$this->container['settings']['logging']['enabled']) return;

		if (!isset($loggers[$name])) {
			$this->addLogger($name);
		}

		$this->loggers[$name]->log($level, $message, $context);
	}
}

<?php

namespace Sleeti\Logging;

class Logger {
	protected $container;

	protected $handler;

	protected $loggers;

	public function __construct($container) {
		$this->container = $container;

		if (!is_dir($this->container['settings']['logging']['path']) && $this->container['settings']['logging']['enabled']) {
			mkdir($this->container['settings']['logging']['path']);
		}

		$logfile       = $this->container['settings']['logging']['path'] . 'sleeti.log';
		$this->handler = new \Monolog\Handler\RotatingFileHandler($logfile, $container['settings']['logging']['maxFiles'] ?? 0);

		$dateFormat   = 'H:i:s';
		$outputFormat = "[%datetime%] [%level_name%] %channel%: %message% %context%\n";
		$formatter    = new \Monolog\Formatter\LineFormatter($outputFormat, $dateFormat);

		$this->handler->setFormatter($formatter);
	}

	private function addLogger($name) {
		$logger = new \Monolog\Logger($name);
		$logger->pushHandler($this->handler, $this->container['settings']['logging']['level'] ?? \Monolog\Logger::INFO);
		$this->loggers[$name] = $logger;
	}

	public function log($name, $level, $message, array $context = []) {
		if (!$this->container['settings']['logging']['enabled']) return;

		if (!isset($loggers[$name])) {
			$this->addLogger($name);
		}

		$this->loggers[$name]->log($level, $message, $context);
	}
}

Create log dir if it doesn't exist

Create log dir if it doesn't exist


<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Messenger;

use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Messenger\MiddlewareInterface;

/**
 * Wraps all handlers in a single doctrine transaction.
 *
 * @author Tobias Nyholm <tobias.nyholm@gmail.com>
 */
class DoctrineTransactionMiddleware implements MiddlewareInterface
{
    private $managerRegistry;
    private $entityManagerName;

    public function __construct(ManagerRegistry $managerRegistry, ?string $entityManagerName)
    {
        $this->managerRegistry = $managerRegistry;
        $this->entityManagerName = $entityManagerName;
    }

    public function handle($message, callable $next)
    {
        $entityManager = $this->managerRegistry->getManager($this->entityManagerName);

        if (!$entityManager instanceof EntityManagerInterface) {
            throw new \InvalidArgumentException(sprintf('The ObjectManager with name "%s" must be an instance of EntityManagerInterface', $this->entityManagerName));
        }

        $entityManager->getConnection()->beginTransaction();
        try {
            $result = $next($message);
            $entityManager->flush();
            $entityManager->getConnection()->commit();
        } catch (\Throwable $exception) {
            $entityManager->getConnection()->rollBack();

            throw $exception;
        }

        return $result;
    }
}

[Messenger] Add a middleware that wraps all handlers in one Doctrine transaction.


<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Stdlib
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @namespace
 */
namespace Zend\Stdlib;

use ArrayIterator,
    ArrayObject;

/**
 * ArrayObject that acts as a stack with regards to iteration
 *
 * @category   Zend
 * @package    Zend_Stdlib
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class ArrayStack extends ArrayObject
{
    /**
     * Retrieve iterator
     *
     * Retrieve an array copy of the object, reverse its order, and return an
     * ArrayIterator with that reversed array.
     *
     * @return ArrayIterator
     */
    public function getIterator()
    {
        $array = $this->getArrayCopy();
        return new ArrayIterator(array_reverse($array));
    }
}

Bring milestones/exceptions up-to-date with zf2/master

Merge branch 'zf2/master' into milestones/exceptions

Conflicts:
	library/Zend/Amf/Parser/TypeLoader.php
	library/Zend/Amf/Server.php
	library/Zend/Application/AbstractBootstrap.php
	library/Zend/File/Transfer/Adapter/AbstractAdapter.php
	library/Zend/Filter/Inflector.php
	library/Zend/Filter/InputFilter.php
	library/Zend/Filter/StaticFilter.php
	library/Zend/Form/Element.php
	library/Zend/Form/Element/File.php
	library/Zend/InfoCard/XML/Security/Transform/Exception.php
	library/Zend/Navigation/Page/Mvc.php
	library/Zend/Paginator/Paginator.php
	library/Zend/Search/Lucene/Document/Exception.php
	library/Zend/Serializer/Adapter/Amf0.php
	library/Zend/Serializer/Adapter/Amf3.php
	library/Zend/Serializer/Exception.php
	library/Zend/Serializer/Serializer.php
	library/Zend/Service/Amazon/Ec2/AbstractService.php
	library/Zend/Tag/Cloud.php
	library/Zend/Tag/Cloud/Decorator/Exception.php
	library/Zend/Tag/Cloud/Decorator/HtmlTag.php
	library/Zend/Test/PHPUnit/ControllerTestCase.php
	library/Zend/Validator/StaticValidator.php
	library/Zend/Wildfire/Protocol/Exception.php
	library/Zend/Wildfire/Protocol/Exception/InvalidArgumentException.php
	tests/Zend/Application/AbstractBootstrapTest.php
	tests/Zend/Filter/InputTest.php
	tests/Zend/Filter/StaticFilterTest.php
	tests/Zend/Form/ElementTest.php
	tests/Zend/Form/FormTest.php
	tests/Zend/Paginator/PaginatorTest.php
	tests/Zend/Serializer/SerializerTest.php
	tests/Zend/Tag/Cloud/CloudTest.php
	tests/Zend/Tag/Cloud/Decorator/HtmlTagTest.php
	tests/Zend/Translate/Adapter/XmlTmTest.php


<?php
/**
 * Tests StreamIO.
 */
namespace PhpAmqpLib\Tests\Unit\Wire\IO;

use \PhpAmqpLib\Wire\IO\StreamIO;

class StreamIOTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage read_write_timeout must be at least 2x the heartbeat
     */
    public function testReadWriteTimeoutMustBeAtLeastTwiceHeartbeat()
    {
        new StreamIO(
            'localhost',
            '5512',
            1,
            1,
            null,
            false,
            1
        );
    }
}

Add test to cover new \InvalidArgumentException being thrown.


<?php

namespace Gos\Bundle\WebSocketBundle\Client\Driver;

/**
 * @author Johann Saunier <johann_27@hotmail.fr>
 */
class InMemoryDriver implements DriverInterface
{
    /**
     * @var array
     */
    protected $elements;

    public function __construct()
    {
        $this->elements = array();
    }

    /**
     * {@inheritdoc}
     */
    public function fetch($id)
    {
        if (!$this->contains($id)) {
            return false;
        }

        return $this->elements[$id];
    }

    /**
     * {@inheritdoc}
     */
    public function contains($id)
    {
        return isset($this->elements[$id]);
    }

    /**
     * {@inheritdoc}
     */
    public function save($id, $data, $lifeTime = 0)
    {
        $this->elements[$id] = $data;         //Lifetime is not supported

        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function delete($id)
    {
        unset($this->elements[$id]);

        return true;
    }
}

Add php client storage driver

Add php client storage driver


<?php

/*
 * This file is part of the Assetic package, an OpenSky project.
 *
 * (c) 2010-2013 OpenSky Project Inc
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Assetic\Filter;

use Assetic\Factory\AssetFactory;

/**
 * Like CallablesFilter, but it is also a DependencyExtractor
 *
 * @author Matthias Pigulla <mp@webfactory.de>
 */
class CallablesDependencyExtractor extends CallablesFilter implements DependencyExtractorInterface
{

    protected $extractor;

    public function __construct($loader = null, $dumper = null, $extractor = null)
    {
        parent::__construct($loader, $dumper);
        $this->extractor = $extractor;
    }

    public function getChildren(AssetFactory $factory, $content, $loadPath = null)
    {
        return $this->extractor($factory, $content, $loadPath);
    }

}

Add a subclass of CallablesFilter that also implements the DependencyExtractor interface.

Useful for tests, among other things.


<?php

namespace Zimbra\Mail\Tests\Struct;

use Zimbra\Mail\Tests\ZimbraMailTestCase;
use Zimbra\Mail\Struct\AttachmentTest;

/**
 * Testcase class for AttachmentTest.
 */
class AttachmentTestTest extends ZimbraMailTestCase
{
    public function testAttachmentTest()
    {
        $index = mt_rand(0, 10);
        $attachmentTest = new AttachmentTest(
            $index, true
        );
        $this->assertInstanceOf('\Zimbra\Mail\Struct\FilterTest', $attachmentTest);

        $xml = '<?xml version="1.0"?>' . "\n"
            .'<attachmentTest index="' . $index . '" negative="true" />';
        $this->assertXmlStringEqualsXmlString($xml, (string) $attachmentTest);

        $array = array(
            'attachmentTest' => array(
                'index' => $index,
                'negative' => true,
            ),
        );
        $this->assertEquals($array, $attachmentTest->toArray());
    }
}

Add Test case for AttachmentTest.

Add Test case for AttachmentTest.


<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class RemoveLastUserImportedSetting extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        DB::table('settings')->where(['key' => 'last_user_imported'])->delete();
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        DB::table('settings')->insert([
            'key' => 'last_user_imported',
            'value' => -1
        ]);
    }

}

Remove "last user imported" setting.

Remove "last user imported" setting.


<?php
/**
 * Created by PhpStorm.
 * User: stas
 * Date: 29.05.16
 * Time: 21:22
 */

namespace WebsocketServerBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use WebsocketServerBundle\Model\Message\Client\PlayzoneClientMessageMethod;
use WebsocketServerBundle\Model\Message\Client\PlayzoneClientMessageScope;
use WebsocketServerBundle\Model\Message\Client\Tournament\TournamentMesssageNewRound;
use WebsocketServerBundle\Model\Message\PlayzoneMessage;
use WebsocketServerBundle\Service\Client\PlayzoneClientSender;

/**
 * Class WebsocketClientTestCommand
 * @package WebsocketServerBundle\Command
 */
class WebsocketClientTestCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this->setName('websocket:client:test');
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $client = $this->getContainer()->get("ws.playzone.client");

        $this->getPlayzoneClientSender()->sendIntroductionFromRobot($client);

        $this->getPlayzoneClientSender()->send(
            $client,
            (new PlayzoneMessage())
                ->setMethod(PlayzoneClientMessageMethod::NEW_TOURNAMENT_ROUND)
                ->setScope(PlayzoneClientMessageScope::SEND_TO_USERS)
                ->setData(
                    $this->getContainer()->get("core.service.playzone_serializer")->toArray(
                        new TournamentMesssageNewRound(1)
                    )
                )
        );
    }

    /**
     * @return PlayzoneClientSender
     */
    private function getPlayzoneClientSender()
    {
        return $this->getContainer()->get("ws.playzone.client.sender");
    }
}

chore(backend): Create command for testing websocket client.


<?php

use Northstar\Models\User;

class KeyTest extends TestCase
{
    /**
     * Test retrieving multiple users.
     * GET /users
     *
     * @return void
     */
    public function testKeyNotVisibleToUserRole()
    {
        $this->get('v2/key');
        $this->assertResponseStatus(401);

        $this->asNormalUser()->get('v2/key');
        $this->assertResponseStatus(401);
    }

    /**
     * Test retrieving multiple users.
     * GET /users
     *
     * @return void
     */
    public function testKeyNotVisibleToStaffRole()
    {
        // Make a staff user & some test users.
        $staff = factory(User::class, 'staff')->create();

        $this->asUser($staff, ['role:staff'])->get('v2/key');
        $this->assertResponseStatus(401);
    }

    /**
     * Test retrieving multiple users.
     * GET /users
     *
     * @return void
     */
    public function testKeyVisibleToAdminRole()
    {
        $this->asAdminUser()->get('v2/key');
        $this->assertResponseStatus(200);
        $this->seeJsonStructure([
            'algorithm',
            'issuer',
            'public_key',
        ]);
    }
}

Add functional tests for public key endpoint.


<?php
require_once '../../src/apiClient.php';
require_once '../../src/contrib/apiCalendarService.php';
session_start();

$client = new apiClient();
$client->setApplicationName("Google Calendar PHP Starter Application");

// Visit https://code.google.com/apis/console?api=calendar to generate your
// client id, client secret, and to register your redirect uri.
// $client->setClientId('insert_your_oauth2_client_id');
// $client->setClientSecret('insert_your_oauth2_client_secret');
// $client->setRedirectUri('insert_your_oauth2_redirect_uri');
// $client->setDeveloperKey('insert_your_developer_key');
$cal = new apiCalendarService($client);
if (isset($_GET['logout'])) {
  unset($_SESSION['token']);
}

if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['token'] = $client->getAccessToken();
  header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);
}

if ($client->getAccessToken()) {
  $calList = $cal->calendarList->listCalendarList();
  print "
Calendar List

" . print_r($calList, true) . "
";

$_SESSION['token'] = $client->getAccessToken();
} else {
  $authUrl = $client->createAuthUrl();
  print "Connect Me!";
}

Add the Google Calendar starter application.

git-svn-id: 6c6eb0d3cc6e8d5f6d3a0c71e6b3abc7e9845ff1@320 6c5fc399-1a2c-022f-82ce-feb0d0b4916c


<?php

namespace Huntie\JsonApi\Tests\Serializers;

use Huntie\JsonApi\Serializers\RelationshipSerializer;
use Huntie\JsonApi\Tests\TestCase;
use Huntie\JsonApi\Tests\Fixtures\Models\Post;
use Huntie\JsonApi\Tests\Fixtures\Models\User;

class RelationshipSerializerTest extends TestCase
{
    /**
     * Test the output of toResourceLinkage on a has one relationship.
     */
    public function testHasOneToResourceLinkage()
    {
        $post = factory(Post::class)
            ->states('withAuthor')
            ->make();
        $serializer = new RelationshipSerializer($post, 'author');
        $relationship = $serializer->toResourceLinkage();

        $this->seeJsonApiResourceIdentifier(['data' => $relationship]);
        $this->assertEquals([
            'type' => 'users',
            'id' => $post->author->id,
        ], $relationship);
    }

    /**
     * Test the output of toResourceLinkage on a has many relationship.
     */
    public function testHasManyToResourceLinkage()
    {
        $user = factory(User::class)
            ->states('withPosts')
            ->make();
        $serializer = new RelationshipSerializer($user, 'posts');
        $relationship = $serializer->toResourceLinkage();

        $this->seeJsonApiIdentifierCollection(['data' => $relationship->toArray()], 2);

        foreach ($relationship as $identifier) {
            $this->assertEquals('posts', $identifier['type']);
        }
    }

    /**
     * Test the output of toResourceCollection on a has one relationship.
     */
    public function testHasOneToResourceCollection()
    {
        $post = factory(Post::class)
            ->states('withAuthor')
            ->make();
        $serializer = new RelationshipSerializer($post, 'author');
        $relationship = $serializer->toResourceCollection();

        $this->seeJsonApiResourceObject(['data' => $relationship]);
        $this->assertEquals('users', $relationship['type']);
    }

    /**
     * Test the output of toResourceCollection on a has many relationship.
     */
    public function testHasManyToResourceCollection()
    {
        $user = factory(User::class)
            ->states('withPosts')
            ->make();
        $serializer = new RelationshipSerializer($user, 'posts');
        $relationship = $serializer->toResourceCollection();

        $this->seeJsonApiObjectCollection(['data' => $relationship->toArray()], 2);

        foreach ($relationship as $identifier) {
            $this->assertEquals('posts', $identifier['type']);
        }
    }

    /**
     * Test returning a subset of attributes from toResourceCollection.
     */
    public function testCollectionFieldSubset()
    {
        $user = factory(User::class)
            ->states('withPosts')
            ->make();
        $serializer = new RelationshipSerializer($user, 'posts', [
            'posts' => ['title', 'created_at']
        ]);

        foreach ($serializer->toResourceCollection() as $record) {
            $this->assertArrayHasKey('title', $record['attributes']);
            $this->assertArrayHasKey('created_at', $record['attributes']);
            $this->assertArrayNotHasKey('content', $record['attributes']);
        }
    }
}

Add set of RelationshipSerializer tests

Add set of RelationshipSerializer tests


<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 * @package   Zend_Form
 */

namespace Zend\Form;

use \Zend\Form\Factory;

/**
 * @catagory Zend
 * @package  Zend_Form
 */
trait FormFactoryAwareTrait
{
    /**
     * @var \Zend\Form\Factory
     */
    protected $form_factory = null;

    /**
     * setFormFactory
     *
     * @param \Zend\Form\Factory $factory
     * @return
     */
    public function setFormFactory(Factory $factory)
    {
        $this->form_factory = $factory;

        return $this;
    }
}

Add a bunch of traits to ZF2

Add a bunch of traits to ZF2

As requested @

https://github.com/protecinnovations/zf2-traits/issues/1

This is the initial commit to start getting traits into ZF2.

We need to move our tests over - which are currently using Mockery.


<?php
// (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

class Search_Formatter_ValueFormatter_Timeago extends Search_Formatter_ValueFormatter_Datetime
{

	function render($name, $value, array $entry)
	{
		global $prefs;

		if (preg_match('/^\d{14}$/', $value)) {
			// Facing a date formated as YYYYMMDDHHIISS as indexed in lucene
			// Always stored as UTC
			$value = date_create_from_format('YmdHise', $value . 'UTC')->getTimestamp();
		}

		if ($prefs['jquery_timeago'] === 'y') {
			TikiLib::lib('header')->add_jq_onready('$("time.timeago").timeago();');
			return '<time class="timeago" datetime="' . TikiLib::date_format('c', $value, false, 5, false) .  '">' . $value . '</time>';
		} else  {
			return parent::render($name, $value, $entry);
		}
	}
}

[ENH] search: Add a new value formatter to use timeago if enabled (otherwise uses datetime)

git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@59270 b456876b-0849-0410-b77d-98878d47e9d5