public static function tearDownAfterClass()
 {
     if (!self::$timing) {
         echo "\n";
         return;
     }
     $class = get_called_class();
     echo "Timing results : {$class}\n";
     $s = sprintf("%40s %6s %9s %9s %4s\n", 'name', 'count', 'total', 'avg', '% best');
     echo str_repeat('=', strlen($s)) . "\n";
     echo $s;
     echo str_repeat('-', strlen($s)) . "\n";
     array_walk(self::$timing, function (&$value, $key) {
         $value['avg'] = round($value['total'] / $value['count'] * 1000000, 3);
     });
     usort(self::$timing, function ($a, $b) {
         $at = $a['avg'];
         $bt = $b['avg'];
         return $at === $bt ? 0 : ($at < $bt ? -1 : 1);
     });
     $best = self::$timing[0]['avg'];
     foreach (self::$timing as $timing) {
         printf("%40s %6d %7.3fms %7.3fus %4.1f%%\n", $timing['name'], $timing['count'], round($timing['total'] * 1000, 3), $timing['avg'], round($timing['avg'] / $best * 100, 3));
     }
     echo str_repeat('-', strlen($s)) . "\n\n";
     printf("\nTiming compensated for avg overhead for: timeIt of %.3fus and startTimer/endTimer of %.3fus per invocation\n\n", self::$timeItOverhead * 1000000, self::$startEndOverhead * 1000000);
     parent::tearDownAfterClass();
 }
Пример #2
0
 public function validateField(Structure $document, $fieldName, array $params)
 {
     $value = $document->get($fieldName);
     if (!$value) {
         return;
     }
     if (empty($params[0])) {
         throw new Exception('Type not specified');
     }
     $requiredTypes = (array) $params[0];
     $allowedTypes = array('array', 'bool', 'callable', 'double', 'float', 'int', 'integer', 'long', 'null', 'numeric', 'object', 'real', 'resource', 'scalar', 'string');
     foreach ($requiredTypes as $type) {
         if (!in_array($type, $allowedTypes)) {
             throw new Exception('Type must be one of ' . implode(', ', $allowedTypes));
         }
         if (true === call_user_func('is_' . $type, $value)) {
             return;
         }
     }
     if (!isset($params['message'])) {
         if (count($requiredTypes) === 1) {
             $params['message'] = 'Field "' . $fieldName . '" must be of type ' . $requiredTypes[0] . ' in ' . get_called_class();
         } else {
             $params['message'] = 'Field "' . $fieldName . '" must be one of types ' . implode(', ', $requiredTypes) . ' in ' . get_called_class();
         }
     }
     $document->addError($fieldName, $this->getName(), $params['message']);
 }
 public function crossover($partner, $options = array())
 {
     $a = $partner->get_data();
     $b = $this->data;
     $a_c = strlen($a);
     $b_c = strlen($b);
     $c = '';
     $c_c = $a_c >= $b_c ? $a_c : $b_c;
     // if it has same length, great!, use std algorithm
     if ($a_c == $b_c) {
         $left = mt_rand(0, 1) == 1 ? $a : $b;
         $right = $left == $b ? $a : $b;
         $sp = mt_rand(0, $c_c);
         $c .= substr($left, 0, $sp);
         $c .= substr($right, $sp);
     } else {
         /*
          * put shorter chromosome, in longer chromosome
          * example:
          *   a: aaaa
          *   b: bb
          *   result: aabb OR abba OR bbaa
          * */
         $longer = $c_c == $a_c ? 'a' : 'b';
         $shorter = $longer == 'b' ? 'a' : 'b';
         $sp_begin = mt_rand(0, ${$longer . '_c'} - ${$shorter . '_c'});
         $tmp = substr_replace(${$longer}, ${$shorter}, -$sp_begin);
         $c .= $tmp . substr(${$longer}, strlen($tmp));
     }
     $class_name = get_called_class();
     return new $class_name($c);
 }
Пример #4
0
 /**
  * @param $name
  *
  * @return mixed
  * @throws FieldNotFoundException
  */
 public function getFieldByName($name)
 {
     if (!isset($this->fields[$name])) {
         throw new FieldNotFoundException($name . ' doesn\'t exist in this ' . get_called_class());
     }
     return $this->fields[$name];
 }
 public function __construct(HTTPRequest $httpRequest, HTTPResponse $httpResponse, Logger $logger)
 {
     $this->httpRequest = $httpRequest;
     $this->httpResponse = $httpResponse;
     $this->logger = $logger;
     $this->entity = get_called_class();
 }
