<?php

namespace Concrete\Tests\Config;

use PHPUnit_Framework_TestCase;

class ValuesTest extends PHPUnit_Framework_TestCase
{
    public function provideConfiguredAliases()
    {
        $config = app('config');
        $result = [];
        foreach ($config->get('app.aliases') as $alias => $actualClass) {
            $result[] = ['app.aliases', $alias, $actualClass];
        }
        foreach ($config->get('app.facades') as $alias => $actualClass) {
            $result[] = ['app.facades', $alias, $actualClass];
        }

        return $result;
    }

    /**
     * @dataProvider provideConfiguredAliases
     *
     * @param string $configKey
     * @param string $alias
     * @param string $classFromConfig
     */
    public function testConfiguredAliases($configKey, $alias, $classFromConfig)
    {
        $alias = ltrim($alias, '\\');
        $classFromConfig = ltrim($classFromConfig, '\\');
        $this->assertTrue(class_exists($alias, true));
        $actualClass = (new \ReflectionClass($alias))->getName();
        $this->assertSame($classFromConfig, $actualClass, "Accordingly to {$configKey}, {$alias} should resolve to {$classFromConfig}, but it resolves to {$actualClass}");
    }
}

Test that aliases/facades are defined correctly


```php

$client = new \GuzzleHttp\Client();
$response = $client->{{ strtolower($route['methods'][0]) }}("{{ $route['boundUri'] }}", [
@if(!empty($route['headers']))
    'headers' => [
    @foreach($route['headers'] as $header => $value)
        "{{$header}}" => "{{$value}}",
    @endforeach
    ],
@endif
@if(!empty($route['cleanQueryParameters']))
    'query' => [
    @foreach($route['cleanQueryParameters'] as $parameter => $value)
        "{{$parameter}}" => "{{$value}}",
    @endforeach
    ],
@endif
@if(!empty($route['cleanBodyParameters']))
    'json' => [
    @foreach($route['cleanBodyParameters'] as $parameter => $value)
        "{{$parameter}}" => "{{$value}}",
    @endforeach
    ],
@endif
]);
$body = $response->getBody();
print_r(json_decode((string) $body));
```

Include PHP as example language

Include PHP as example language


<?php

declare(strict_types=1);

/**
 * @copyright Copyright (c) 2022 Côme Chilliet <come.chilliet@nextcloud.com>
 *
 * @author Côme Chilliet <come.chilliet@nextcloud.com>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

namespace OCA\Files_Sharing\Migration;

use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;

/**
 * Auto-generated migration step: Please modify to your needs!
 */
class Version24000Date20220404142216 extends SimpleMigrationStep {
	/**
	 * @param IOutput $output
	 * @param Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
	 * @param array $options
	 * @return null|ISchemaWrapper
	 */
	public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
		/** @var ISchemaWrapper $schema */
		$schema = $schemaClosure();

		$table = $schema->getTable('share_external');
		$column = $table->getColumn('name');
		if ($column->getLength() < 4000) {
			$column->setLength(4000);
			return $schema;
		}
		return null;
	}
}

Set oc_share_external.name column length to 4000 to remove arbitrary limitation

Signed-off-by: Côme Chilliet <65266482bbd411837c7b5a3a962855e6c075a719@nextcloud.com>


<?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\Component\HttpKernel\Controller\ArgumentResolver;

use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;

/**
 * Yields a service keyed by _controller and argument name.
 *
 * @author Nicolas Grekas <p@tchwork.com>
 */
final class ServiceValueResolver implements ArgumentValueResolverInterface
{
    private $container;

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

    /**
     * {@inheritdoc}
     */
    public function supports(Request $request, ArgumentMetadata $argument)
    {
        return is_string($controller = $request->attributes->get('_controller')) && $this->container->has($controller) && $this->container->get($controller)->has($argument->getName());
    }

    /**
     * {@inheritdoc}
     */
    public function resolve(Request $request, ArgumentMetadata $argument)
    {
        yield $this->container->get($request->attributes->get('_controller'))->get($argument->getName());
    }
}

<?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\Component\HttpKernel\Controller\ArgumentResolver;

use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;

/**
 * Yields a service keyed by _controller and argument name.
 *
 * @author Nicolas Grekas <p@tchwork.com>
 */
final class ServiceValueResolver implements ArgumentValueResolverInterface
{
    private $container;

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

    /**
     * {@inheritdoc}
     */
    public function supports(Request $request, ArgumentMetadata $argument)
    {
        $controller = $request->attributes->get('_controller');

        if (\is_array($controller) && \is_callable($controller, true) && \is_string($controller[0])) {
            $controller = $controller[0].'::'.$controller[1];
        }

        return \is_string($controller) && $this->container->has($controller) && $this->container->get($controller)->has($argument->getName());
    }

    /**
     * {@inheritdoc}
     */
    public function resolve(Request $request, ArgumentMetadata $argument)
    {
        if (\is_array($controller = $request->attributes->get('_controller'))) {
            $controller = $controller[0].'::'.$controller[1];
        }

        yield $this->container->get($controller)->get($argument->getName());
    }
}

[HttpKernel] Fix service arg resolver for controllers as array callables


<?php

// Make sure we are called from index.php
if (!defined('SECURITY')) die('Hacking attempt');

// Check user to ensure they are admin
if (!$user->isAuthenticated() || !$user->isAdmin($_SESSION['USERDATA']['id'])) {
  header("HTTP/1.1 404 Page not found");
  die("404 Page not found");
}

$aThemes = $template->getThemes();
$aTemplates = $template->getTemplatesTree($aThemes);
$aActiveTemplates = $template->cachedGetActiveTemplates();

$aFlatTemplatesList = array();
foreach($aThemes as $sTheme) {
  $templates = $template->getTemplateFiles($sTheme);
  $aFlatTemplatesList = array_merge($aFlatTemplatesList, $templates);
}

//Fetch current slug and template
$sTemplate = @$_REQUEST['template'];
if(!in_array($sTemplate, $aFlatTemplatesList)) {
  $sTemplate = $aFlatTemplatesList[0];
}

$sOriginalTemplate = $template->getTemplateContent($sTemplate);

if (@$_REQUEST['do'] == 'save') {
  if ($template->updateEntry(@$_REQUEST['template'], @$_REQUEST['content'], @$_REQUEST['active'])) {
    $_SESSION['POPUP'][] = array('CONTENT' => 'Page updated', 'TYPE' => 'success');
  } else {
    $_SESSION['POPUP'][] = array('CONTENT' => 'Page update failed: ' . $template->getError(), 'TYPE' => 'errormsg');
  }
}

$oDatabaseTemplate = $template->getEntry($sTemplate);

if ( $oDatabaseTemplate === false ) {
  $_SESSION['POPUP'][] = array('CONTENT' => 'Can\'t fetch template from Database. Have you created `templates` table? Run 005_create_templates_table.sql from sql folder', 'TYPE' => 'errormsg');
}

$smarty->assign("TEMPLATES", $aTemplates);
$smarty->assign("ACTIVE_TEMPLATES", $aActiveTemplates);
$smarty->assign("CURRENT_TEMPLATE", $sTemplate);
$smarty->assign("ORIGINAL_TEMPLATE", $sOriginalTemplate);
$smarty->assign("DATABASE_TEMPLATE", $oDatabaseTemplate);
$smarty->assign("CONTENT", "default.tpl");
?>

Put back in the templates

Put back in the templates


<?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 OpenConext\EngineBlockBundle\Controller;

/**
 * Marker interface for throttling authentication loops
 */
interface AuthenticationLoopThrottlingController
{
}

Introduce marker interface for controllers that require authentication loop throttling

The marker interface will be used to determine whether the authentication state is to be initialized in the session or not for the routed controller


<?php

class AccessKeysSiteConfig extends DataObjectDecorator {

    function extraStatics() {
        return array(
            'db' => array(
                'SkipToMainContentAccessKey' => 'VarChar(1)'
            )
        );
    }

    public function updateCMSFields(FieldSet &$fields) {
	    $tf2 = new TextField('SkipToMainContentAccessKey');
	    $tf2->setMaxLength(1);
	    $fields->addFieldToTab('Root.Accessibility', $tf2);
	    $fields->renameField("SkipToMainContentAccessKey", _t('AccessKey.SKIP_TO_MAIN_CONTENT_ACCESS_KEY'));
	}

}
?>

FIX: Remove access key fields that are not required

Conflicts:

	code/AccessKeysSiteConfig.php


<?php

namespace ForkCMS\Bundle\CoreBundle\Tests\Validator;

use ForkCMS\Bundle\CoreBundle\Validator\UrlValidator;
use PHPUnit\Framework\TestCase;

class UrlValidatorTest extends TestCase
{
    public function testExternalUrlValidation()
    {
        $urlValidator = new UrlValidator();

        $urls = [
            'http://test.com/index.js' => true,
            'https://test.com/index.js' => true,
            '/index.js' => false,
            'index.js' => false,
            'dev/index.js' => false,
            '/dev/index.js' => false,
        ];

        foreach ($urls as $url => $isExternal) {
            $this->assertEquals($isExternal, $urlValidator->isExternalUrl($url), $url . ' was not validated correctly');
        }
    }
}

Add test for the urlvalidator

Add test for the urlvalidator


<?php

use Phinx\Migration\AbstractMigration;

class AlterUserColumnDefaults extends AbstractMigration
{

    /**
     * Migrate Up.
     */
    public function up()
    {
        $this->table('users')
            ->changeColumn('activated', 'boolean', ['default' => 0, 'null' => true])
            ->changeColumn('activation_code', 'string', ['null' => true])
            ->changeColumn('activated_at', 'string', ['null' => true])
            ->changeColumn('last_login', 'string', ['null' => true])
            ->changeColumn('persist_code', 'string', ['null' => true])
            ->changeColumn('reset_password_code', 'string', ['null' => true])
            ->changeColumn('first_name', 'string', ['null' => true])
            ->changeColumn('last_name', 'string', ['null' => true])
            ->changeColumn('created_at', 'datetime', ['default' => '0000-00-00 00:00:00'])
            ->changeColumn('updated_at', 'datetime', ['default' => '0000-00-00 00:00:00'])
            ->save();
    }

    /**
     * Migrate Down.
     */
    public function down()
    {
        $this->table('users')
            ->changeColumn('activated', 'boolean')
            ->changeColumn('activation_code', 'string')
            ->changeColumn('activated_at', 'string')
            ->changeColumn('last_login', 'string')
            ->changeColumn('persist_code', 'string')
            ->changeColumn('reset_password_code', 'string')
            ->changeColumn('first_name', 'string')
            ->changeColumn('last_name', 'string')
            ->changeColumn('created_at', 'datetime')
            ->changeColumn('updated_at', 'datetime')
            ->save();
    }
}

Add a migration to fix all of the column defaults and allow NULL for users table


