public function importValue($value)
 {
     if ($value) {
         Assert::isEqual(get_class($value), $this->className);
     } else {
         return parent::importValue(null);
     }
     return $this->import([$this->getName() => $value->getId()]);
 }
Example #2
0
 /**
  * @return Form
  **/
 public function fillOwn($object, &$result)
 {
     Assert::isInstance($result, Form::class);
     foreach ($this->getFormMapping() as $primitive) {
         if ($primitive instanceof PrimitiveForm && $result->exists($primitive->getName()) && $primitive->isComposite()) {
             Assert::isEqual($primitive->getProto(), $result->get($primitive->getName())->getProto());
             continue;
         }
         $result->add($primitive);
     }
     $result = parent::fillOwn($object, $result);
     $result->setProto($this->proto);
     return $result;
 }
Example #3
0
 public static function copyProperties($source, $destination)
 {
     Assert::isEqual(get_class($source), get_class($destination));
     $class = new \ReflectionClass($source);
     foreach ($class->getProperties() as $property) {
         $name = ucfirst($property->getName());
         $getter = 'get' . $name;
         $setter = 'set' . $name;
         if ($class->hasMethod($getter) && $class->hasMethod($setter)) {
             $sourceValue = $source->{$getter}();
             if ($sourceValue === null) {
                 $setMethood = $class->getMethod($setter);
                 $parameterList = $setMethood->getParameters();
                 $firstParameter = $parameterList[0];
                 if ($firstParameter->allowsNull()) {
                     $destination->{$setter}($sourceValue);
                 }
             } else {
                 $destination->{$setter}($sourceValue);
             }
         }
     }
 }
Example #4
0
 public static function getCovariance(array $list1, array $list2)
 {
     $list1Size = count($list1);
     $list2Size = count($list2);
     Assert::isEqual($list1Size, $list2Size, 'Array sizes should be equals!');
     $list1AverageValue = self::getAverage($list1);
     $list2AverageValue = self::getAverage($list2);
     $tempSum = 0;
     for ($i = 0; $i < $list1Size; $i++) {
         $elt1Dev = self::getMeanDeviation($list1[$i], $list1AverageValue);
         $elt2Dev = self::getMeanDeviation($list2[$i], $list2AverageValue);
         $tempSum += $elt1Dev * $elt2Dev;
     }
     return $tempSum / ($list1Size - 1);
 }
Example #5
0
 public final function validateList($objectsList, $formsList, $previousObjectsList = null)
 {
     Assert::isEqual(count($objectsList), count($formsList));
     reset($formsList);
     if ($previousObjectsList) {
         Assert::isEqual(count($objectsList), count($previousObjectsList));
         reset($previousObjectsList);
     }
     $result = true;
     $previousObject = null;
     foreach ($objectsList as $object) {
         $form = current($formsList);
         next($formsList);
         if ($previousObjectsList) {
             $previousObject = current($previousObjectsList);
             next($previousObjectsList);
         }
         if (!$this->validate($object, $form, $previousObject)) {
             $result = false;
         }
     }
     return $result;
 }
 protected function call($method, DTOMessage $request, $resultClass)
 {
     $requestDto = $request->makeDto();
     Assert::isInstance($requestDto, DTOClass::class);
     if (defined('__LOCAL_DEBUG__') && !defined('SIMPLE_TEST')) {
         // self-validation
         $form = ObjectToFormConverter::create($request->entityProto())->make($request);
         Assert::isTrue(!$form->getErrors() && $request->entityProto()->validate($request, $form), Assert::dumpArgument($request));
     }
     try {
         try {
             $resultDto = $this->getSoapClient()->{$method}($requestDto);
         } catch (BaseException $e) {
             if (get_class($e) == BaseException::class) {
                 throw new SoapFault('Server', get_class($e) . ': ' . $e->getMessage());
             } else {
                 $this->logCall();
                 throw $e;
             }
         }
     } catch (SoapFault $e) {
         $this->logCall();
         throw self::convertSoapFault($e);
     }
     $this->logCall();
     if (!$resultClass) {
         Assert::isNull($resultDto);
         $result = null;
     } else {
         Assert::isInstance($resultDto, DTOClass::class);
         Assert::isEqual($resultDto->entityProto()->className(), $resultClass);
         $form = DTOToFormImporter::create($resultDto->entityProto())->make($resultDto);
         Assert::isTrue(!$form->getErrors(), Assert::dumpArgument($resultDto));
         $result = $resultDto->makeObject($form);
         Assert::isInstance($result, DTOMessage::class);
         Assert::isEqual(get_class($result), $resultClass);
         Assert::isTrue($result->entityProto()->validate($result, $form), Assert::dumpArgument($result));
     }
     return $result;
 }