Пример #6
0
 /**
  * Constructor.
  * Accepts an object, array, or JSON string.
  *
  * @param mixed $in -OPTIONAL
  */
 public function __construct($in = null)
 {
     $this->_called_class = get_called_class();
     $this->_class_vars = get_class_vars($this->_called_class);
     //	remove elements with names starting with underscore
     foreach ($this->_class_vars as $k => $v) {
         if ($k[0] === '_') {
             unset($this->_class_vars[$k]);
         } elseif (is_string($v) && 0 === stripos($v, '__class__')) {
             //	We must use `eval` because we want to handle
             //		'__class__Date' and
             //		'__class__DateTime("Jan 1, 2015")' with 1 or more parameters.
             $this->_class_vars[$k] = eval(preg_replace('/^__class__(.*)$/iu', 'return new $1;', $v));
             //	Objects are always passed by reference,
             //		but we want a separate copy so the original stays unchanged.
             $this->{$k} = clone $this->_class_vars[$k];
         }
     }
     $this->_public_names = array_keys($this->_class_vars);
     //	Don't waste time with assignObject if input is one of these.
     //		Just return leaving the default values.
     switch (gettype($in)) {
         case 'NULL':
         case 'null':
         case 'bool':
         case 'boolean':
             return;
     }
     $this->assignObject($in);
 }
 /**
  * @return ITemplateFileFormatter
  * @throws InvalidStateException
  */
 public function getTemplateFileFormatter()
 {
     if ($this->templateFileFormatter === NULL) {
         throw new InvalidStateException(sprintf('Template file formatter was not set. Did you forget to call %s::injectTemplateFileFormatter()?', get_called_class()));
     }
     return $this->templateFileFormatter;
 }
Пример #8
0
 /**
  * Returns the static model of the specified AR class.
  *
  * @param string $className
  * @return YdActiveRecord the static model class
  */
 public static function model($className = null)
 {
     if (!$className) {
         $className = get_called_class();
     }
     return parent::model($className);
 }
Пример #9
0
 /**
  * Magic method run protected/private static methods.
  *
  * @param string $name The called method name.
  * @param array $arguments Array of arguments.
  */
 public static function __callStatic($name, $arguments)
 {
     $class = get_called_class();
     if (method_exists($class, $name)) {
         return forward_static_call_array([$class, $name], $arguments);
     }
 }
Пример #10
0
 public function organize(&$baseCvmp, &$ignoreVMs = [], $isMainInteration = true)
 {
     $class = get_called_class();
     $pareto = [];
     if (count($ignoreVMs) >= $baseCvmp['nvms'] or $class::$stop) {
         return $baseCvmp;
     }
     //Select Lower VM from the Rank
     $lowVM = $this->selectLowerVm($baseCvmp, $ignoreVMs);
     //generateCVMP
     $cvmps = $this->generateCVMP($baseCvmp, $lowVM);
     //foreach Possible CVMP
     $ignoreVMs[$lowVM] = $lowVM;
     foreach ($cvmps as $key => $cvmp) {
         Counter::$scenarios++;
         if (!$class::$stop and $this->isNonDominanted($baseCvmp, $cvmp)) {
             Counter::$pareto++;
             $pareto[] = $this->organize($cvmp, $ignoreVMs, false);
         }
     }
     //Taking the lowVM putted before
     array_pop($ignoreVMs);
     if (empty($pareto)) {
         Counter::$leaf++;
     }
     $pareto[] = $baseCvmp;
     $sCvmp = $this->getCvmpWithMaxCostBenefit($pareto);
     if ($isMainInteration) {
         $class::updateIgnoreVMs($ignoreVMs, $sCvmp, $lowVM);
         $sCvmp = $this->organize($sCvmp, $ignoreVMs, true);
     }
     return $sCvmp;
 }