<?php
/**
 * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * This file is licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License. A copy of
 * the License is located at
 *
 * http://aws.amazon.com/apache2.0/
 *
 * This file 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 'vendor/autoload.php';

use Aws\S3\S3Client;
use Aws\Exception\AwsException;

// Create a S3Client
$s3Client = new S3Client([
    'region' => 'us-west-2',
    'version' => '2006-03-01'
]);

// Retrieving the Bucket Website Configuration
$bucket = 'my-s3-bucket';
try {
    $resp = $s3Client->getBucketWebsite([
        'Bucket' => $bucket
    ]);
    echo "Succeed in retrieving website configuration for bucket: ". $bucket ."\n";
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}

// Setting a Bucket Website Configuration
$params = [
    'Bucket' => $bucket,
    'WebsiteConfiguration' => [
        'ErrorDocument' => [
            'Key' => 'foo',
        ],
        'IndexDocument' => [
            'Suffix' => 'bar',
        ],
    ]
];

try {
    $resp = $s3Client->putBucketWebsite($params);
    echo "Succeed in setting bucket website configuration.\n";
} catch (AwsException $e) {
    // Display error message
    echo $e->getMessage();
    echo "\n";
}

// Deleting a Bucket Website Configuration
try {
    $resp = $s3Client->deleteBucketWebsite([
        'Bucket' => $bucket
    ]);
    echo "Succeed in deleting policy for bucket: ". $bucket ."\n";
} catch (AwsException $e) {
    // output error message if fails
    echo $e->getMessage();
    echo "\n";
}

Add php using s3 bucket as a web host example


<?php
/**
 * Created by PhpStorm.
 * User: jasondent
 * Date: 15/09/15
 * Time: 10:39
 */

namespace Revinate\GetterSetter\test;

use Revinate\GetterSetter as gs;

class ArrayObjectTest extends \PHPUnit_Framework_TestCase {

    /**
     * @return object
     */
    protected function getData() {
        return (object) array(
            'a' => array(
                'aa' => 'aa',
                'ab' => 'ab',
            ),
            'b' => array(
                'ba' => (object) array(
                    'baa' => 'baa',
                    'bab' => 'bab',
                ),
            ),
            'c' => null
        );
    }

    public function test() {
        $data = new \ArrayObject($this->getData());

        $this->assertEquals('aa', gs\get($data, 'a.aa'));
        $this->assertEquals(null, gs\get($data, 'c', 'default'));
        $this->assertEquals('default', gs\get($data, 'd', 'default'));

        gs\set($data, 'd', array(0,1,2,3,4,5));
        $this->assertEquals(4, gs\get($data, 'd.4'));
    }

}

Add test case for ArrayObjects.

Add test case for ArrayObjects.


<?php

namespace Droath\ProjectX\Tests;

use Droath\ProjectX\Filesystem\YamlFilesystem;
use PHPUnit\Framework\TestCase;
use org\bovigo\vfs\vfsStream;

/**
 * Define Project-X test base class.
 */
abstract class TestBase extends TestCase
{
    /**
     * Project-X directory.
     *
     * @var \org\bovigo\vfs\vfsStreamDirectory
     */
    protected $projectDir;

    /**
     * Project-X root URL.
     *
     * @var string
     */
    protected $projectRoot;

    /**
     * Project-X file name.
     *
     * @var string
     */
    protected $projectFileName = 'project-x.yml';

    /**
     * {@inheritdoc}
     */
    public static function setUpBeforeClass()
    {
        if (!defined('APP_ROOT')) {
            define('APP_ROOT', '.');
        }
    }

    /**
     * {@inheritdoc}
     */
    public function setUp()
    {
        $this->projectDir = vfsStream::setup('root');
        $this->projectRoot = vfsStream::url('root');

        (new YamlFilesystem(
            $this->getProjectXFileContents(),
            $this->projectRoot
        ))
        ->save($this->projectFileName);
    }

    protected function getProjectXFileContents()
    {
        return [
            'name' => 'Project-X Test',
            'type' => 'drupal',
            'engine' => 'docker',
            'host' => [
                'name' => 'local.project-x-test.com',
                'open_on_startup' => 'true',
            ],
        ];
    }

    protected function getProjectFileUrl($filename)
    {
        return vfsStream::url("root/{$filename}");
    }
}

Add PHPunit test base class.

Add PHPunit test base class.


<?php

/*
 * This file is part of the Active Collab Bootstrap project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

namespace ActiveCollab\Bootstrap\ResultEncoder;

use ActiveCollab\Controller\ResultEncoder\ResultEncoder as BaseResultEncoder;

/**
 * @package ActiveCollab\Bootstrap\ResultEncoder
 */
class ResultEncoder extends BaseResultEncoder
{
}

Add Bootstrap level result encoder

Add Bootstrap level result encoder


<?php

namespace Risan\OAuth1\Signature;

class PlainTextSigner implements SignerInterface, KeyBasedSignerInterface
{
    use CanGetSigningKey;

    /**
     * {@inheritdoc}
     */
    public function getMethod()
    {
        return 'PLAINTEXT';
    }

    /**
     * {@inheritdoc}
     */
    public function sign($uri, array $parameters = [], $httpMethod = 'POST')
    {
        return $this->getKey();
    }
}

Add plain text signer class.

:sparkles: Add plain text signer class.


<?php

namespace AcademyHQ\API\Repository\OMA;

use AcademyHQ\API\ValueObjects as VO;
use AcademyHQ\API\HTTP\Request\Request as Request;
use Guzzle\Http\Client as GuzzleClient;
use AcademyHQ\API\Common\Credentials;
use AcademyHQ\API\Repository\BaseRepository;

/**
 * Class OffSessionRepository
 *
 * @package AcademyHQ\API\Repository\OMA
 */
class OffSessionRepository extends BaseRepository
{

	/**
	 * OffSessionRepository constructor.
	 *
	 * @param Credentials $credentials
	 */
	public function __construct(Credentials $credentials)
	{
		parent::__construct();
		$this->credentials = $credentials;
		$this->base_url .= '/oma';
	}

	/**
	 * Get Program Details
	 * @param VO\Token   $token
	 * @param VO\Integer $occupation_id
	 *
	 * @return \AcademyHQ\API\HTTP\Response\json
	 * @throws VO\Exception\MethodNotAllowedException
	 * @throws \AcademyHQ\API\HTTP\Response\Exception\ResponseException
	 */
	public function get_occupation_details(
		VO\Integer $occupation_id
	) {
		$request = new Request(
			new GuzzleClient,
			$this->credentials,
			VO\HTTP\Url::fromNative($this->base_url.'/out_session/occupation/details'),
			new VO\HTTP\Method('POST')
		);
		$request_parameters = array(
			'occupation_id' => $occupation_id->__toInteger(),
		);
		$response = $request->send($request_parameters, null);
		$data = $response->get_data();
		return $data;
	}

}

Add changes to get the occupation details out session for VC Service in OMA


<?php
/**
 * @author         Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright      (c) 2019, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Core / Model
 */

namespace PH7;

class SubscriberCoreModel extends UserCoreModel
{
    const ACTIVE_STATUS = 1;
    const INACTIVE_STATUS = 0;

    /**
     * Adding a Subscriber.
     *
     * @param array $aData
     *
     * @return int The ID of the Subscriber.
     */
    public function add(array $aData)
    {
        $rStmt = Db::getInstance()->prepare('INSERT INTO' . Db::prefix(DbTableName::SUBSCRIBER) . '(name, email, joinDate, ip, hashValidation, active, affiliatedId)
            VALUES (:name, :email, :joinDate, :ip, :hashValidation, :active, :affiliatedId)');

        $rStmt->bindValue(':name', $aData['name'], \PDO::PARAM_STR);
        $rStmt->bindValue(':email', $aData['email'], \PDO::PARAM_STR);
        $rStmt->bindValue(':joinDate', $aData['current_date'], \PDO::PARAM_STR);
        $rStmt->bindValue(':ip', $aData['ip'], \PDO::PARAM_STR);
        $rStmt->bindParam(':hashValidation', $aData['hash_validation'], \PDO::PARAM_STR, self::HASH_VALIDATION_LENGTH);
        $rStmt->bindValue(':active', $aData['active'], \PDO::PARAM_INT);
        $rStmt->bindValue(':affiliatedId', $aData['affiliated_id'], \PDO::PARAM_INT);
        $rStmt->execute();

        return (int)Db::getInstance()->lastInsertId();
    }
}

Add a SubscriberCore Model to be available everywhere for Profile Faker mod


<?php

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

DB::Execute('UPDATE utils_attachment_file af SET filestorage_id=(SELECT id FROM utils_filestorage WHERE link=(' . DB::Concat('\'attachment_file/\'', 'af.id') . '))');

Add patch to rewrite filestorage ids in attachments


<?php
/**
 * @copyright 2016 Contentful GmbH
 * @license   MIT
 */

namespace Contentful\ContentfulBundle\Tests\DataCollector;

use Contentful\ContentfulBundle\DataCollector\ContentfulDataCollector;
use Contentful\Log\ArrayLogger;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class ContentfulDataCollectorTest extends \PHPUnit_Framework_TestCase
{
    public function testGetClients()
    {
        $arrayLogger = new ArrayLogger();
        $clients = [
            'delivery' => [
                'default_client' => 'foo',
                'clients' => [
                    'foo' => ['space' => 'abc', 'token' => '123'],
                    'bar' => ['space' => 'def', 'token' => '456', 'preview' => true]
                ]
            ]
        ];

        $dataCollector = new ContentfulDataCollector($arrayLogger, $clients);

        $dataCollector->collect(new Request, new Response);

        $this->assertEquals($clients, $dataCollector->getClients());
    }
}

Add unit tests for ContentfulDataCollector


<?php
/**
 * Converts old API where the flow chart data was saved in the database as
 * "backslashed" json object. With the new API the ORM handles this automatically.
 */
class FlowChartMigrate extends BuildTask {