Example #7
0
 public static function makeUniqueLatinName($originalName)
 {
     $extension = substr($originalName, strrpos($originalName, '.'));
     Assert::isEqual(preg_match('/\\.[^0-9a-zA-Z]/', $extension), 0, 'I don\'t know how to work with this extension: ' . $extension);
     return time() . '_' . uniqid() . $extension;
 }
Example #8
0
 public static function setChars($chars)
 {
     self::check($chars);
     Assert::isEqual(mb_strlen($chars), 62, 'Wrong length');
     self::$chars = $chars;
 }
Example #9
0
 private function __construct($name)
 {
     $units = self::getUnits();
     if (!isset($units[$name])) {
         throw new WrongArgumentException("know nothing about unit '{$name}'");
     }
     if (!$units[$name]) {
         throw new UnimplementedFeatureException('need for complex logic, see manual');
     }
     $this->name = $name;
     $this->months = $units[$name][0];
     $this->days = $units[$name][1];
     $this->seconds = $units[$name][2];
     $notNulls = 0;
     if ($this->months > 0) {
         ++$notNulls;
     }
     if ($this->days > 0) {
         ++$notNulls;
     }
     if ($this->seconds > 0) {
         ++$notNulls;
     }
     Assert::isEqual($notNulls, 1, "broken unit '{$name}'");
 }
Example #10
0
 /**
  * @return MetaConfiguration
  **/
 public function checkIntegrity()
 {
     $out = $this->getOutput()->newLine()->infoLine('Checking sanity of generated files: ')->newLine();
     $out->info("\t");
     $formErrors = [];
     foreach ($this->classes as $name => $class) {
         if (!($class->getPattern() instanceof SpookedClassPattern || $class->getPattern() instanceof SpookedEnumerationPattern || $class->getPattern() instanceof SpookedEnumPattern || $class->getPattern() instanceof SpookedRegistryPattern || $class->getPattern() instanceof InternalClassPattern) && class_exists(MetaClassNameBuilder::getClassOfMetaClass($class, true))) {
             $out->info($name, true);
             $className = MetaClassNameBuilder::getClassOfMetaClass($class);
             $info = new \ReflectionClass($className);
             $this->checkClassSanity($class, $info);
             if ($info->implementsInterface(Prototyped::class)) {
                 $this->checkClassSanity($class, new \ReflectionClass($class->getProtoClass()));
             }
             if ($info->implementsInterface(DAOConnected::class)) {
                 $this->checkClassSanity($class, new \ReflectionClass($class->getDaoClass()));
             }
             foreach ($class->getInterfaces() as $interface) {
                 Assert::isTrue($info->implementsInterface($interface), 'class ' . $class->getName() . ' expected to implement interface ' . $interface);
             }
             // special handling for Enumeration instances
             if ($class->getPattern() instanceof EnumerationClassPattern || $class->getPattern() instanceof EnumClassPattern || $class->getPattern() instanceof RegistryClassPattern) {
                 $object = new $className(call_user_func([$className, 'getAnyId']));
                 Assert::isTrue(unserialize(serialize($object)) == $object);
                 $out->info(', ');
                 if ($this->checkEnumerationRefIntegrity) {
                     if ($object instanceof Enumeration || $object instanceof Enum || $object instanceof Registry) {
                         $this->checkEnumerationReferentialIntegrity($object, $class->getTableName());
                     }
                 }
                 continue;
             }
             if ($class->getPattern() instanceof AbstractClassPattern) {
                 $out->info(', ');
                 continue;
             }
             /** @var Prototyped $object */
             $object = new $className();
             $proto = $object->proto();
             $form = $proto->makeForm();
             foreach ($class->getProperties() as $name => $property) {
                 Assert::isTrue($property->toLightProperty($class) == $proto->getPropertyByName($name), 'defined property does not match autogenerated one - ' . $class->getName() . '::' . $property->getName());
             }
             if (!$object instanceof DAOConnected) {
                 $out->info(', ');
                 continue;
             }
             $dao = $object->dao();
             Assert::isEqual($dao->getIdName(), $class->getIdentifier()->getColumnName(), 'identifier name mismatch in ' . $class->getName() . ' class');
             try {
                 DBPool::getByDao($dao);
             } catch (MissingElementException $e) {
                 // skipping
                 $out->info(', ');
                 continue;
             }
             $query = Criteria::create($dao)->setLimit(1)->add(Expression::notNull($class->getIdentifier()->getName()))->addOrder($class->getIdentifier()->getName())->toSelectQuery();
             $out->warning(' (' . $query->getFieldsCount() . '/' . $query->getTablesCount() . '/');
             $clone = clone $object;
             if (serialize($clone) == serialize($object)) {
                 $out->info('C', true);
             } else {
                 $out->error('C', true);
             }
             $out->warning('/');
             try {
                 $object = $dao->getByQuery($query);
                 $form = $object->proto()->makeForm();
                 FormUtils::object2form($object, $form);
                 if ($errors = $form->getErrors()) {
                     $formErrors[$class->getName()] = $errors;
                     $out->error('F', true);
                 } else {
                     $out->info('F', true);
                 }
             } catch (ObjectNotFoundException $e) {
                 $out->warning('F');
             }
             $out->warning('/');
             if (Criteria::create($dao)->setFetchStrategy(FetchStrategy::cascade())->toSelectQuery() == $dao->makeSelectHead()) {
                 $out->info('H', true);
             } else {
                 $out->error('H', true);
             }
             $out->warning('/');
             // cloning once again
             $clone = clone $object;
             FormUtils::object2form($object, $form);
             FormUtils::form2object($form, $object);
             if ($object != $clone) {
                 $out->error('T', true);
             } else {
                 $out->info('T', true);
             }
             $out->warning(')')->info(', ');
         }
     }
     $out->infoLine('done.');
     if ($formErrors) {
         $out->newLine()->errorLine('Errors found:')->newLine();
         foreach ($formErrors as $class => $errors) {
             $out->errorLine("\t" . $class . ':', true);
             foreach ($errors as $name => $error) {
                 $out->errorLine("\t\t" . $name . ' - ' . ($error == Form::WRONG ? ' wrong' : ' missing'));
             }
             $out->newLine();
         }
     }
     return $this;
 }