Пример #11
0
 /**
  * Creates and instance of the mock WebServiceApplicationWeb object.
  *
  * The test can implement the following overrides:
  * - mockAppendBody
  * - mockGetBody
  * - mockPrepentBody
  * - mockSetBody
  *
  * If any *Body methods are implemented in the test class, all should be implemented otherwise behaviour will be unreliable.
  *
  * @param   TestCase  $test     A test object.
  * @param   array     $options  A set of options to configure the mock.
  *
  * @return  PHPUnit_Framework_MockObject_MockObject
  *
  * @since   11.3
  */
 public static function create($test, $options = array())
 {
     // Set expected server variables.
     if (!isset($_SERVER['HTTP_HOST'])) {
         $_SERVER['HTTP_HOST'] = 'localhost';
     }
     // Collect all the relevant methods in WebServiceApplicationWeb (work in progress).
     $methods = array('allowCache', 'appendBody', 'clearHeaders', 'close', 'execute', 'get', 'getBody', 'getDocument', 'getHeaders', 'getIdentity', 'getLanguage', 'getSession', 'loadConfiguration', 'loadDispatcher', 'loadDocument', 'loadIdentity', 'loadLanguage', 'loadSession', 'prependBody', 'redirect', 'registerEvent', 'sendHeaders', 'set', 'setBody', 'setHeader', 'triggerEvent');
     // Create the mock.
     $mockObject = $test->getMock('WebServiceApplicationWeb', $methods, array(), '', true);
     // Mock calls to JApplicationWeb::getDocument().
     $mockObject->expects($test->any())->method('getDocument')->will($test->returnValue(TestMockDocument::create($test)));
     // Mock calls to JApplicationWeb::getLanguage().
     $mockObject->expects($test->any())->method('getLanguage')->will($test->returnValue(TestMockLanguage::create($test)));
     // Mock a call to JApplicationWeb::getSession().
     if (isset($options['session'])) {
         $mockObject->expects($test->any())->method('getSession')->will($test->returnValue($options['session']));
     } else {
         $mockObject->expects($test->any())->method('getSession')->will($test->returnValue(TestMockSession::create($test)));
     }
     $test->assignMockCallbacks($mockObject, array('appendBody' => array(is_callable(array($test, 'mockAppendBody')) ? $test : get_called_class(), 'mockAppendBody'), 'getBody' => array(is_callable(array($test, 'mockGetBody')) ? $test : get_called_class(), 'mockGetBody'), 'prependBody' => array(is_callable(array($test, 'mockPrependBody')) ? $test : get_called_class(), 'mockPrependBody'), 'setBody' => array(is_callable(array($test, 'mockSetBody')) ? $test : get_called_class(), 'mockSetBody')));
     // Reset the body storage.
     self::$body = array();
     return $mockObject;
 }
Пример #12
0
 public function __unset($name)
 {
     if (!$this->__isset($name)) {
         Exception::error(I18n::__('Property %s->%s does not exist.', get_called_class(), $name));
     }
     unset($this->{$name});
 }
Пример #13
0
 protected function getAbsoluteTemplatePath($template_path)
 {
     $config = new \Config();
     $class_name = substr(get_called_class(), strrpos(get_called_class(), '\\') + 1);
     $class_name = str_replace('View_', '', $class_name);
     return $config->paths->server_root . '/../Layout/Common/Client/Template/' . implode('/', explode('_', $class_name)) . '.php';
 }
 /**
  * @param WorkflowMessage $workflowMessage
  * @return void
  */
 public function handleWorkflowMessage(WorkflowMessage $workflowMessage)
 {
     if (!MessageNameUtils::isProcessingCommand($workflowMessage->messageName())) {
         $this->workflowEngine->dispatch(LogMessage::logUnsupportedMessageReceived($workflowMessage));
     }
     try {
         if ($workflowMessage->messageType() === MessageNameUtils::COLLECT_DATA) {
             $processingMessage = $this->handleCollectData($workflowMessage);
             if (!$processingMessage instanceof ProcessingMessage) {
                 throw new \RuntimeException(sprintf("%s::handleCollectData method returned %s instead of a ProcessingMessage", get_called_class(), is_object($processingMessage) ? get_class($processingMessage) : gettype($processingMessage)));
             }
         } else {
             if ($workflowMessage->messageType() === MessageNameUtils::PROCESS_DATA) {
                 $processingMessage = $this->handleProcessData($workflowMessage);
                 if (!$processingMessage instanceof ProcessingMessage) {
                     throw new \RuntimeException(sprintf("%s::handleProcessData method returned %s instead of a ProcessingMessage", get_called_class(), is_object($processingMessage) ? get_class($processingMessage) : gettype($processingMessage)));
                 }
             } else {
                 $this->workflowEngine->dispatch(LogMessage::logUnsupportedMessageReceived($workflowMessage));
                 return;
             }
         }
         $this->workflowEngine->dispatch($processingMessage);
         return;
     } catch (\Exception $ex) {
         $this->workflowEngine->dispatch(LogMessage::logException($ex, $workflowMessage));
         return;
     }
 }