	public function run($request) {
		$nl = '<br />'.PHP_EOL;
		if(PHP_SAPI == 'cli') {
			$nl = PHP_EOL;
		}
		$flowchartPages = FlowchartPage::get();

		if($flowchartPages->Count() == 0) {
			echo "No pages to convert".$nl;
			return;
		}

		echo 'Will migrate '.$flowchartPages->count().' flowchart page(s) chart data:'.$nl.$nl;

		foreach($flowchartPages as $page) {
			$page->FlowchartData = stripslashes($page->FlowchartData);
			$page->write();
			echo 'Migrated "'.$page->Link().'"';
			if($page->isPublished()) {
				$page->doPublish();
				echo ' and republished it';
			}
			echo $nl;
		}
	}
}

Migrate flow chart pages chart data to the new API

CLI Usage:
./framework/sake dev/tasks/FlowChartMigrate flush=1

Via webserver:
/dev/tasks/FlowChartMigrate?flush=1


<?php

/*
 * This file is part of the FOSUserBundle package.
 *
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace FOS\UserBundle\Tests\DependencyInjection\Compiler;

use FOS\UserBundle\DependencyInjection\Compiler\SecurityEncoderFactoryPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;

class SecurityEncoderFactoryPassTest extends \PHPUnit_Framework_TestCase
{
    private $container;
    private $pass;

    public function setUp()
    {
        $this->container = new ContainerBuilder();
        $this->pass = new SecurityEncoderFactoryPass();
    }

    public function testShouldComposeAlias()
    {
        $this->container->setDefinition('security.encoder_factory.real', new Definition());
        $this->container->setAlias('security.encoder_factory', 'security.encoder_factory.real');

        $this->pass->process($this->container);

        $this->assertServiceHasAlias('security.encoder_factory.real', 'fos_user.encoder_factory.parent');
        $this->assertFalse($this->container->getAlias('fos_user.encoder_factory.parent')->isPublic());
        $this->assertServiceHasAlias('fos_user.encoder_factory', 'security.encoder_factory');
    }

    public function testShouldComposeDefinition()
    {
        $this->container->setDefinition('security.encoder_factory', $originalDefinition = new Definition());

        $this->pass->process($this->container);

        $newDefinition = $this->container->getDefinition('fos_user.encoder_factory.parent');
        $this->assertFalse($newDefinition->isPublic());
        $this->assertSame($originalDefinition, $newDefinition);

        $this->assertServiceHasAlias('fos_user.encoder_factory', 'security.encoder_factory');
    }

    private function assertServiceHasAlias($serviceId, $aliasId)
    {
        $this->assertEquals($serviceId, (string) $this->container->getAlias($aliasId), sprintf('Service "%s" has alias "%s"', $serviceId, $aliasId));
    }
}

Add unit tests for SecurityEncoderFactoryPass


<?php

namespace PageExperience\Tests\Engine\EventDispatcher;

use PageExperience\Tests\TestCase;
use PageExperience\Engine\EventDispatcher\StoppablePropagation;

/**
 * Test the StoppablePropagationTest class.
 *
 * @package ampproject/px-toolbox-php
 */
final class StoppablePropagationTest extends TestCase
{
    /**
     * Test propagation status.
     */
    public function testPropagationStatus()
    {
        /** @var StoppablePropagation **/
        $mock = $this->getMockForTrait(StoppablePropagation::class);

        self::assertFalse($mock->isPropagationStopped());

        $mock->stopPropagation();
        self::assertTrue($mock->isPropagationStopped());
    }
}

Add test cases for StoppablePropagation

Add test cases for StoppablePropagation


<?php declare(strict_types=1);

namespace hollodotme\Readis\Application\ReadModel\KeyDataBuilders;

use hollodotme\Readis\Application\Interfaces\ProvidesKeyInfo;
use hollodotme\Readis\Application\ReadModel\Constants\KeyType;
use hollodotme\Readis\Application\ReadModel\DTO\KeyData;
use hollodotme\Readis\Application\ReadModel\Interfaces\BuildsKeyData;
use hollodotme\Readis\Application\ReadModel\Interfaces\PrettifiesString;
use hollodotme\Readis\Application\ReadModel\Interfaces\ProvidesKeyData;
use hollodotme\Readis\Application\ReadModel\Interfaces\ProvidesKeyName;
use hollodotme\Readis\Infrastructure\Redis\ServerManager;

final class SortedSetKeyDataBuilder implements BuildsKeyData
{
	private const MEMBER_SEPARATOR = "\n\n---\n\n";

	/** @var ServerManager */
	private $manager;

	/** @var PrettifiesString */
	private $prettifier;

	public function __construct( ServerManager $manager, PrettifiesString $prettifier )
	{
		$this->manager    = $manager;
		$this->prettifier = $prettifier;
	}

	public function canBuildKeyData( ProvidesKeyInfo $keyInfo, ProvidesKeyName $keyName ) : bool
	{
		return !$keyName->hasSubKey() && (KeyType::SORTED_SET === $keyInfo->getType());
	}

	public function buildKeyData( ProvidesKeyInfo $keyInfo, ProvidesKeyName $keyName ) : ProvidesKeyData
	{
		$setMembers = $keyInfo->getSubItems();
		$rawMembers = [];
		$index      = 0;
		foreach ( $setMembers as $member => $score )
		{
			$rawMembers[] = $this->getMemberOutput( $index++, $member, $score );
		}

		$prettyMembers = [];
		$index         = 0;
		foreach ( $setMembers as $member => $score )
		{
			$prettyMember    = $this->prettifier->prettify( $member );
			$prettyMembers[] = $this->getMemberOutput( $index++, $prettyMember, $score );
		}

		$rawKeyData = implode( self::MEMBER_SEPARATOR, $rawMembers );
		$keyData    = implode( self::MEMBER_SEPARATOR, $prettyMembers );

		return new KeyData( $keyData, $rawKeyData );
	}

	private function getMemberOutput( int $index, string $member, float $score ) : string
	{
		return sprintf(
			"Member %d (Score: %s):\n%s\n%s",
			$index,
			(string)$score,
			str_repeat( '=', 18 + strlen( (string)$index ) + strlen( (string)$score ) ),
			$member
		);
	}
}

Add sorted set key data builder

Add sorted set key data builder


<?php
namespace common\commands;

use Yii;

class CompanyAccess
{
    public function getQueryConditions(){
        $company_id = yii::$app->getUser()->identity->company->id;
        $user_role = yii::$app->getUser()->identity->role;

        $conditions = array();

        // Student
        if($user_role <= 10)
        {
            $conditions['id'] = $company_id;
        }
        // Instructor
        else if($user_role <= 20)
        {
            $conditions['token_customer_id'] = yii::$app->getUser()->identity->tokenCustomer->id;
        }
        // Manager, Admin
        else
        {
            // No conditions
        }

        return $conditions;
    }
}

Add a company access helper

Add a company access helper


<?php

namespace Tests\Regis\GithubContext\Infrastructure\Inspection;

use PHPUnit\Framework\TestCase;
use M6Web\Component\RedisMock\RedisMockFactory;
use Predis\ClientInterface as RedisClient;
use Regis\GithubContext\Application\Inspection\ViolationsCache;
use Regis\GithubContext\Domain\Entity;
use Regis\GithubContext\Domain\Model;

class ViolationsCacheTest extends TestCase
{
    /** @var RedisClient */
    private $redis;

    /** @var ViolationsCache */
    private $violationsCache;

    /** @var Entity\Violation */
    private $violation;

    /** @var Model\PullRequest */
    private $pullRequest;

    public function setUp()
    {
        $factory = new RedisMockFactory();
        $this->redis = $factory->getAdapter(\Predis\Client::class, true);
        $this->violationsCache = new ViolationsCache($this->redis);

        $repositoryIdentifier = Model\RepositoryIdentifier::fromFullName('K-Phoen/test');

        $this->violation = Entity\Violation::newError('file.php', 42, 4, 'Test violation');
        $this->pullRequest = new Model\PullRequest($repositoryIdentifier, 2, 'head-sha', 'base-sha');
    }

    public function testWhenAViolationIsNotCached()
    {
        $this->assertFalse($this->violationsCache->has($this->violation, $this->pullRequest));
    }

    public function testWhenAViolationIsAlreadyCached()
    {
        $this->assertFalse($this->violationsCache->has($this->violation, $this->pullRequest));

        $this->violationsCache->save($this->violation, $this->pullRequest);

        $this->assertTrue($this->violationsCache->has($this->violation, $this->pullRequest));
    }

    public function testViolationsForAPullRequestCanBeCleared()
    {
        $this->violationsCache->save($this->violation, $this->pullRequest);

        $this->assertTrue($this->violationsCache->has($this->violation, $this->pullRequest));

        $this->violationsCache->clear($this->pullRequest);

        $this->assertFalse($this->violationsCache->has($this->violation, $this->pullRequest));
    }
}

Add unit tests for the violations cache

Add unit tests for the violations cache


<?php

/*
 * This file is part of the VinceTypeBundle package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace Vince\Bundle\TypeBundle\Component\Form\Test;

use Symfony\Component\Form\Forms;
use Symfony\Component\Form\Test\TypeTestCase as BaseTypeTestCase;
use Symfony\Component\Form\PreloadedExtension;
use Vince\Bundle\TypeBundle\Form\Extension\HelpTypeExtension;
use Vince\Bundle\TypeBundle\Form\Extension\LocaleTypeExtension;
use Vince\Bundle\TypeBundle\Form\Type\DatepickerType;
use Vince\Bundle\TypeBundle\Form\Type\MaskedType;
use Vince\Bundle\TypeBundle\Form\Type\RedactorType;
use Vince\Bundle\TypeBundle\Form\Type\TokenType;

/**
 * Add features to form tests
 *
 * @author Vincent Chalamon <vincentchalamon@gmail.com>
 */
abstract class TypeTestCase extends BaseTypeTestCase
{

    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        parent::setUp();