Example #11
0
 public static function hex2Binary($hex)
 {
     $length = strlen($hex);
     Assert::isEqual($length % 2, 0);
     $out = null;
     for ($i = 0; $i < $length; $i += 2) {
         $out .= pack('C', hexdec(substr($hex, $i, 2)));
     }
     return $out;
 }
Example #12
0
 public function endPrefetch(array $objectList)
 {
     if (!$this->depth) {
         throw new WrongStateException('prefetch mode is already off');
     }
     foreach ($this->storage[$this->depth] as $setter => $innerList) {
         Assert::isEqual(count($objectList), count($innerList) + array_sum($this->skipList[$this->depth]));
         $ids = [];
         foreach ($innerList as $inner) {
             if ($inner) {
                 $ids[] = $inner->getId();
             }
         }
         // finding first available inner object
         foreach ($innerList as $inner) {
             if ($inner) {
                 break;
             }
         }
         if (!$inner) {
             continue;
         }
         // put yet unmapped objects into dao's identityMap
         $inner->dao()->getListByIds($ids);
         $skippedMap = $this->skipList[$this->depth];
         $i = $j = 0;
         foreach ($objectList as $object) {
             $objectId = $object->getId();
             if (isset($skippedMap[$objectId])) {
                 if ($skippedMap[$objectId] == 1) {
                     unset($skippedMap[$objectId]);
                 } else {
                     --$skippedMap[$objectId];
                 }
                 ++$j;
                 continue;
             }
             if ($innerList[$i]) {
                 try {
                     // avoid dao "caching" here
                     // because of possible breakage
                     // in overriden properties
                     $object->{$setter}($innerList[$i]->dao()->getById($innerList[$i]->getId()));
                 } catch (ObjectNotFoundException $e) {
                     throw new WrongStateException('possible corruption found: ' . $e->getMessage());
                 }
             }
             ++$i;
         }
         Assert::isEqual($i, count($objectList) - $j);
     }
     unset($this->skipList[$this->depth], $this->storage[$this->depth--]);
     return $objectList;
 }
Example #13
0
 private function assertSavePointName($savepointName)
 {
     Assert::isEqual(1, preg_match('~^[A-Za-z][A-Za-z0-9]*$~iu', $savepointName));
 }
 public function store($localFile, $desiredName)
 {
     if (!is_readable($localFile) || !is_file($localFile)) {
         throw new WrongArgumentException('Wrong file: ' . $localFile);
     }
     if (preg_match($this->unAllowedName, $desiredName)) {
         throw new WrongArgumentException('Wrong desired name: ' . $desiredName);
     }
     $origDesiredName = $desiredName;
     $desiredNameFull = $this->getPath($desiredName, true);
     if ($this->exists($desiredName) && $this->resolveNameConflicts) {
         $desiredName = $this->generateName($desiredName);
         $desiredNameFull = $this->getPath($desiredName, true);
     }
     if ($this->exists($desiredName)) {
         throw new Exception('File name conflict:' . $origDesiredName . '"');
     }
     $context = $this->context;
     $upload = function () use($localFile, $desiredNameFull, $desiredName, $context) {
         $src = fopen($localFile, 'rb');
         $dst = fopen($desiredNameFull, 'wb', false, $context);
         Assert::isEqual(stream_copy_to_stream($src, $dst), filesize($localFile), 'Bytes copied mismatch');
         $this->closeHandles($src, $dst);
         if (!$this->exists($desiredName)) {
             throw new Exception('Could not find file after upload"' . $desiredName . '", linkId: ' . $this->linkId);
         }
     };
     $this->tryToDo($upload, 'Couldn`t store file ' . $origDesiredName . ', reason: %s');
     return $desiredName;
 }