Esempio n. 1
0
 public final function last()
 {
     if (0 === $this->count()) {
         throw new UserException('Failed to get the last item, because this bulk is empty.', $this);
     }
     return Kit::last($this->itemList);
 }
Esempio n. 2
0
 public function setEmail($email)
 {
     // @TODO: validate
     Kit::ensureString($email);
     $this->setInfo('Email', $email);
     return $this;
 }
Esempio n. 3
0
 protected final function callParent($method_name)
 {
     $arg_list = func_get_args();
     $method_name = $arg_list[0];
     $arg_list = Kit::slice($arg_list, 1);
     return $this->execute($method_name, $arg_list, TRUE);
 }
Esempio n. 4
0
 public final function createEntity()
 {
     if (TRUE === is_null($this->entityClassName)) {
         $this->includeEntity();
     }
     $entity_class_name = $this->entityClassName;
     Kit::ensureString(static::COLLECTION_NAME, TRUE);
     return new $entity_class_name(static::COLLECTION_NAME, static::ENTITY_PATH, FALSE);
 }
Esempio n. 5
0
 /**
  * @param mixed $value
  * @return boolean
  */
 public static final function isFloat($value)
 {
     if (TRUE === Kit::isFloat($value) or TRUE === Kit::isInt($value)) {
         return TRUE;
     } elseif (1 === preg_match('@^(\\d+(\\.\\d*)?|\\.\\d+)$@', $value)) {
         return TRUE;
     } else {
         return FALSE;
     }
 }
Esempio n. 6
0
 public static final function getInstance($collection_name, $entity_path)
 {
     Kit::ensureString($entity_path);
     if (FALSE === isset(self::$entityWrapperContainer)) {
         self::$entityWrapperContainer = new Container();
     }
     if (TRUE === self::$entityWrapperContainer->has($entity_path)) {
         return self::$entityWrapperContainer->get($entity_path);
     } else {
         return self::$entityWrapperContainer->set($entity_path, new static($collection_name));
     }
 }
Esempio n. 7
0
 public static function initialize()
 {
     $constantMapping = (require_once Loader::APPPATH() . 'Config/Const.php');
     Kit::update(self::$constantMapping, $constantMapping);
     $constantMapping = (require_once Loader::APPPATH() . 'Config/Const-local.php');
     Kit::update(self::$constantMapping, $constantMapping);
     foreach (self::$constantMapping as $name => $value) {
         if (FALSE === defined($name)) {
             define($name, $value);
         }
     }
 }
Esempio n. 8
0
 public static final function isLogin($user_type_list)
 {
     $result = (TRUE === isset(self::$currentUser) and TRUE === self::$currentUser instanceof UserEntity);
     if (FALSE === $result or 0 === Kit::len($user_type_list)) {
         return $result;
     }
     foreach ($user_type_list as $user_type) {
         if ($user_type === self::$currentUser->getType()) {
             return TRUE;
         }
     }
     return FALSE;
 }
Esempio n. 9
0
 /**
  * @param string $APPPATH
  * @param string $RUNTIMEPATH
  * @param string $APPNAME
  */
 public static function initialize($APPPATH, $RUNTIMEPATH, $APPNAME)
 {
     $APPPATH = Kit::getRealPath($APPPATH);
     $ILEXPATH = Kit::getRealPath(__DIR__ . '/Base/');
     $RUNTIMEPATH = Kit::getRealPath($RUNTIMEPATH);
     /**
      * Loader::initialize() should be called before Constant::initialize(), 
      * because Loader::APPPATH() is called in Constant::initialize()
      */
     session_cache_expire(240);
     date_default_timezone_set('UTC');
     Loader::initialize($ILEXPATH, $APPPATH, $RUNTIMEPATH, $APPNAME);
     Constant::initialize();
     Debug::initialize();
 }
Esempio n. 10
0
 public final function __construct($id_or_string)
 {
     if (TRUE === $id_or_string instanceof MongoDBId) {
         $this->id = $id_or_string->toMongoId();
     } elseif (TRUE === $id_or_string instanceof MongoId) {
         $this->id = $id_or_string;
     } elseif (TRUE === MongoId::isValid($id_or_string)) {
         Kit::ensureString($id_or_string);
         try {
             $this->id = new MongoId($id_or_string);
         } catch (Exception $e) {
             throw new UserException("Invalid \$string({$id_or_string}) to construct a MongoId.");
         }
     } else {
         throw new UserException('Invalid $id_or_string.', $id_or_string);
     }
 }