        $this->factory = Forms::createFormFactoryBuilder()
            ->addExtensions($this->getExtensions())
            ->addTypeExtensions(array(new HelpTypeExtension(), new LocaleTypeExtension()))
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function getExtensions()
    {
        return array(new PreloadedExtension(array(
            'masked'     => new MaskedType(),
            'datepicker' => new DatepickerType(),
            'redactor'   => new RedactorType(),
            'token'      => new TokenType()
            ), array())
        );
    }
}

Add abstract class for type tests

Add abstract class for type tests


<?php
/**
 * Script to fix users with `xxxx@mobile` emails, but nothing set in their mobile field.
 *
 * to run:
 * drush --script-path=../scripts/ php-script fix-mobile-fields.php
 */

$records = db_query('SELECT u.uid FROM users u
  LEFT JOIN field_data_field_mobile m ON u.uid = m.entity_id
  WHERE mail LIKE \'%@mobile\'
  AND (m.field_mobile_value IS NULL OR m.field_mobile_value = \'\')');

foreach ($records as $record) {
  $user = user_load($record->uid);

  $mobile = dosomething_user_clean_mobile_number(str_replace('@mobile', '', $user->mail));

  // If we couldn't clean the mobile number, print an error and skip this record.
  if(! $mobile) {
    print 'Could not fix mobile field for ' . $user->uid . ' (' . $user->mail . ')' . PHP_EOL;
    continue;
  }

  $edit = [];
  dosomething_user_set_fields($edit, [
    'mobile' => $mobile
  ]);

  // Make sure we're not making a duplicate of an existing mobile field.
  if($existing = dosomething_user_get_user_by_mobile($mobile)) {
    print 'Could not overwrite existing mobile field for ' . $existing->uid . ' with ' . $user->uid . ' (' . $user->mail . ')' . PHP_EOL;
    continue;
  }

  user_save($user, $edit);

  print 'Fixed mobile field for ' . $user->uid . ' (' . $user->mail . ' --> ' . $mobile . ')' . PHP_EOL;
}

Add a script to fix users who have missing mobile field.


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

$client = new apiClient();
$client->setApplicationName("Google Site Verification PHP Sample");

// Visit https://code.google.com/apis/console?api=siteVerification 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');
$service = new apiSiteVerificationService($client);

if (isset($_GET['logout'])) {
  unset($_SESSION['token']);
}

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 ($client->getAccessToken()) {
  $resources = $service->webResource->listWebResource();
  print '
' . print_r($resources, true) . '
';

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

Add a sample application for the site verification api.


<?php

/**
 * Various SAML 2 constants.
 *
 * @package simpleSAMLphp
 * @version $Id$
 */
class sspmod_saml2_Const {

	/**
	 * Top-level status code indicating successful processing of the request.
	 */
	const STATUS_SUCCESS = 'urn:oasis:names:tc:SAML:2.0:status:Success';

	/**
	 * Top-level status code indicating that there was a problem with the request.
	 */
	const STATUS_REQUESTER = 'urn:oasis:names:tc:SAML:2.0:status:Requester';

	/**
	 * Top-level status code indicating that there was a problem generating the response.
	 */
	const STATUS_RESPONDER = 'urn:oasis:names:tc:SAML:2.0:status:Responder';

	/**
	 * Top-level status code indicating that the request was from an unsupported version of the SAML protocol.
	 */
	const STATUS_VERSION_MISMATCH = 'urn:oasis:names:tc:SAML:2.0:status:VersionMismatch';

	/**
	 * Second-level status code for NoPassive errors.
	 */
	const STATUS_NO_PASSIVE = 'urn:oasis:names:tc:SAML:2.0:status:NoPassive';

}

?>

Add a class for SAML2 constants.

saml2: Add a class for SAML2 constants.

This patch adds the SimpleSAML_XML_SAML2 class, which currently contain
SAML 2 status codes constants. New SAML2 constants should be added to this
class.

git-svn-id: a243b28a2a52d65555a829a95c8c333076d39ae1@1569 44740490-163a-0410-bde0-09ae8108e29a


<?php

namespace Knp\Component\Pager\Event\Subscriber\Sortable;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Knp\Component\Pager\Event\BeforeEvent;

class SortableSubscriber implements EventSubscriberInterface
{
    public function before(BeforeEvent $event)
    {
        $disp = $event->getEventDispatcher();
        // hook all standard sortable subscribers
        $disp->addSubscriber(new Doctrine\ORM\QuerySubscriber);
        $disp->addSubscriber(new Doctrine\ODM\MongoDB\QuerySubscriber);
        $disp->addSubscriber(new ElasticaQuerySubscriber());
        $disp->addSubscriber(new SolariumQuerySubscriber);
    }

    public static function getSubscribedEvents()
    {
        return array(
            'knp_pager.before' => array('before', 1)
        );
    }
}

<?php

namespace Knp\Component\Pager\Event\Subscriber\Sortable;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Knp\Component\Pager\Event\BeforeEvent;

class SortableSubscriber implements EventSubscriberInterface
{
    public function before(BeforeEvent $event)
    {
        $disp = $event->getEventDispatcher();
        // hook all standard sortable subscribers
        $disp->addSubscriber(new Doctrine\ORM\QuerySubscriber());
        $disp->addSubscriber(new Doctrine\ODM\MongoDB\QuerySubscriber());
        $disp->addSubscriber(new ElasticaQuerySubscriber());
        $disp->addSubscriber(new PropelQuerySubscriber());
        $disp->addSubscriber(new SolariumQuerySubscriber());
    }

    public static function getSubscribedEvents()
    {
        return array(
            'knp_pager.before' => array('before', 1)
        );
    }
}

Add missing hook for `PropelQuerySubscriber`


<?php
/**
 * Created by PhpStorm.
 * User: Omar
 * Date: 4/24/2016
 * Time: 10:44 PM
 */

namespace Demo\CartBundle\Entity;

/**
 * Interface CartManagerInterface
 * @package Demo\CartBundle\Entity
 *
 * Interface for order cart management
 * Provides data access layer
 */
interface CartManagerInterface
{
    /**
     * Create new cart
     *
     * Sticking to the convention that every user has one shopping cart,
     * the cart should be created and assigned to user upon user creation.
     *
     * @return mixed
     */
    public function create();

    /**
     * Delete cart
     *
     * @return mixed
     */
    public function delete($cart);

    /**
     * Update the cart
     *
     * @param $cart
     * @return mixed
     */
    public function update($cart);

    /**
     * Add shopping item to the cart
     *
     * @param $item
     * @param $quantity
     * @return mixed
     */
    public function addShoppingItem($item, $quantity);

    /**
     * Add order item to the cart
     *
     * @param $item
     * @return mixed
     */
    public function addOrderItem($item);

    /**
     * Add wish list item to the cart
     *
     * @param $item
     * @return mixed
     */
    public function addWishOrderItem($item);

    /**
     * remove item from the cart
     *
     * @param $item
     * @return mixed
     */
    public function removeItem($item);

    /**
     * Empty the cart, remove all elements
     *
     * @param $item
     * @return mixed
     */
    public function emptyCart($item);
}

Add cart manager interface [initial version]


<?php

namespace Ice\MailerBundle\PreCompiler;

use Ice\MailerBundle\Attachment\Attachment;
use Ice\MailerBundle\Attachment\AttachmentException;
use Ice\MailerBundle\Attachment\AttachmentFactory;
use Ice\MailerBundle\Attachment\AttachmentKeyCDN;
use Ice\MailerBundle\Event\PreCompileEvent;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Class AttachmentInformation
 * @package Ice\MailerBundle\PreCompiler
 */
class AttachmentInformation
{

    /**
     *
     * @param PreCompileEvent $event
     * @throws AttachmentException
     */
    public function onPreCompile(PreCompileEvent $event)
    {
        $vars = $event->getTemplate()->getVars();
        /** @var \Ice\MailerBundle\Entity\Mail $mail */
        $mail = $event->getMail();

        if ($vars['attachments']) {
            $attachmentsInstances = [];
            foreach ($vars['attachments'] as $i => $attach) {

                $attachment = AttachmentFactory::build($attach);

                $attachmentsInstances[] = $attachment;
            }

            $mail->setAttachments(new ArrayCollection($attachmentsInstances));
        }
    }
}

<?php

namespace Ice\MailerBundle\PreCompiler;

use Ice\MailerBundle\Attachment\Attachment;
use Ice\MailerBundle\Attachment\AttachmentException;
use Ice\MailerBundle\Attachment\AttachmentFactory;
use Ice\MailerBundle\Attachment\AttachmentKeyCDN;
use Ice\MailerBundle\Event\PreCompileEvent;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Class AttachmentInformation
 * @package Ice\MailerBundle\PreCompiler
 */
class AttachmentInformation
{

    /**
     *
     * @param PreCompileEvent $event
     * @throws AttachmentException
     */
    public function onPreCompile(PreCompileEvent $event)
    {
        $vars = $event->getTemplate()->getVars();
        /** @var \Ice\MailerBundle\Entity\Mail $mail */
        $mail = $event->getMail();

        if (isset($vars['attachments']) && count($vars['attachments'])) {
            $attachmentsInstances = [];
            foreach ($vars['attachments'] as $i => $attach) {

                $attachment = AttachmentFactory::build($attach);

                $attachmentsInstances[] = $attachment;
            }

            $mail->setAttachments(new ArrayCollection($attachmentsInstances));
        }
    }
}

Fix bug with email attachments

Fix bug with email attachments


<?php

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

class AddSlugToStoriesTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('stories', function(Blueprint $table) {
            $table->string('slug');
            $table->unique(['issue_id', 'slug']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('stories', function(Blueprint $table) {
        	$table->dropIndex('stories_issue_id_slug_unique');
        	$table->dropColumn('slug');
        });
    }

}

Add slug column to story model

Add slug column to story model


<?php
namespace Airbrake;

require_once(__DIR__.'/../../src/Airbrake/Configuration.php');
require_once(__DIR__.'/../../src/Airbrake/Exception.php');

class ConfigurationTest extends \PHPUnit_Framework_TestCase {
    /**
     * @var Configuration
     */
    protected $object;

    protected function setUp() {
        $config = array(
            'component' => 'home',
            'action' => 'index',
            'projectRoot' => realpath(__DIR__),
            'url' => 'http://airbrake.io/boom',
            'hostname' => 'airbraker',
            'queue' => 'airbrake-queue',
            'getData' => array('get' => 'this'),
            'postData' => array('post' => 'that')
        );
        $this->object = new Configuration('1234',$config);
    }

    /**
     * @covers Airbrake\Configuration
     */
    public function testDefaultAttributeValues() {
        $this->assertEquals($this->object->get('timeout'), 2);
        $this->assertEquals($this->object->get('environmentName'), 'production');
        $this->assertEquals($this->object->get('apiEndPoint'), 'http://api.airbrake.io/notifier_api/v2/notices');
    }

    public function testSetAttributesAtRuntime() {
        $this->assertEquals($this->object->get('component'), 'home');
        $this->assertEquals($this->object->get('action'), 'index');
        $this->assertEquals($this->object->get('projectRoot'), realpath(__DIR__));
        $this->assertEquals($this->object->get('url'), 'http://airbrake.io/boom');
        $this->assertEquals($this->object->get('hostname'), 'airbraker');
        $this->assertEquals($this->object->get('queue'), 'airbrake-queue');
        $this->assertEquals($this->object->get('getData'), array('get' => 'this'));
        $this->assertEquals($this->object->get('postData'), array('post' => 'that'));
        $this->assertInternalType('array', $this->object->get('getData'));
        $this->assertInternalType('array', $this->object->get('postData'));
    }

    /**
     * @covers Airbrake\Configuration::getParamters
     */
    public function testGetParamters() {
        $this->assertEquals($this->object->getParamters(), array(
            'get' => 'this',
            'post' => 'that')
        );
    }

    /**
     * @covers Airbrake\Configuration::verify
     */
    public function testVerify() {
        $this->object->set('apiKey', null);
        try {
            $this->object->verify();
        } catch(\Exception $e) {
            $this->assertInstanceOf('Airbrake\Exception', $e);
        }
    }
}

Add unit test for Configuration

Add unit test for Configuration


<?php

/**
 * Solr data helper
 *
 * @category Asm
 * @package Asm_Solr
 * @author Ingo Renner <ingo@infielddesign.com>
 */
class Asm_Solr_Model_Indexer_Cms extends Asm_Solr_Model_Indexer_Abstract
{

}

Add skeleton for CMS indexer

Add skeleton for CMS indexer


<?php
declare(strict_types=1);

namespace PHPSTORM_META {

    use Moka\Moka;

    override(
        Moka::phpunit(0),
        map([
            '' => '@'
        ])
    );

    override(
        Moka::prophecy(0),
        map([
            '' => '@'
        ])
    );

    override(
        Moka::mockery(0),
        map([
            '' => '@'
        ])
    );

    override(
        Moka::phake(0),
        map([
            '' => '@'
        ])
    );

    override(
        \Moka\Plugin\PHPUnit\moka(0),
        map([
            '' => '@'
        ])
    );

    override(
        \Moka\Plugin\Prophecy\moka(0),
        map([
            '' => '@'
        ])
    );

    override(
        \Moka\Plugin\Mockery\moka(0),
        map([
            '' => '@'
        ])
    );

    override(
        \Moka\Plugin\Phake\moka(0),
        map([
            '' => '@'
        ])
    );
}

Add PhpStorm configuration for Moka

Add PhpStorm configuration for Moka


<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;

return [
    'up' => function (Builder $schema) {
        // Delete rows with non-existent entities so that we will be able to create
        // foreign keys without any issues.
        $connection = $schema->getConnection();
        $connection->table('posts')
            ->orWhereNotExists(function ($query) {
                $query->selectRaw(1)->from('discussions')->whereColumn('id', 'discussion_id');
            })
            ->delete();

        $schema->table('posts', function (Blueprint $table) {
            $table->foreign('discussion_id')->references('id')->on('discussions')->onDelete('cascade');
        });
    },

    'down' => function (Builder $schema) {
        $schema->table('posts', function (Blueprint $table) {
            $table->dropForeign(['discussion_id']);
        });
    }
];

Add discussion_id foreign key to posts table


<?php

namespace Arctic\Model\PhotoSite;

use Arctic\Model;

/**
 * Class PhotoRetailItem
 * @property int $id
 * @property string $name
 * @property string $shortname
 * @property string $variation
 * @property string $description
 * @property array $taxrates
 * @property bool $requirephysicaldelivery
 * @property int $storeshippingclassid
 * @property float $weight
 * @property string $mixable
 * @property bool $enablephotos
 * @property bool $enablephotosets
 * @property int $maxphotos
 * @property int $maxphotosets
 * @property int $maxfiles
 * @property int $maxfilesize In bytes.
 * @property float $baseprice
 * @property float $priceperphoto
 * @property float $priceperphotoset
 * @property float $priceperphotosetphoto
 * @property int $accountid
 * @property int $order
 * @property string $createdon
 * @property string $modifiedon
 * @property bool $deleted
 * @property \Arctic\Model\Store\ShippingClass $shippingclass
 */
class PhotoRetailItem extends Model
{
    public static function getApiPath() {
        return 'photoretailitem';
    }

    public function __construct() {
        parent::__construct();

        $this->_addMultipleReference('shippingclass', 'Arctic\Model\Store\ShippingClass', 'shippingclass');
    }
}

Add photo retail item model.

Add photo retail item model.


<?php
/*
  $Id$

  osCommerce, Open Source E-Commerce Solutions
  http://www.oscommerce.com

  Copyright (c) 2008 osCommerce

  Released under the GNU General Public License
*/
?>

<?php
/*
  The following copyright announcement is in compliance
  to section 2c of the GNU General Public License, and
  can not be removed, or can only be modified
  appropriately with additional copyright notices.

  For more information please read the osCommerce
  Copyright Policy at:

  http://www.oscommerce.com/about/copyright

  This comment must be left intact together with the
  copyright announcement.
*/
?>
osCommerce Online Merchant Copyright © 2008 osCommerce

osCommerce provides no warranty and is redistributable under the GNU General Public License

    <?php echo tep_image(DIR_WS_IMAGES . 'pixel_trans.gif', '', '1', '5'); ?>

    Powered by osCommerce

<?php
/*
  $Id$

  osCommerce, Open Source E-Commerce Solutions
  http://www.oscommerce.com

  Copyright (c) 2008 osCommerce

  Released under the GNU General Public License
*/
?>

<?php
/*
  The following copyright announcement is in compliance
  to section 2c of the GNU General Public License, and
  can not be removed, or can only be modified
  appropriately with additional copyright notices.

  For more information please read the osCommerce
  Copyright Policy at:

  http://www.oscommerce.com/about/copyright

  This comment must be left intact together with the
  copyright announcement.
*/
?>
osCommerce Online Merchant Copyright © 2010 osCommerce

osCommerce provides no warranty and is redistributable under the GNU General Public License

    <?php echo tep_image(DIR_WS_IMAGES . 'pixel_trans.gif', '', '1', '5'); ?>

    Powered by osCommerce

Update administration tool copyright year


<?php
/**
 * Front End Accounts
 *
 * @category    WordPress
 * @package     FrontEndAcounts
 * @since       0.1
 * @author      Christopher Davis <http://christopherdavis.me>
 * @copyright   2013 Christopher Davis
 * @license     http://opensource.org/licenses/MIT MIT
 */

namespace Chrisguitarguy\FrontEndAccounts\Form\Field;

/**
 * When we get a field we don't understand.
 *
 * @since   0.1
 */
class DummyField extends FieldBase implements FieldInterface
{
    public function render()
    {
        echo '
Invalid Field
';
    }

    public function validate()
    {
        return false;
    }
}

Add a dummy field class

Add a dummy field class


<?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_I18n
 * @subpackage View
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

namespace Zend\I18n\View\Helper;

use DateTime;
use IntlDateFormatter;
use Zend\View\Helper\AbstractHelper;
use Zend\I18n\Exception;

/**
 * View helper for formatting dates.
 *
 * @category   Zend
 * @package    Zend_I18n
 * @subpackage View
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class DateFormat extends AbstractHelper
{
    /**
     * Formatter instances.
     *
     * @var array
     */
    protected $formatters = array();

    /**
     * Add a formatter.
     *
     * @param  string            $name
     * @param  IntlDateFormatter $formatter
     * @return DateFormat
     */
    public function addFormatter($name, IntlDateFormatter $formatter)
    {
        $this->formatters[$name] = $formatter;
        return $this;
    }

    /**
     * Format a date.
     *
     * @param  DateTime|integer|array $date
     * @param  string
     * @param  string $textDomain
     * @param  string $locale
     * @return string
     */
    public function __invoke($date, $formatterName)
    {
        if (!isset($this->formatters[$formatterName]) {
            throw new Exception\RuntimeException(sprintf(
                'No formatter with name %s found',
                $formatterName
            )));
        }

        return $this->formatters[$formatterName]
                    ->format($date);
    }
}

Add date format view helper

[zen-18] Add date format view helper


<?php
namespace Zend\Config;

use Zend\ServiceManager\AbstractPluginManager;

class WriterPluginManager extends AbstractPluginManager
{
    protected $invokableClasses = array(
        'php'  => 'Zend\Config\Writer\PhpArray',
        'ini'  => 'Zend\Config\Writer\Ini',
        'json' => 'Zend\Config\Writer\Json',
        'yaml' => 'Zend\Config\Writer\Yaml',
        'xml'  => 'Zend\Config\Writer\Xml',
    );

    public function validatePlugin($plugin)
    {
        if ($plugin instanceOf Writer\AbstractWriter) {
            return;
        }

        $type = is_object($plugin) ? get_class($plugin) : gettype($plugin);

        throw new Exception\InvalidArgumentException(
            "Plugin of type {$type} is invalid. Plugin must extend ".
                __NAMESPACE__.'\Writer\AbstractWriter'
        );
    }
}

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

namespace Zend\Config;

use Zend\ServiceManager\AbstractPluginManager;

class WriterPluginManager extends AbstractPluginManager
{
    protected $invokableClasses = array(
        'php'  => 'Zend\Config\Writer\PhpArray',
        'ini'  => 'Zend\Config\Writer\Ini',
        'json' => 'Zend\Config\Writer\Json',
        'yaml' => 'Zend\Config\Writer\Yaml',
        'xml'  => 'Zend\Config\Writer\Xml',
    );

    public function validatePlugin($plugin)
    {
        if ($plugin instanceOf Writer\AbstractWriter) {
            return;
        }

        $type = is_object($plugin) ? get_class($plugin) : gettype($plugin);

        throw new Exception\InvalidArgumentException(
            "Plugin of type {$type} is invalid. Plugin must extend ".
                __NAMESPACE__.'\Writer\AbstractWriter'
        );
    }
}

Add missing file level doc-block

Add missing file level doc-block


<?php

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

class AddXmlDocumentToEntriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('entries', function (Blueprint $table) {
            $table->mediumText('xml_document')->nullable()->after('url');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('entries', function (Blueprint $table) {
            $table->dropColumn('xml_document');
        });
    }
}

Add xml_document column to entries table


<?php

use Northstar\Auth\Registrar;
use Northstar\Models\User;

class PasswordResetTest extends TestCase
{
    /**
     * Reset the server variables for the request.
     *
     * @var array
     */
    protected $serverVariables = [
        'Accept' => 'text/html',
    ];

    /**
     * Test that the homepage redirects to login page.
     */
    public function testPasswordResetFlow()
    {
        $user = factory(User::class)->create(['email' => 'forgetful@example.com']);
        $token = '';

        // We'll mock the email for this request & store the token for later.
        // @TODO: Use Laravel 5.3's Mail Fakes for this. (https://laravel.com/docs/5.3/mocking#mail-fakes)
        Mail::shouldReceive('send')->once()->with('auth.emails.password', Mockery::on(function ($array) use (&$user, &$token) {
            $token = $array['token'];

            return $user->id == $array['user']->id;
        }), Mockery::any());

        // The user should be able to request a new password by entering their email.
        $this->visit('/password/reset');
        $this->see('Forgot your password?');
        $this->submitForm('Request New Password', [
            'email' => 'forgetful@example.com',
        ]);

        // The user should visit the link that was sent via email & set a new password.
        $this->visit('/password/reset/'.$token.'?email='.$user->email);
        $this->submitForm('Reset Password', [
            'password' => 'top_secret',
            'password_confirmation' => 'top_secret',
        ]);

        // The user should be logged-in and see the confirmation message.
        $this->see('Your password has been reset!');
        $this->seeIsAuthenticatedAs($user, 'web');

        // And their account should be updated with their new password.
        $this->assertTrue(app(Registrar::class)->validateCredentials($user->fresh(), ['password' => 'top_secret']));
    }
}

Add a functional test for the password reset flow.


<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Peer, App\Hub\Node\Node, App\Hub\Service, App\User;

class FixProfile extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fix:profile';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Adds missing profiles.';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
     $q = \DB::table('nodes')
     ->select(\DB::raw('*'))
     ->join('profile', 'nodes.id', '!=', 'profile.node_id')
/*     ->where(\DB::raw('
        WHERE   NOT EXISTS
                (
                SELECT  1
                FROM    email e
                WHERE   e.id = m.id
                )
        '))*/
        ->take(10)
        ->get();
        $this->info(count($q));
        return;
    }
}

Add missing profile generator console command


<?php

namespace CultuurNet\UDB3\EventExport\Command;

use CultuurNet\UDB3\EventExport\EventExportQuery;
use CultuurNet\UDB3\EventExport\HTML\Brand;
use CultuurNet\UDB3\EventExport\HTML\Title;
use ValueObjects\Web\EmailAddress;

class ExportEventsAsPDFTest extends \PHPUnit_Framework_TestCase
{