Пример #15
0
 public static function factory($config = array(), $required = array())
 {
     if (!defined('static::ENDPOINT')) {
         throw new Exception\ServiceEndpointException('A client must have an endpoint');
     }
     $default = array('base_url' => '{scheme}://{domain}/' . static::ENDPOINT);
     $required = array_merge(array('scheme', 'domain', 'base_url'), $required);
     $config = Collection::fromConfig($config, $default, $required);
     $client = new static($config->get('base_url'), $config);
     $refClass = new \ReflectionClass(get_called_class());
     $serviceDefinitionPath = dirname($refClass->getFileName());
     $classNamePieces = explode('\\', get_called_class());
     $serviceDefinitionFile = array_pop($classNamePieces) . '.json';
     switch (true) {
         case is_readable(dirname($serviceDefinitionPath) . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . $serviceDefinitionFile):
             $serviceDefinition = $serviceDefinitionPath . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . $serviceDefinitionFile;
             break;
         case is_readable($serviceDefinitionPath . DIRECTORY_SEPARATOR . $serviceDefinitionFile):
             $serviceDefinition = $serviceDefinitionPath . DIRECTORY_SEPARATOR . $serviceDefinitionFile;
             break;
         default:
             throw new Exception\ClientConfigurationException('A client must have a service definition. Could not read the file "' . $serviceDefinition . '"');
     }
     $description = ServiceDescription::factory($serviceDefinition);
     $client->setDescription($description);
     return $client;
 }
 protected static function extractProperty($element, $property)
 {
     if (!is_a($element, get_called_class()) || !property_exists($element, $property)) {
         throw new \InvalidArgumentException('property ' . $property . ' does not exists in class: ' . get_called_class());
     }
     return $element->{$property};
 }
Пример #17
0
 /**
  * Starting the error handler
  *
  * @param int $errorLevel
  */
 public static function start($errorLevel = \E_WARNING)
 {
     if (!static::$stack) {
         set_error_handler(array(get_called_class(), 'addError'), $errorLevel);
     }
     static::$stack[] = null;
 }
 public static function fromCommand(OperationCommand $command)
 {
     $response = json_decode($command->getResponse()->getBody(true), true);
     $class = get_called_class();
     // Cannot do new self() with abstract class
     return new $class($response);
 }
Пример #19
0
	/**
	 * Creates and instance of the mock JApplication object.
	 *
	 * @param   TestCase  $test  A test object.
	 * @param   array     $data  Data to prime the cache with.
	 *
	 * @return  object
	 *
	 * @since   12.1
	 */
	public static function create(TestCase $test, $data = array())
	{
		self::$cache = $data;

		// Collect all the relevant methods in JConfig.
		$methods = array(
			'get',
			'store',
		);

		// Create the mock.
		$mockObject = $test->getMock(
			'JCache',
			$methods,
			// Constructor arguments.
			array(),
			// Mock class name.
			'',
			// Call original constructor.
			false
		);

		$test->assignMockCallbacks(
			$mockObject,
			array(
				'get' => array(get_called_class(), 'mockGet'),
				'store' => array(get_called_class(), 'mockStore'),
			)
		);

		return $mockObject;
	}
Пример #20
0
 /**
  * Returns the implementation implementation registered with the Facade.
  *
  * @return Xaamin\Whatsapi\Contracts\WhatsapiInterface
  */
 public static function instance()
 {
     if (!static::$instance) {
         static::$instance = forward_static_call_array(array(get_called_class(), 'create'), func_get_args());
     }
     return static::$instance;
 }
Пример #21
0
 /**
  *   Raises an error.
  *   @param $errorMsg The error message.
  *   @param $field The component field that raised the error, if available.
  */
 protected function RaiseError($errorMsg, $field = null)
 {
     $this->LastError = $errorMsg;
     if (!empty($this->ErrorCallbackFn)) {
         call_user_func($this->ErrorCallbackFn, $this, get_called_class(), $field, $errorMsg);
     }
 }
Пример #22
0
 public function run($context)
 {
     $stock_count = 0;
     foreach ($context->stocks as $stock) {
         if ($stock->attivo == 0 || $stock->tipo != 'obbligazione') {
             // printf("%s stock %s is inactive or not a bond.\n", get_called_class(), $stock->isin);
             continue;
         }
         $bond = new Bond();
         if (!$bond->find_by_id($stock->isin)) {
             // printf("%s bond %s does not exist.\n", get_called_class(), $stock->isin);
             continue;
         }
         if ($bond->scadenza < date('Y-m-d')) {
             $stock->attivo = 0;
             $stock->save();
             $stock_count++;
         }
         // else
         // {
         //   printf("%s bond %s expires in the future\n", get_called_class(), $stock->isin);
         // }
     }
     printf("%s deactivated %d stocks\n", get_called_class(), $stock_count);
 }
 /**
  * {@inheritdoc}
  */
 public function readObjects()
 {
     //get classes
     $baseClass = $this->className;
     $classParts = explode('\\', get_called_class());
     $articleType = explode('.', $baseClass::$objectType);
     parent::readObjects();
     if ($this->categoryList) {
         if (0 !== count($this->objectIDs)) {
             $conditionBuilder = new PreparedStatementConditionBuilder();
             $conditionBuilder->add($this->getDatabaseTableIndexName() . ' IN (?)', array($this->objectIDs));
             $sql = '
                 SELECT *
                 FROM ' . $classParts[0] . WCF_N . '_' . $articleType . '_to_category
                 ' . $conditionBuilder;
             $statement = WCF::getDB()->prepareStatement($sql);
             $statement->execute($conditionBuilder->getParameters());
             while ($row = $statement->fetchArray()) {
                 if (isset($this->objects[$row[$this->getDatabaseTableIndexName()]])) {
                     $this->objects[$row[$this->getDatabaseTableIndexName()]]->setCategoryID($row['categoryID']);
                 }
             }
         }
     }
 }