Esempio n. 11
0
 /**
  * @param string    $message
  * @param mixed     $detail
  * @param Exception $previous
  * @param int       $code
  */
 public final function __construct($variable, $expected_type_list)
 {
     if (FALSE === is_array($expected_type_list)) {
         $expected_type_list = [$expected_type_list];
     }
     foreach ($expected_type_list as $expected_type) {
         if (FALSE === Kit::isValidType($expected_type)) {
             throw new UserException('Invalid type.', $expected_type);
         }
     }
     $this->variable = $variable;
     $variable_type = $this->variableType = Kit::type($variable, TRUE);
     $this->expectedTypeList = $expected_type_list;
     $expected_type_string = Kit::join(' or ', $expected_type_list);
     $message = "Invalid type({$variable_type}), {$expected_type_string} is expected.";
     $detail = ['variable' => $variable, 'variable_type' => $variable_type, 'expected_type_list' => $expected_type_list];
     parent::__construct($message, $detail);
 }
Esempio n. 12
0
 public final function shuffle()
 {
     return $this->setEntityList(Kit::shuffled($this->getEntityList()));
 }
Esempio n. 13
0
<?php

namespace Ilex\Test;

ini_set('error_reporting', E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
ini_set('display_errors', 1);
ini_set('html_errors', 0);
session_cache_expire(240);
require_once __DIR__ . '/../../../autoload.php';
require_once __DIR__ . '/ValidatorTester.php';
use Exception;
use Ilex\Tester;
use Ilex\Core\Debug;
use Ilex\Lib\Kit;
use Ilex\Test\ValidatorTester as VT;
try {
    Tester::boot(__DIR__ . '/app', __DIR__ . '/runtime', 'app');
    // VT::test('countCollection');
    // echo 'Validator Test Passed.' . PHP_EOL;
} catch (Exception $e) {
    echo Kit::j(Debug::extractException($e));
}
Esempio n. 14
0
 /**
  * @return string
  */
 public final function __toString()
 {
     return Kit::j($this->data);
 }
Esempio n. 15
0
 /**
  * @param string $name
  * @param array  $data
  * @return boolean
  */
 public static final function merge($name, $data)
 {
     if (TRUE === Kit::in($name, ['get', 'post', 'input'])) {
         $name .= 'Data';
         self::${$name}->merge($data);
         /* 
         CAUTION: 
             The + operator returns the right-hand array appended to the left-hand array;
             for keys that exist in both arrays, the elements from the left-hand array will be used,
             and the matching elements from the right-hand array will be ignored.
         
             array_merge — Merge one or more arrays
             array array_merge ( array $array1 [, array $... ] )
             Merges the elements of one or more arrays together so that the values of one
             are appended to the end of the previous one. It returns the resulting array.
             If the input arrays have the same string keys, then the later value for that key will 
             overwrite the previous one. If, however, the arrays contain numeric keys,
             the later value will not overwrite the original value, but will be appended.
             Values in the input array with numeric keys will be renumbered with
             incrementing keys starting from zero in the result array.
         */
         if ($name !== 'input') {
             self::$inputData->merge(self::get());
             self::$inputData->merge(self::post());
         }
         return TRUE;
     } else {
         throw new UserException("Invalid \$name({$name}).");
     }
 }
Esempio n. 16
0
 private final function has($path)
 {
     // Kit::ensureType($path, [ Kit::TYPE_STRING, Kit::TYPE_LIST ]); // @CAUTION
     // Kit::ensureType($path, [ Kit::TYPE_STRING, Kit::TYPE_ARRAY ]);
     Kit::ensureString($path);
     // Kit::ensureDict($this->document); // @CAUTION
     // Kit::ensureArray($this->document);
     // if (TRUE === Kit::isString($path)) {
     return FALSE === is_null($this->document[$path]);
     // } else throw new UserException('Can not support list-type $path yet.', $path);
 }
Esempio n. 17
0
 public final function passwordIs($password)
 {
     Kit::ensureString($password);
     return $this->infoFieldIs('Password', $password);
 }
Esempio n. 18
0
 private final function createEntityWithDocument($document)
 {
     // Kit::ensureDict($document); // @CAUTION
     Kit::ensureArray($document);
     if (FALSE === isset($document['_id']) or FALSE === $document['_id'] instanceof MongoId) {
         throw new UserException('_id is not set or proper in $document.', $document);
     }
     $document['_id'] = new MongoDBId($document['_id']);
     $entity_class_name = $this->entityClassName;
     Kit::ensureString($entity_class_name);
     return new $entity_class_name($this->collectionName, $this->entityPath, TRUE, $document);
 }
Esempio n. 19
0
 /**
  * eg. 'Collection/Content/ResourceCollection' => 'Content/Resource'
  * eg. 'Entity/Content/ResourceEntity'         => 'Content/Resource'
  */
 public static final function getModelPath($model_class_name, $delimiter = '\\')
 {
     Kit::ensureString($model_class_name);
     Kit::ensureString($delimiter);
     $handler_prefix = self::getHandlerPrefixFromPath($model_class_name);
     // 'Resource'
     $word_list = Kit::split($delimiter, $model_class_name);
     while (Kit::len($word_list) > 0 and 'Model' !== $word_list[0]) {
         $word_list = Kit::slice($word_list, 1);
     }
     $word_list = Kit::slice($word_list, 2);
     // [ 'Content', 'ResourceCollection' ]
     Kit::popList($word_list);
     // [ 'Content' ]
     $word_list[] = $handler_prefix;
     // [ 'Content', 'Resource' ]
     return Kit::join('/', $word_list);
     // 'Content/Resource'
 }
Esempio n. 20
0
 /**
  * @param int     $execution_id
  * @param array   $execution_record
  * @param int     $status_code
  * @param boolean $close_cgi_only
  */
 private final function respond($execution_id, $execution_record, $status_code, $close_cgi_only = FALSE)
 {
     if (FALSE === $close_cgi_only) {
         $this->result['database'] = [];
         if (2 !== $this->getCode()) {
             $this->result['database']['rollbacked'] = MDBC::rollback();
         } else {
             $this->result['database']['rollbacked'] = FALSE;
         }
         $this->result['database']['changed'] = MDBC::isChanged();
         Debug::updateExecutionRecord($execution_id, $execution_record);
         Debug::popExecutionId($execution_id);
     }
     if (FALSE === is_null($error = error_get_last()) and TRUE === Debug::isErrorCared($error)) {
         Debug::handleFatalError($error);
     }
     header('Content-Type : application/json', TRUE, $status_code);
     if (FALSE === Debug::isProduction()) {
         $this->result['monitor'] = Debug::getMonitor();
         $this->result += Debug::getDebugInfo();
         $this->result += ['size' => sprintf('%.2fKB', Kit::len(json_encode($this->result)) / 1024)];
         if (TRUE === is_null($this->result['mainException'])) {
             unset($this->result['mainException']);
         }
         if (TRUE === is_null($this->result['monitor'])) {
             unset($this->result['monitor']);
         }
     } else {
         unset($this->result['mainException']);
         unset($this->result['monitor']);
         unset($this->result['database']);
         unset($this->result['process']);
     }
     Http::json($this->result);
     if (TRUE === $close_cgi_only) {
         fastcgi_finish_request();
         // DO NOT exit in order to run the subsequent scripts.
     } else {
         exit;
     }
 }
Esempio n. 21
0
 /**
  * Remove documents from this collection.
  * @param array   $criterion Associative array with fields to match.
  * @param boolean $multiple  If set to TRUE, all documents matching $criterion will be removed.
  * @return array Returns an array containing the status of the removal.
  * @throws MongoCursorException        if the "w" option is set and the write fails.
  * @throws MongoCursorTimeoutException if the "w" option is set to a value greater than one
  *                                     and the operation takes longer than MongoCursor::$timeout
  *                                     milliseconds to complete.
  *                                     This does not kill the operation on the server,
  *                                     it is a client-side timeout.
  *                                     The operation in MongoCollection::$wtimeout
  *                                     is milliseconds.
  */
 private final function mongoRemove($criterion, $multiple = TRUE)
 {
     $this->ensureInitialized();
     // Kit::ensureDict($criterion); // @CAUTION
     Kit::ensureArray($criterion);
     Kit::ensureBoolean($multiple);
     $options = ['w' => 1, 'justOne' => FALSE === $multiple];
     $status = $this->collection->remove($criterion, $options);
     self::$isChanged = TRUE;
     return $status;
 }
Esempio n. 22
0
 /**
  * Extracts args and handles the request,
  * by choosing the appropriate handler,
  * and calling the appropriate method
  * if $description CAN fit $this->uri.
  * @param string      $description eg. '/project/(num)', '/(num)', '/', '/user/(any)', '(all)'
  * @param mixed       $handler     eg. 'Project',        $this,    an anonymous function
  * @param string|NULL $function    eg. 'view'
  * @param boolean     $is_time_consuming
  * @return boolean
  */
 private final function fitGeneral($description, $handler, $function = NULL, $is_time_consuming = FALSE)
 {
     /**
      * eg. $description : '/project/(id:num)' => '/project/([0-9]+?)'
      *     $this->uri   : '/project/12'
      *     $match_list  : ['/project/12', '12']
      */
     $pattern = $this->getPattern($description);
     // It will attempt to match the whole $this->uri string.
     $uri = rtrim($this->uri, '/');
     // $this->uri contains no GET args.
     if (1 === preg_match($pattern, $uri, $match_list)) {
         preg_match_all('@([^:\\(\\)]+):([^:\\(\\)]+)@', $description, $m, PREG_SET_ORDER);
         $mapping = [];
         foreach ($m as $value) {
             $mapping[$value[1]] = $value[2];
             // 'id' => 'num'
         }
         $Input = Loader::loadInput();
         foreach ($match_list as $key => $value) {
             // [0 => 12, 'id' => 12]
             if (TRUE === Kit::isInt($key)) {
                 unset($match_list[$key]);
             } elseif ('num' === $mapping[$key]) {
                 $Input->setInput($key, intval($value));
             } else {
                 $Input->setInput($key, $value);
             }
         }
         if (TRUE === Kit::isString($handler) or FALSE === $handler instanceof \Closure) {
             // $handler is a string or IS NOT an anonymous function, i.e., an instance.
             Kit::ensureString($function);
             $this->end(call_user_func_array([TRUE === Kit::isString($handler) ? Loader::loadService($handler) : $handler, $function], [$is_time_consuming]));
         } elseif (TRUE === is_callable($handler)) {
             // $handler is an anonymous function.
             $this->end(call_user_func_array($handler, [$is_time_consuming]));
         }
         // CAN FIT!
         return TRUE;
     } else {
         // CAN NOT FIT!
         return FALSE;
     }
 }
Esempio n. 23
0
 private final function getInitiatorNameAndType($method_name, $declaring_class)
 {
     $backtrace = Kit::columns(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 20), ['class', 'function'], FALSE);
     $initiator_name = NULL;
     foreach ($backtrace as $record) {
         if (TRUE === is_null($record['class']) or TRUE === Kit::in($record['class'], ['Ilex\\Base\\Base', 'Ilex\\Base\\Controller\\Service\\BaseService', 'Ilex\\Base\\Model\\BaseModel'])) {
             continue;
         }
         if ($method_name !== $record['function']) {
             $initiator_name = $record['class'];
             break;
         }
     }
     if (TRUE === is_null($initiator_name)) {
         $result = [$initiator_name, self::T_OTHER];
     } else {
         $initiator = new ReflectionClass($initiator_name);
         $declaring_class_name = $declaring_class->getName();
         if ($initiator_name === $declaring_class_name) {
             $result = [$initiator_name, self::T_SELF];
         } elseif (TRUE === $initiator->isSubclassOf($declaring_class_name)) {
             $result = [$initiator_name, self::T_DESCENDANT];
         } else {
             $result = [$initiator_name, self::T_OTHER];
         }
     }
     // var_dump([$method_name, $declaring_class, $initiator_name]);
     // var_dump($result);
     // var_dump($backtrace);
     return $result;
 }
Esempio n. 24
0
 public final function limit($limit = NULL)
 {
     if (TRUE === is_null($limit)) {
         return $this->limit;
     }
     Kit::ensureInt($limit);
     $this->limit = $limit;
     return $this;
 }
Esempio n. 25
0
 /**
  * Converts time to date string and returns it.
  * @param int|NULL $time
  * @param string   $format
  * @return string
  */
 public static final function time($time = NULL, $format = 'Y-m-d H:i:s')
 {
     if (TRUE === Kit::isNULL($time)) {
         $time = time();
     }
     return date($format, $time);
 }
Esempio n. 26
0
 public static final function daysAfterNow($days)
 {
     Kit::ensureInt($days);
     return new MongoDate((new DateTime())->add(new DateInterval("P{$days}D"))->getTimestamp());
 }