    private $export;

    private $clonedExport;

    public function setUp()
    {
        $this->export = new ExportEventsAsPDF(
            new EventExportQuery('*.*'),
            new Brand('vlieg'),
            new Title('title')
        );
        $this->clonedExport = clone $this->export;
    }

    /**
     * @test
     */
    public function it_allows_to_specify_a_notification_email_address()
    {
        $email = new EmailAddress('john@doe.com');
        $newExport = $this->export->withEmailNotificationTo($email);

        $this->assertNotSame($newExport, $this->export);
        $this->assertEquals($email, $newExport->getAddress());

        $this->assertEquals($this->clonedExport, $this->export);
    }
}

III-217: Test event export command for allowing a notification address


<?php

namespace Concrete\Tests\Update;

use Concrete\Core\Updater\Migrations\Configuration;
use Doctrine\DBAL\Migrations\Version;
use PHPUnit\Framework\TestCase;

class LatestMigrationTest extends TestCase
{
    public function testLatestMigration(): void
    {
        $configuredDBVersion = $this->getConfiguredDBVersion();
        $latestMigrationID = $this->getLatestMigrationID();
        $this->assertSame($configuredDBVersion, $latestMigrationID, "The last migration should be {$configuredDBVersion} instead of {$latestMigrationID}");
    }