Пример #24
0
 public function getTypeObject()
 {
     $class = substr(get_called_class(), strrpos(get_called_class(), '\\') + 1);
     $class = substr($class, 0, strpos($class, 'Configuration'));
     $handle = uncamelcase($class);
     return \Concrete\Core\File\StorageLocation\Type\Type::getByHandle($handle);
 }
 /**
  * @return string
  */
 public function getNodeName()
 {
     if (null === $this->nodeName) {
         $this->nodeName = preg_replace('~.*\\\\([^\\\\]+)Node$~', '$1', get_called_class());
     }
     return $this->nodeName;
 }
Пример #26
0
 /**
  * Setup a database connection (to a table)
  * @param string an optional table name, optional only in PHP <= 5.3.0
  */
 public function __construct($tableName = NULL)
 {
     // db connection
     $this->db = Fari_DbPdo::getConnection();
     // table name exists?
     if (isset($tableName)) {
         $this->tableName = $tableName;
     } else {
         if (isset($this->tableName)) {
             assert('!empty($this->tableName); // table name needs to be provided');
         } else {
             // are we using high enough version of PHP for late static binding?
             try {
                 if (version_compare(phpversion(), '5.3.0', '<=') == TRUE) {
                     throw new Fari_Exception('Table name can automatically only be resolved in PHP 5.3.0.');
                 }
             } catch (Fari_Exception $exception) {
                 $exception->fire();
             }
             // ... yes, get the name of the class as the name of the table
             $this->tableName = get_called_class();
         }
     }
     // attach observers
     $this->logger = new Fari_DbLogger();
     $this->logger->attach(new Fari_ApplicationLogger());
     // attach validator
     $this->validator = $this->attachValidator();
     // prep relationships
     $this->relationships = new Fari_DbTableRelationships();
 }
Пример #27
0
 /**
  * ScalarValue constructor.
  *
  * @param int|string $value
  *
  * @throws \UnexpectedValueException
  */
 public function __construct($value)
 {
     if (false === static::isValid($value)) {
         throw new \UnexpectedValueException(sprintf('Value "%s" is not valid value of class %s', $value, get_called_class()));
     }
     $this->value = $value;
 }
Пример #28
0
 /**
  * @param string $suffix
  * @param null|string $class
  * @return string
  */
 static function getEncodedName($suffix = '', $class = NULL)
 {
     if (NULL === $class) {
         $class = get_called_class();
     }
     return base_convert(md5($class . $suffix), 16, 36);
 }
Пример #29
0
 /**
  * @param string|object|null $class
  *
  * @return CqlDaoCollection
  */
 protected static function _createCollection($class = null)
 {
     if ($class === null) {
         $class = get_called_class();
     }
     return CqlDaoCollection::create($class);
 }
 public function crossover($partner, $options = array())
 {
     $tmp_options = array_merge(self::$options_default, $options);
     $goal = str_split($options['goal']);
     $a = str_split($partner->get_data());
     $b = str_split($this->data);
     $c_data = '';
     foreach ($goal as $i => $chr) {
         if (isset($a[$i]) && isset($b[$i])) {
             $c_data .= $chr == $a[$i] ? $a[$i] : $b[$i];
         } else {
             if (isset($a[$i]) && !isset($b[$i])) {
                 $c_data .= $a[$i];
             } else {
                 if (isset($b[$i]) && !isset($a[$i])) {
                     $c_data .= $b[$i];
                 } else {
                     $c_data .= mt_rand(0, strlen($tmp_options['seed']) - 1);
                 }
             }
         }
     }
     $class_name = get_called_class();
     return new $class_name($c_data);
 }