    protected function getConfiguredDBVersion(): string
    {
        $config = app('config');

        return $config->get('concrete.version_db');
    }

    protected function getLatestMigrationID(): string
    {
        $configuration = new Configuration();
        $versions = $configuration->getMigrations();
        $versionIDs = array_map(
            function (Version $version): string {
                return $version->getVersion();
            },
            $versions
        );
        sort($versionIDs);

        return array_pop($versionIDs);
    }
}

Check that the latest migration has the correct version


<?php
namespace App\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Command\LockableTrait;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Yaml\Yaml;

use App\Utils\MailAlert;
use App\Repository\DataRepository;
use App\Service\ResourceService;

class MailAlertCommand extends Command
{
    use LockableTrait;

    private $service;
    private $alert;
    private $mailer;

	public function __construct(ResourceService $service, \Swift_Mailer $mailer, MailAlert $alert) {
		$this->mailer = $mailer;
        $this->service = $service;
        $this->alert = $alert;

        parent::__construct();
    }

    protected function configure()
    {
        $this->setName('app:mail-alert');
        $this->setDescription('Check if alert for too long lock should be sent to users.');
        $this->setHelp('This command allows you to alert users about too long locked resources...');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        if (!$this->lock()) {
            $output->writeln('The command is already running in another process.');

            return 0;
        }

        $output->writeln('Checking too long locked resources...');

        $repository = $this->service->LoadRepositoryOnly();

		if ($repository === null) {
            $output->writeln('Error: Repository not found');
            return 0;
        }

        if ($this->check($repository, $output)) {
            $output->writeln('At least one resource found and user have been notified.');
        }
    }

    private function check(DataRepository $repository, OutputInterface $output)
    {
		$config = Yaml::parse(
			file_get_contents(__DIR__.'/../../config/mailalert.yaml')
		);

		$issues = $this->alert->prepareResourceCheckMessage($repository, $config);

		if (count($issues) === 0) {
            $output->writeln('Nothing to send, everything is ok.');
            return false;
		}

		if (!$this->alert->send($this->mailer, $config['resourceCheckMessage'], $issues)) {
            $output->writeln('Error: Email cannot be sent');
            return false;
        }

        return true;
    }
}

Add a command to send a alert by mail if a lock is too old.


<?php

namespace fennecweb;

class ProjectRemoveTest extends \PHPUnit_Framework_TestCase
{
    const NICKNAME = 'ProjectRemoveTestUser';
    const USERID = 'ProjectRemoveTestUser';
    const PROVIDER = 'ProjectRemoveTestUser';

    public function setUp()
    {
        $_SESSION['user'] = array(
            'nickname' => ProjectRemoveTest::NICKNAME,
            'id' => ProjectRemoveTest::USERID,
            'provider' => ProjectRemoveTest::PROVIDER,
            'token' => 'ProjectRemoveTestUserToken'
        );
    }

    public function testExecute()
    {
        // Test for error returned by empty file
        list($service) = WebService::factory('listing/Projects');
        $entries = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
        $this->assertEquals(count($entries['data']), 1);
        $id = $entries['data'][0]['internal_project_id'];
        list($service) = WebService::factory('manage/ProjectRemove');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'ids' => array($id))));
        list($service) = WebService::factory('listing/Projects');
        $entries = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
        $this->assertEquals(count($entries['data']), 0);
    }
}

Add test case for project delete webservice


<?php
//----------------------------------------------------------------------
// Copyright (c) 2012 Raytheon BBN Technologies
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and/or hardware specification (the "Work") to
// deal in the Work without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Work, and to permit persons to whom the Work
// is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Work.
//
// THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
// IN THE WORK.
//----------------------------------------------------------------------

require_once("settings.php");
require_once("user.php");

$user = geni_loadUser();
if (!isset($user) || is_null($user) || ! $user->isActive()) {
  relative_redirect('home.php');
}

$key_id = NULL;
if (array_key_exists('id', $_GET)) {
  $key_id = $_GET['id'];
}

if (is_null($key_id)) {
  relative_redirect('home.php');
}

$keys = fetchSshKeys($user->account_id);
$private_key = NULL;
$filename = NULL;
foreach ($keys as $key) {
  if ($key['id'] == $key_id) {
    $private_key = $key['private_key'];
    $filename = $key['filename'];
  }
}

if (is_null($private_key)) {
  relative_redirect('home.php');
} else {
// Set headers for download
  header("Cache-Control: public");
  header("Content-Description: File Transfer");
  header("Content-Disposition: attachment; filename=$filename");
  header("Content-Type: application/pem");
  header("Content-Transfer-Encoding: binary");
  print $private_key;
}
?>

Add page to download private ssh key.

Add page to download private ssh key.


<?php
/**
 * Plugin Name: E2E Disable jQuery Migrate
 * Description: Plugin for disabling jQuery migrate during E2E tests.
 *
 * @package   Google\Site_Kit
 * @copyright 2019 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

add_action(
	'wp_default_scripts',
	function ( WP_Scripts $scripts ) {
		$scripts->remove( 'jquery' );
		$scripts->add( 'jquery', false, array( 'jquery-core' ), $scripts->registered['jquery-core']->ver );
	}
);

Disable jqmigrate during e2e tests.

Disable jqmigrate during e2e tests.

This helps keep the console clean, especially when "persist log" is enabled.


<?php

namespace PhpWatson\Sdk\Interfaces;

use GuzzleHttp\Psr7\Response;

interface ResponseInterface
{
    /**
     * Parse an incoming PSR7 response
     *
     * @param Response $response
     * @return mixed
     */
    public function parse(Response $response);

    /**
     * Return true if the request produces an error
     *
     * @return bool
     */
    public function isError();

    public function getContent();

    public function setContent($content);

    public function getHeaders();

    public function setHeaders($headers);

    public function getStatusCode();

    public function setStatusCode($statusCode);

    public function setIsError($isError);
}

Add Response methods to interface

Add Response methods to interface


<?php
include ("conectare_db.php");
$sql = 'begin :rezultat :=  admin_pachet.sterge_domeniu(:v_id); END;';
$stid = oci_parse($connection, $sql);
oci_bind_by_name($stid, ":v_id", $_POST["d_id"]);
oci_bind_by_name($stid, ':rezultat', $rezultat, 100);
if(!oci_execute($stid))
{
    $e = oci_error($stid);
    echo "Something went wrong :( <br/>";
    echo "Error: " . $e['message'];
}
oci_free_statement($stid);
oci_close($connection);
echo $rezultat;
?>

Add admin delete domain PHP

Add admin delete domain PHP


<?php

/*
 * Require Performance
 */

require_once('../vendor/autoload.php');
use Performance\Performance;

/*
 * One test for measurements the accurate
 */
Performance::point('1A');
Performance::point('1B');
Performance::point('1C');
Performance::point('1D');

Performance::point('2A');
Performance::finish();
Performance::point('2B');
Performance::finish();
Performance::point('2C');
Performance::finish();
Performance::point('2D');

// Finish all tasks and show test results
Performance::results();

Add example for testing measurement more accurate


<?php
/**
 * Created by PhpStorm.
 * User: mirel
 * Date: 22.02.2016
 * Time: 11:53
 */

namespace mpf\base;

class Singleton extends Object {

    private static $_instances = [];

    /**
     * @param array $config
     * @return static
     */
    public static function get($config = []) {
        $c = md5(json_encode($config));
        $class = get_called_class();
        if (!isset(self::$_instances[$class . $c]))
            self::$_instances[$class . $c] = new $class($config);
        return self::$_instances[$class . $c];
    }
}

Add a new helper class that extends Object and adds ::get() method


#!/usr/bin/php
<?php

// Don't allow from Apache
if (PHP_SAPI !== 'cli')
{
    die('Nope.');
}

if (count($argv) < 2) {
    die("Usage: rpicons.php <folder>\n");
}

error_reporting(E_ALL);
ini_set('display_errors', 1);

$iconFolder = $argv[1];

if (!file_exists($iconFolder))
{
    die("Folder not found: $iconFolder\n");
}

$targetFolder = dirname(__FILE__) . '/target';
if (!file_exists($targetFolder)) mkdir($targetFolder);

$sourceFiles = scandir($iconFolder);
foreach ($sourceFiles as $sourceFile) {
    if (strpos($sourceFile, '.png') === FALSE) continue;

    $sourceImage = imagecreatefrompng($iconFolder . '/' . $sourceFile);
    $sourceWidth = imagesx($sourceImage);
    $sourceHeight = imagesy($sourceImage);
    $icon = imagecreatetruecolor(32, 32);
    imagecopyresampled($icon, $sourceImage, 0, 0, 0, 0, 32, 32, $sourceWidth, $sourceHeight);
    imagepng($icon, $targetFolder . '/' . $sourceFile);
    imagedestroy($sourceImage);
    imagedestroy($icon);

    echo "Resized $sourceFile\n";
}

Add a helpful script for resizing any icon to 32x32


<?php
class PHPCS_Sniffs_ControlStructures_ControlSignatureSniff extends PHP_CodeSniffer_Standards_AbstractPatternSniff
{
    public function __construct()
    {
        parent::__construct(true);
    }

    protected function getPatterns()
    {
        return array(
          'do {EOL...} while (...);EOL',
          'while (...) {EOL',
          'for (...) {EOL',
          'if (...) {EOL',
          'foreach (...) {EOL',
          // Decide wether to use '}EOLelse' or '} else'
          #'}EOLelse if (...) {EOL',
          #'}EOLelse {EOL',
          'do {EOL',
        );
    }
}

Revert "Delete" from 137c29648e. Restored the brace style sniff deactivation the part the code base is unclear about.


<?php declare(strict_types=1);

namespace PAF\Common\Presenter;

use PAF\Common\Security\LiveUserIdentity;
use PAF\Modules\CommonModule\Model\User;
use PAF\Modules\CommonModule\Services\Users;
use PAF\Modules\DirectoryModule\Model\Person;
use PAF\Modules\DirectoryModule\Services\PersonService;

trait HasAppUser
{
    /** @var User */
    protected $appUser;
    /** @var Person */
    protected $dirPerson;

    public function injectAppUser(PersonService $personService)
    {
        if (!$this->user->isLoggedIn()) {
            return;
        }

        /** @var LiveUserIdentity $identity */
        $identity = $this->user->identity;
        $this->appUser = $identity->getEntity();
        $this->dirPerson = $personService->findOneBy(['user' => $this->appUser]);
    }
}

Add presenter trait for user initialization


<?php
/**
 * A dependency injection container for lazy-evaluated shared resources.
**/
namespace Ob_Ivan\ResourceContainer;

use ArrayAccess;

class ResourceContainer implements ArrayAccess
{
    /**
     * @var [<string name> => <mixed(self) factory>]
    **/
    private $factories = [];

    /**
     * @var [<string name> => <mixed value>]
    **/
    private $values = [];

    // public : ArrayAccess //

    public function offsetExists($name)
    {
        return isset($this->values[$name]) || isset($this->factories[$name]);
    }

    public function offsetGet($name)
    {
        if (isset($this->values[$name])) {
            return $this->values[$name];
        }
        if (isset($this->factories[$name])) {
            return $this->factories[$name]($this);
        }
        throw new Exception('Unknown resource "' . $name . '"');
    }

    public function offsetSet($name, $value)
    {
        $this->values[$name] = $value;
        unset($this->factories[$name]);
    }

    public function offsetUnset($name)
    {
        unset($this->values[$name]);
        unset($this->factories[$name]);
    }

    // public : ResourceContainer //

    public function __construct(array $values = [])
    {
        foreach ($values as $name => $value) {
            $this[$name] = $value;
        }
    }

    public function register($name, callable $factory)
    {
        $this->factories[$name] = $this->share($factory);
        unset($this->values[$name]);
    }

    // private //

    private function share(callable $factory)
    {
        return function ($container) use ($factory) {
            static $value;
            if (is_null($value)) {
                $value = $factory($container);
            }
            return $value;
        };
    }
}

Add a prototype for dependency injection container of my choice


<?php
declare(ENCODING = 'utf-8');
namespace F3\FLOW3\Property\TypeConverter;

/*                                                                        *
 * This script belongs to the FLOW3 framework.                            *
 *                                                                        *
 * It is free software; you can redistribute it and/or modify it under    *
 * the terms of the GNU Lesser General Public License as published by the *
 * Free Software Foundation, either version 3 of the License, or (at your *
 * option) any later version.                                             *
 *                                                                        *
 * This script is distributed in the hope that it will be useful, but     *
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN-    *
 * TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser       *
 * General Public License for more details.                               *
 *                                                                        *
 * You should have received a copy of the GNU Lesser General Public       *
 * License along with the script.                                         *
 * If not, see http://www.gnu.org/licenses/lgpl.html                      *
 *                                                                        *
 * The TYPO3 project - inspiring people to share!                         *
 *                                                                        */

/**
 * Converter which transforms a string to a boolean, by simply casting it.
 *
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License, version 3 or later
 * @api
 * @scope singleton
 */
class StringToBooleanConverter extends \F3\FLOW3\Property\TypeConverter\AbstractTypeConverter {

	protected $sourceTypes = array('string');
	protected $targetType = 'boolean';
	protected $priority = 1;

	public function convertFrom($source, $targetType, array $subProperties = array(), \F3\FLOW3\Property\PropertyMappingConfigurationInterface $configuration = NULL) {
		return (boolean)$source;
	}
}
?>

Add string to boolean Type converter

[+FEATURE] Add string to boolean Type converter

Change-Id: Ia4d93a20bd61900f503815c93c7752ae4300469f
Original-Commit-Hash: 52ef434ce2c825bd565d171a0e8adc99125742b2


<?php

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

class RenameKillLogApiEndpoint extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		\DB::statement("UPDATE `api_calllist` SET `name` = 'KillMails' WHERE `name` = 'KillLog'");
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		\DB::statement("UPDATE `api_calllist` SET `name` = 'KillLog' WHERE `name` = 'KillMails'");
	}

}

Rename KillLog API to KillMails

Rename KillLog API to KillMails


<?php

use Aviat\Ion\Friend;
use Aviat\Ion\Cache\CacheManager;

class CacheManagerText extends AnimeClient_TestCase {

	protected $cachedTime;

	public function __call($name, $args)
	{
		return call_user_func_array($name, $args);
	}

	public function setUp()
	{
		parent::setUp();
		$this->cache = new CacheManager($this->container);
		$this->friend = new Friend($this->cache);
	}

	public function testGet()
	{
		$this->cachedTime = $this->cache->get($this, 'time');
		$this->assertEquals($this->cache->get($this, 'time'), $this->cachedTime);
	}

	public function testGetFresh()
	{
		$this->assertNotEquals($this->cache->getFresh($this, 'time'), $this->cachedTime);
	}

	public function testPurge()
	{
		$this->cachedTime = $this->cache->get($this, 'time');
		$key = $this->friend->generateHashForMethod($this, 'time', []);
		$this->cache->purge();
		$this->assertEmpty($this->friend->driver->get($key));
	}
}

Add tests for Cache Manager class

Add tests for Cache Manager class


<?php

class BloomdClient
{
	// CONSTANTS - - - - - - - - - - - - - - - - - - - - -

	// Constants for TCP or UDP connection to bloomd
	const BLOOMD_TCP = 0;
	const BLOOMD_UDP = 1;

	// INSTANCE VARIABLES - - - - - - - - - - - - - - - - -

	// Server host, port, protocol
	protected $host;
	protected $port;
	protected $protocol;

	// The socket used for communication with bloomd
	protected $socket;

	// Connection status
	protected $connected = false;

	// CONSTRUCTOR - - - - - - - - - - - - - - - - - - - -

	public function __construct($host, $port = 8673, $protocol = self::BLOOMD_TCP)
	{
		$this->host = $host;
		$this->port = $port;
		$this->protocol = $protocol;

		// If protocol is TCP, open persistent connection to server
		if ($protocol === self::BLOOMD_TCP)
		{
			$this->connect();
		}
	}

	// Initiate a connection to bloomd server
	public function connect()
	{
		if (!$this->connected)
		{
			// Create a IPv4 TCP socket
			$this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
			socket_set_option($this->socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 1, 'usec' => 0));

			// Connect to host
			socket_connect($this->socket, $this->host, intval($this->port));

			$this->connected = true;
			return true;
		}

		return false;
	}

	// Close a connection to bloomd server
	public function disconnect()
	{
		// Verify socket is actually open
		if ($this->connected && isset($this->socket))
		{
			// Close socket
			socket_close($this->socket);

			$this->connected = false;
			return true;
		}

		return false;
	}

	// Send a message to server on socket
	private function send($input)
	{
		if (!$this->connected || empty($this->socket))
		{
			throw new Exception(__METHOD__ . ": client is not connected to bloomd server!");
		}

		// Write message on socket
		socket_write($this->socket, $input);

		return true;
	}
}

Add initial basic bloomd client

Add initial basic bloomd client


<?php

namespace Glavweb\CoreBundle\Mapping\Annotation;

/**
 * Class ImagineFilters
 * @package Glavweb\UploaderBundle\Mapping\Annotation
 *
 * @Annotation
 * @Target({"PROPERTY"})
 */
class ImagineFilters
{
    /**
     * @var array
     */
    public $filters;

    /**
     * @var string
     */
    public $property;

    /**
     * @return array
     */
    public function getFilters()
    {
        return $this->filters;
    }

    /**
     * @return string
     */
    public function getProperty()
    {
        return $this->property;
    }
}

Add the imagine filters annotation.

Add  the imagine filters annotation.


<?php

namespace MS\PHPMD\Tests\Unit\CleanCode;

use MS\PHPMD\Rule\CleanCode\InlineIf;
use MS\PHPMD\Tests\Unit\AbstractApplyTest;

/**
 * Class InlineIfTest
 *
 * @package MS\PHPMD\Tests\Unit\CleanCode
 */
class InlineIfTest extends AbstractApplyTest
{
    /**
     * @covers MS\PHPMD\Rule\CleanCode\InlineIf
     */
    public function testFindOneInlineIf()
    {
        $node = $this->getMethodNode('TestClass', 'doSomething', [
            'ConditionalExpression' => [$this->getNode('?')]
        ]);

        $this->assertRule($node, 1);
    }

    /**
     * @covers MS\PHPMD\Rule\CleanCode\InlineIf
     */
    public function testFindNoInlineIf()
    {
        $node = $this->getMethodNode('TestClass', 'tryMore', [
            'ConditionalExpression' => []
        ]);

        $this->assertRule($node, 0);
    }

    /**
     * @return InlineIf
     */
    protected function getRule()
    {
        $rule =  new InlineIf();

        return $rule;
    }
}

Add inline if unit test

Add inline if unit test


<?php
namespace RbCommentTest\Factory\Controller;

use Interop\Container\ContainerInterface;
use PHPUnit_Framework_TestCase;
use RbComment\Controller\CommentController;
use RbComment\Factory\Controller\CommentControllerFactory;
use RbComment\Model\CommentTable;
use ZendService\Akismet\Akismet;

final class CommentControllerFactoryTest extends PHPUnit_Framework_TestCase
{
    /**
     * @group factory
     */
    public function testInvokeWillCreateACommentControllerInstance()
    {
        $containerMock = $this->createMock(ContainerInterface::class);

        $configServiceMock  = [uniqid()];
        $commentTableMock   = $this->createMock(CommentTable::class);
        $akismetServiceMock = $this->createMock(Akismet::class);

        $commentControllerFactory = new CommentControllerFactory();

        // Expectations
        $containerMock->expects($this->exactly(3))
                      ->method('get')
                      ->withConsecutive(
                          ['Config'],
                          [CommentTable::class],
                          ['RbComment\Akismet']
                      )
                      ->willReturnOnConsecutiveCalls(
                          $configServiceMock,
                          $commentTableMock,
                          $akismetServiceMock
                      );

        $controller = $commentControllerFactory($containerMock, CommentController::class);

        // Assertions
        $this->assertInstanceOf(CommentController::class, $controller);
    }
}

Add tests for the comment controller factory


<?php
/**
 *
FormFieldsSemanticUI

 *
 * Project Name: Backfront
 * Project URI: https://github.com/BackFront/umbrella-packege
 * Description: Generate the HTML fields
 * Version: 1.0.0
 * Author: Douglas Alves
 * Author URI: http://alvesdouglas.com.br/
 * License: Apache License 2.0
 *
 * @package Backfront
 * @subpackage Form
 * @version 1.0.0
 *
 * @author Douglas Alves <alves.douglaz@gmail.com>
 * @link https://github.com/BackFront/backfront-package Project Repository
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @since 1.0.0
 *
 * FIELDS:
 * - text
 * - textarea
 * - number
 * - checkbox
 * - radio
 * - select
 * - file input/media
 * - image input
 * - submit
 * - button
 * - title
 * - separator
 * - url
 * - color picker
 * - icon_picker
 * - date
 * - custom
 */

namespace Backfront\Form
{

    class FormFieldsSemanticUI implements IFormFields
    {

        public function __call($name, $arguments)
        {
            trigger_error("O field de tipo {$name} não pode ser gerado", E_USER_WARNING);
        }

        public static function text($args)
        {
            return "olá mundo UI
";
        }

        public static function textarea($args)
        {

        }

        public static function checkbox($args)
        {

        }

        public static function radio($args)
        {

        }

        public static function select($args)
        {

        }

        public static function file_input($args)
        {

        }

        public static function submit($args)
        {

        }

        public static function button($args)
        {

        }

        /**
         *
is_selected

         *
         * Verify if the current value is selected
         * use the database value in variable $selected
         *
         * @param string $current
         * @param string $selected
         * @param string $type
         * @return string
         */
        public static function is_selected($current, $selected, $type = "select")
        {
            $s = null;
            if ($current == $selected && $type == 'select')
                return "selected=\"selected\" ";
            if ($current == $selected && $type == 'check')
                return "checked=\"checked\" ";
            return;
        }

    }
}

Create a abstract class 'FormFieldSemanticUI' - responsible to generate html fields using the frontend frameword 'Semanti-ui'


<?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\Bundle\FrameworkBundle\Tests\Templating\Loader;

use Symfony\Bundle\FrameworkBundle\Templating\Loader\TemplateLocator;
use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;

class TemplateLocatorTest extends TestCase
{
    public function testLocateATemplate()
    {
        $template = new TemplateReference('bundle', 'controller', 'name', 'format', 'engine');

        $fileLocator = $this->getFileLocator();

        $fileLocator
            ->expects($this->once())
            ->method('locate')
            ->with($template->getPath(), '/path/to/fallback')
            ->will($this->returnValue('/path/to/template'))
        ;

        $locator = new TemplateLocator($fileLocator, '/path/to/fallback');

        $this->assertEquals('/path/to/template', $locator->locate($template));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testThrowsExceptionWhenTemplateNotFound()
    {
        $template = new TemplateReference('bundle', 'controller', 'name', 'format', 'engine');

        $fileLocator = $this->getFileLocator();

        $fileLocator
            ->expects($this->once())
            ->method('locate')
            ->will($this->throwException(new \InvalidArgumentException()))
        ;

        $locator = new TemplateLocator($fileLocator, '/path/to/fallback');

        $locator->locate($template);
    }

    protected function getFileLocator()
    {
        return $this
            ->getMockBuilder('Symfony\Component\Config\FileLocator')
            ->setMethods(array('locate'))
            ->setConstructorArgs(array('/path/to/fallback'))
            ->getMock()
        ;
    }
}

[FrameworkBundle] Add unit tests for the TemplateLocator class


<?php

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

class AddFingerprintIndexToConfessionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('confessions', function (Blueprint $table) {
            $table->index('fingerprint');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('confessions', function (Blueprint $table) {
            $table->dropIndex('confessions_fingerprint_index');
        });
    }
}

Add migration to index fingerprint column


<?php

namespace Tests\AppBundle\API\Listing;

use AppBundle\AppBundle;
use AppBundle\DB;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;

class OrganismsTest extends WebTestCase
{

    public function testExecute()
    {
        $client = static::createClient();
        $default_db = $client->getContainer()->getParameter('default_db');
        $session = null;
        $organisms = $client->getContainer()->get('app.api.webservice')->factory('listing', 'organisms');
        $parameterBag = new ParameterBag(array('dbversion' => $default_db, 'search' => 'bla', 'limit' => 5));
        $results = $organisms->execute($parameterBag, $session);
        $expected = array(
            array("organism_id" => 48, "scientific_name" => "Prototheca blaschkeae", "rank" => "species", "common_name" => null),
            array("organism_id" => 338, "scientific_name" => "Groenbladia", "rank" => "genus", "common_name" => null),
            array("organism_id" => 445, "scientific_name" => "Leucaena pueblana", "rank" => "species", "common_name" => null),
            array("organism_id" => 756, "scientific_name" => "Clusia blattophila", "rank" => "species", "common_name" => null),
            array("organism_id" => 1774, "scientific_name" => "Gloeospermum blakeanum", "rank" => "species", "common_name" => null)
        );
        $this->assertEquals($expected, $results);
    }
}

Add test for listing organisms webservice


<?php

namespace AppBundle\API\Upload;

use AppBundle\Service\DBVersion;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\HttpKernel\KernelInterface;

class Traits
{
    private $dbversion;
    private $kernel;

    /**
     * Traits constructor.
     * @param $dbversion
     * @param KernelInterface $kernel
     */
    public function __construct(DBVersion $dbversion, KernelInterface $kernel)
    {
        $this->dbversion = $dbversion->getConnectionName();
        $this->kernel = $kernel;
    }

    public function execute($user, $traitType, $defaultCitation, $mapping, $skipUnmapped){
        $content = file_get_contents($_FILES[0]['tmp_name']);
        $result = $this->executeTraitImportCommand($content, $user, $traitType, $defaultCitation, $mapping, $skipUnmapped);
        return $result;
    }

    private function executeTraitImportCommand($content, $user, $traitType, $defaultCitation, $mapping, $skipUnmapped)
    {
        $tempFile = tempnam(sys_get_temp_dir(), 'traitUpload');
        file_put_contents($tempFile, $content);
        $application = new Application($this->kernel);
        $application->setAutoExit(false);

        $input = new ArrayInput(array(
           'command' => 'app:import-trait-entries',
           // (optional) define the value of command arguments
           'file' => $tempFile,
           // (optional) pass options to the command
           '--fennec-user-id' => $user->getId(),
            '--dbversion' => $this->dbversion,
            '--traittype' => $traitType,
            '--default-citation' => $defaultCitation,
            '--mapping' => $mapping,
            '--skip-unmapped' => $skipUnmapped,
            '--provider' => 'userImport'
        ));

        // You can use NullOutput() if you don't need the output
        $output = new BufferedOutput();
        $application->run($input, $output);

        // return the output, don't use if you used NullOutput()
        $result = $output->fetch();
        var_dump($result);
        unlink($tempFile);
        return $result;
    }

}

Add new service for uploading traits

Add new service for uploading traits


<?php

namespace Oro\Bundle\ApiBundle\Tests\Unit\Processor\NormalizeValue;

use Oro\Bundle\ApiBundle\Processor\NormalizeValue\NormalizeValueContext;

class NormalizeValueContextTest extends \PHPUnit_Framework_TestCase
{
    /** @var NormalizeValueContext */
    protected $context;

    public function setUp()
    {
        $this->context = new NormalizeValueContext();
    }

    public function testArrayDelimiter()
    {
        $this->assertEquals(',', $this->context->getArrayDelimiter());
        $this->context->setArrayDelimiter('-');
        $this->assertEquals('-', $this->context->getArrayDelimiter());
    }

    public function testDataType()
    {
        $this->assertFalse($this->context->has('dataType'));
        $this->context->setDataType('string');
        $this->assertEquals('string', $this->context->getDataType());
    }

    public function testRequirement()
    {
        $this->assertFalse($this->context->has('requirement'));
        $this->context->setRequirement('.+');
        $this->assertEquals('.+', $this->context->getRequirement());
        $this->context->removeRequirement();
        $this->assertFalse($this->context->has('requirement'));
    }

    public function testArrayAllowed()
    {
        $this->assertFalse($this->context->has('dataType'));
        $this->context->setArrayAllowed(true);
        $this->assertTrue($this->context->isArrayAllowed());
    }
}

BAP-9469: Increase JSON API performance
 - Add unit tests


<?php
defined('BASEPATH') OR exit('No direct script access allowed');

//  CONFIG APP BY HEKKYDEV REPOSITORY

$config['ci_app_title'] = "SCM | Pertamina LPG Sistem Management";

Create app title on config folder

Create app title on config folder


<?php
namespace Talk;

use Application\BaseCommentEntity;
use stdClass;

class TalkCommentEntity extends BaseCommentEntity
{
    public function getUsername()
    {
        if (!isset($this->data->username)) {
            return null;
        }

        return $this->data->username;
    }

    public function getTalkTitle()
    {
        if (!isset($this->data->talk_title)) {
            return null;
        }

        return $this->data->talk_title;
    }

    public function getTalkUri()
    {
        if (!isset($this->data->talk_uri)) {
            return null;
        }

        return $this->data->talk_uri;
    }

    public function getCommentUri()
    {
        if (!isset($this->data->uri)) {
            return null;
        }

        return $this->data->uri;
    }

    public function canRateTalk($user_uri)
    {
        if ($this->data->user_uri == $user_uri) {
            return false;
        }

        return true;
    }
}

<?php
namespace Talk;

use Application\BaseCommentEntity;
use stdClass;

class TalkCommentEntity extends BaseCommentEntity
{
    public function getUsername()
    {
        if (!isset($this->data->username)) {
            return null;
        }

        return $this->data->username;
    }

    public function getTalkTitle()
    {
        if (!isset($this->data->talk_title)) {
            return null;
        }

        return $this->data->talk_title;
    }

    public function getTalkUri()
    {
        if (!isset($this->data->talk_uri)) {
            return null;
        }

        return $this->data->talk_uri;
    }

    public function getCommentUri()
    {
        if (!isset($this->data->uri)) {
            return null;
        }

        return $this->data->uri;
    }

    public function canRateTalk($user_uri)
    {

        if (isset($this->data->user_uri) && $this->data->user_uri == $user_uri) {
            return false;
        }

        return true;
    }
}

Check for existince of uri

Check for existince of uri


<?php

use Gaufrette\Adapter\InMemory;
require_once __DIR__ . '/CommandTestCase.php';

class HydrateTest extends CommandTestCase
{
    protected
        $mock;

    protected function setUp()
    {
        parent::setUp();

        $this->app['sources.fileSystem.adapter'] = new InMemory(array(
        	'src/file' => '',
        ));

        $this->mock = $this->getMock(
            'Karma\Hydrator',
            array(),
            array($this->app['sources.fileSystem'], $this->app['configuration'])
        );
    }

    /**
     * @dataProvider providerTestOptions
     */
    public function testOptions($option, $expectedMethodCall)
    {
        $this->mock->expects($this->once())
            ->method($expectedMethodCall);

        $this->app['hydrator'] = $this->mock;

        $this->runCommand('hydrate', array(
            $option => true,
            'sourcePath' => 'src/'
        ));
    }

    public function providerTestOptions()
    {
        return array(
        	array('--dry-run', 'setDryRun'),
        	array('--backup', 'enableBackup'),
        );
    }
}

Add hydrate command unit test

Add hydrate command unit test