Example #1
0
    protected function setUp()
    {
        parent::setUp();
        if (!class_exists('Propel\\Bundle\\PropelBundle\\Tests\\Fixtures\\DataFixtures\\Loader\\CoolBook')) {
            $schema = <<<XML
<database name="default" package="vendor.bundles.Propel.Bundle.PropelBundle.Tests.Fixtures.DataFixtures.Loader" namespace="Propel\\Bundle\\PropelBundle\\Tests\\Fixtures\\DataFixtures\\Loader" defaultIdMethod="native">
    <table name="cool_book">
        <column name="id" type="integer" primaryKey="true" />
        <column name="name" type="varchar" size="255" />
        <column name="description" type="varchar" />
        <column name="author_id" type="integer" required="false" defaultValue="null" />
        <column name="complementary_infos" required="false" type="object" description="An object column" />

        <foreign-key foreignTable="cool_book_author" onDelete="CASCADE" onUpdate="CASCADE">
            <reference local="author_id" foreign="id" />
        </foreign-key>
    </table>

    <table name="cool_book_author">
        <column name="id" type="integer" primaryKey="true" />
        <column name="name" type="varchar" size="255" />
    </table>
</database>
XML;
            QuickBuilder::buildSchema($schema);
        }
        $this->con = Propel::getServiceContainer()->getConnection('default');
        $this->con->beginTransaction();
    }
Example #2
0
 public static function exec($callable, $arrArgs, $action, $creator = null, $related = null, PropelPDO $con)
 {
     if (!$con->beginTransaction()) {
         throw new Exception('Could not begin transaction');
     }
     try {
         $resIsArray = $res = false;
         $res = $return = call_user_func_array($callable, $arrArgs);
         $resIsArray = is_array($res);
         if ($resIsArray) {
             if (isset($res[self::ARR_RESULT_RETURN_KEY])) {
                 $return = $res[self::ARR_RESULT_RETURN_KEY];
                 unset($res[self::ARR_RESULT_RETURN_KEY]);
             }
             if (!$related && isset($res[self::ARR_RELATED_RETURN_KEY])) {
                 $related = $res[self::ARR_RELATED_RETURN_KEY];
                 unset($res[self::ARR_RELATED_RETURN_KEY]);
             }
         }
         self::insert($action, self::TYPE_SUCCESS, $creator, $related, $resIsArray ? $res : [$res], null, $con);
         if (!$con->commit()) {
             throw new Exception('Could not commit transaction');
         }
         return $return;
     } catch (Exception $e) {
         $con->rollBack();
         $activity = self::insert($action, self::TYPE_FAILURE, $creator, $related, $resIsArray ? $res : [$res], $e, $con);
         self::$_ActivityExceptions[] = $activity->toArray();
         throw $e;
     }
 }
 /**
  * Update all ancestor entries to reflect changes on this instance.
  *
  * @param \PropelPDO $con
  *
  * @return \Propel\Bundle\PropelAclBundle\Model\Acl\ObjectIdentity $this
  */
 protected function updateAncestorsTree(\PropelPDO $con = null)
 {
     $con->beginTransaction();
     $oldAncestors = ObjectIdentityQuery::create()->findAncestors($this, $con);
     $children = ObjectIdentityQuery::create()->findGrandChildren($this, $con);
     $children->append($this);
     if (count($oldAncestors)) {
         foreach ($children as $eachChild) {
             /*
              * Delete only those entries, that are ancestors based on the parent relation.
              * Ancestors of grand children up to the current node will be kept.
              */
             $query = ObjectIdentityAncestorQuery::create()->filterByObjectIdentityId($eachChild->getId())->filterByObjectIdentityRelatedByAncestorId($oldAncestors, \Criteria::IN);
             if ($eachChild->getId() !== $this->getId()) {
                 $query->filterByAncestorId(array($eachChild->getId(), $this->getId()), \Criteria::NOT_IN);
             } else {
                 $query->filterByAncestorId($this->getId(), \Criteria::NOT_EQUAL);
             }
             $query->delete($con);
         }
     }
     // This is the new parent object identity!
     $parent = $this->getObjectIdentityRelatedByParentObjectIdentityId($con);
     if (null !== $parent) {
         $newAncestors = ObjectIdentityQuery::create()->findAncestors($parent, $con);
         $newAncestors->append($parent);
         foreach ($newAncestors as $eachAncestor) {
             // This collection contains the current object identity!
             foreach ($children as $eachChild) {
                 $ancestor = ObjectIdentityAncestorQuery::create()->filterByObjectIdentityId($eachChild->getId())->filterByAncestorId($eachAncestor->getId())->findOneOrCreate($con);
                 // If the entry already exists, next please.
                 if (!$ancestor->isNew()) {
                     continue;
                 }
                 if ($eachChild->getId() === $this->getId()) {
                     // Do not save() here, as it would result in an infinite recursion loop!
                     $this->addObjectIdentityAncestorRelatedByObjectIdentityId($ancestor);
                 } else {
                     // Save the new ancestor to avoid integrity constraint violation.
                     $ancestor->save($con);
                     $eachChild->addObjectIdentityAncestorRelatedByObjectIdentityId($ancestor)->save($con);
                 }
             }
         }
     }
     $con->commit();
     return $this;
 }
 protected function doSave(PropelPDO $con)
 {
     try {
         $con->beginTransaction();
         if ($this->countCourseSubjectStudentMarks() == 0) {
             for ($i = 1; $i <= $this->getCourseSubject()->getCareerSubjectSchoolYear()->getConfiguration()->getCourseMarks(); $i++) {
                 $course_subject_student_mark = new CourseSubjectStudentMark();
                 $course_subject_student_mark->setCourseSubjectStudent($this);
                 $course_subject_student_mark->setMarkNumber($i);
                 $last_period_close = $this->getCourseSubject()->getCourse()->getCurrentPeriod() - 1;
                 if ($i <= $last_period_close) {
                     $course_subject_student_mark->setIsClosed(true);
                     // se pone la nota como cerrada
                 }
                 $course_subject_student_mark->save($con);
             }
         }
         parent::doSave($con);
         $con->commit();
     } catch (PropelException $e) {
         $con->rollBack();
     }
 }
Example #5
0
 private function importTransactions(Status $logger, array $clockingTypeMap, array $bookingTypesByIdentifier, array $usersByName, array $clockingDataByOldID, PDO $source, PropelPDO $dest)
 {
     if (!$dest->beginTransaction()) {
         throw new Exception('Could not start transaction.');
     }
     try {
         $statement = $source->query('SELECT * FROM ext_clockings_transactions');
         $logger->info($statement->rowCount());
         $oldTransactions = $statement->fetchAll(PDO::FETCH_ASSOC);
         $statement->closeCursor();
         $statement = null;
         foreach ($oldTransactions as $rowIndex => $oldTransaction) {
             $authUserName = $oldTransaction['creator'];
             $userName = $oldTransaction['username'];
             if (empty($usersByName[$userName])) {
                 $logger->info('Transaction #' . $oldTransaction['ID'] . ' references unknown user "' . $userName . '".');
                 continue;
             }
             $transaction = new Transaction();
             $dataItems = $this->getTransactionClockingDataItems($logger, $oldTransaction, $clockingDataByOldID, $source);
             $clockings = $this->getClockings($dataItems);
             if (empty($clockings)) {
                 $date = (int) $oldTransaction['date'];
                 $start = $date;
                 $end = $date;
             } else {
                 list($start, $end) = $this->getClockingRange($clockings);
                 foreach ($clockings as $clocking) {
                     $transactionClocking = new TransactionClocking();
                     $transaction->addTransactionClocking($transactionClocking->setTransaction($transaction)->setClocking($clocking));
                 }
             }
             // Check transaction / booking consistency
             $logger->start('Checking consistency of new transactions & bookings');
             $worktimeId = $bookingTypesByIdentifier['regular']->getId();
             $flexitimeId = $bookingTypesByIdentifier['flexitime']->getId();
             $overtimeId = $bookingTypesByIdentifier['overtime']->getId();
             $vacationId = $bookingTypesByIdentifier['vacation']->getId();
             $sickLeaveId = $bookingTypesByIdentifier['sick_leave']->getId();
             $educationId = $bookingTypesByIdentifier['education']->getId();
             $actualTimes = array($worktimeId => 0.0, $flexitimeId => 0.0, -$flexitimeId => 0.0, $overtimeId => 0.0, $vacationId => 0.0, $sickLeaveId => 0.0, $educationId => 0.0);
             //$actualDenied    = 0;
             $bookings = $this->createBookings($logger, $dataItems, $bookingTypesByIdentifier, $dest);
             foreach ($bookings as $booking) {
                 $bookingTypeId = $booking->getBookingTypeId();
                 if (!isset($actualTimes[$bookingTypeId])) {
                     throw new Exception('Unknown booking type #' . $bookingTypeId . ' specified for booking #' . $booking->getId() . '.');
                 }
                 $value = $booking->getValue();
                 if ($bookingTypeId === $flexitimeId and $value < 0) {
                     $actualTimes[-$bookingTypeId] += $value;
                 } else {
                     $actualTimes[$bookingTypeId] += $value;
                 }
                 $transaction->addBooking($booking);
             }
             $transaction->setUserRelatedByCreatorId($usersByName[$authUserName])->setUserRelatedByUserId($usersByName[$userName])->setStart($start)->setEnd($end)->setCreationdate((int) $oldTransaction['creationdate'])->setComment($oldTransaction['comment'])->setDeleted($oldTransaction['visibility'])->save($dest);
             // Cross-check times of bookings and transaction
             #$this->failTimeDelta($logger, $oldTransaction, 'time', $actualTimes[$worktimeId] + $actualTimes[$flexitimeId] + $actualTimes[$overtimeId], $bookings);
             #$this->failTimeDelta($logger, $oldTransaction, 'time', $actualTimes[$worktimeId], $bookings);
             $this->failTimeDelta($logger, $oldTransaction, 'flexitime', $actualTimes[$flexitimeId] + $actualTimes[-$flexitimeId], $bookings);
             $this->failTimeDelta($logger, $oldTransaction, 'overtime', $actualTimes[$overtimeId], $bookings);
             //$this->failTimeDelta($logger, $oldTransaction, 'denied', $actualDenied, $bookings);
             $logger->done();
         }
     } catch (Exception $e) {
         $dest->rollBack();
         throw $e;
     }
     if (!$dest->commit()) {
         throw new Exception('Could not commit transaction.');
     }
 }
 public function delete(PropelPDO $con = null)
 {
     $con->beginTransaction();
     try {
         TestableAggregateCommentQuery::create()->filterByPrimaryKey($this->getPrimaryKey())->delete($con);
         $con->commit();
         $this->setDeleted(true);
     } catch (PropelException $e) {
         $con->rollBack();
         throw $e;
     }
 }
Example #7
0
 /**
  * Do Explain Plan for query object or query string
  *
  * @param PropelPDO $con propel connection
  * @param ModelCriteria|string $query query the criteria or the query string
  * @throws PropelException
  * @return PDOStatement A PDO statement executed using the connection, ready to be fetched
  */
 public function doExplainPlan(PropelPDO $con, $query)
 {
     $con->beginTransaction();
     if ($query instanceof ModelCriteria) {
         $params = array();
         $dbMap = Propel::getDatabaseMap($query->getDbName());
         $sql = BasePeer::createSelectSql($query, $params);
     } else {
         $sql = $query;
     }
     // unique id for the query string
     $uniqueId = uniqid('Propel', true);
     $stmt = $con->prepare($this->getExplainPlanQuery($sql, $uniqueId));
     if ($query instanceof ModelCriteria) {
         $this->bindValues($stmt, $params, $dbMap);
     }
     $stmt->execute();
     // explain plan is save in a table, data must be commit
     $con->commit();
     $stmt = $con->prepare($this->getExplainPlanReadQuery($uniqueId));
     $stmt->execute();
     return $stmt;
 }
Example #8
0
 public function beginTransaction()
 {
     if ($this->getKalturaOption(KalturaPDO::KALTURA_ATTR_NO_TRANSACTION)) {
         return true;
     }
     return parent::beginTransaction();
 }
Example #9
0
 public static function createFromSignup($data, $refererMember, Invitation $invitation = null, PropelPDO $con)
 {
     // This functions expects this parameter to be valid!
     // E.g. the result from self::validateSignupForm()
     $now = time();
     if (!$con->beginTransaction()) {
         throw new Exception('Could not begin transaction');
     }
     try {
         $member = new Member();
         $member->setFirstName($data['firstName'])->setLastName($data['lastName'])->setEmail($data['email'])->setTitle($data['title'])->setCity($data['city'])->setCountry($data['country'])->setAge($data['age'])->setBankRecipient($data['bank_recipient'])->setIban($data['iban'])->setBic($data['bic'])->setPassword($data['password'])->setSignupDate($now);
         if ($invitation) {
             $member->setType($invitation->getType());
             if ($invitation->getFreeSignup()) {
                 $member->setPaidDate($now);
             }
             $invitation->setAcceptedDate($now);
         }
         $member->setRefererMember($refererMember, $con);
         $member->save($con);
         if ($invitation) {
             $invitation->setAcceptedMemberId($member->getId());
             $invitation->save($con);
         }
         if (!$con->commit()) {
             throw new Exception('Could not commit transaction');
         }
     } catch (Exception $e) {
         $con->rollBack();
         throw $e;
     }
     return $member;
 }
Example #10
0
 /**
  * Creates booking and transaction records from array data.
  *
  * @param User $authUser The user creating the transactions.
  * @param User $user The user to associate the transactions with.
  * @param array $bookingData An associative array mapping internal
  *     identifiers to booking record data that can be passed to
  *     {@link Booking::fromArray()}. The internal identifiers can be
  *     referenced in the transaction data.
  * @param array $bookingTypeIds An associative array with booking type IDs
  *     (in the keys) to allow.
  * @param array $transactionData An array of transaction record data
  *     suitable for {@link Transaction::fromArray()} and with two additional
  *     properties:
  *     - "Bookings" with an array of internal booking identifiers and
  *     - "Clockings" with an array of clocking IDs to link to the transaction.
  * @return array An array with two elements:
  *     1. An associative array mapping IDs of clockings for which
  *        transactions were created to themselves.
  *     2. An array of the created transactions.
  */
 private function createBookingsTransactions(User $authUser, User $user, array $bookingData, array $bookingTypeIds, array $transactionData, PropelPDO $con)
 {
     $resultClockingIds = array();
     $transactions = array();
     if (!$con->beginTransaction()) {
         throw new Exception('Could not start transaction.');
     }
     try {
         // Create bookings
         $bookingsByKey = $this->createBookings($bookingData, $bookingTypeIds, $con);
         $orphanedBookings = $bookingsByKey;
         // Create transactions and link them to clockings and new bookings
         foreach ($transactionData as $transactionItem) {
             if (!isset($transactionItem['Start'], $transactionItem['End'])) {
                 throw new Exception('Invalid transaction data (missing start and/or end date): ' . json_encode($transactionItem));
             } elseif (empty($transactionItem['Clockings'])) {
                 // This could be allowed to support artificial transactions
                 throw new Exception('Plugins created a transaction not linked to any clockings: ' . json_encode($transactionItem));
             }
             $clockingIds = $transactionItem['Clockings'];
             if (!is_array($clockingIds)) {
                 throw new Exception('"Clockings" property of transaction record must specify an array of clocking database IDs. Transaction record: ' . json_encode($transactionItem));
             }
             $transaction = new Transaction();
             $transaction->fromArray(array_intersect_key($transactionItem, array('Start' => true, 'End' => true, 'Comment' => true, 'Type' => true)));
             $transaction->setUserRelatedByCreatorId($authUser)->setUserRelatedByUserId($user)->save($con);
             if (!empty($transactionItem['Bookings'])) {
                 $bookingKeys = $transactionItem['Bookings'];
                 if (!is_array($bookingKeys)) {
                     throw new Exception('"Bookings" property of transaction record must specify an array of internal booking identifiers. Transaction record: ' . json_encode($transactionItem));
                 }
                 $bookingKeys = $this->linkTransactionBookings($transaction, $bookingsByKey, $bookingKeys, $bookingTypeIds, $con);
                 // Remove from orphans list
                 $orphanedBookings = array_diff_key($orphanedBookings, array_fill_keys($bookingKeys, true));
             }
             if (!empty($clockingIds)) {
                 $clockings = ClockingAPI::createClockingQuery($user, $con)->findPks($clockingIds, $con)->getArrayCopy('Id');
                 // Prevents duplicated rows - don't ask why, but this query produces duplicates.
                 $missingClockingIds = array_diff_key(array_fill_keys($clockingIds, true), $clockings);
                 if (!empty($missingClockingIds)) {
                     throw new Exception('Could not find clockings with these IDs: ' . implode(', ', array_keys($missingClockingIds)));
                 }
                 $this->linkTransactionClockings($transaction, $clockings, $con);
                 $resultClockingIds += array_combine($clockingIds, $clockingIds);
             }
             $transactions[] = $transaction;
         }
         if (!empty($orphanedBookings)) {
             throw new Exception('Plugins created ' . count($orphanedBookings) . ' booking(s) not linked to any transactions.');
         }
     } catch (Exception $e) {
         $con->rollBack();
         throw $e;
     }
     if (!$con->commit()) {
         throw new Exception('Could not commit transaction.');
     }
     return array($resultClockingIds, $transactions);
 }
Example #11
0
 public function createFromSignup($data, $referrerMember, \Invitation $invitation = null, \PropelPDO $con)
 {
     // This functions expects this parameter to be valid!
     // E.g. the result from $this->validateSignupForm()
     $now = time();
     if (!$con->beginTransaction()) {
         throw new \Exception('Could not begin transaction');
     }
     try {
         $member = new \Member();
         $member->setFirstName($data['firstName'])->setLastName($data['lastName'])->setEmail($data['email'])->setTitle($data['title'])->setCity($data['city'])->setZipCode($data['zip_code'])->setCountry('India')->setAge($data['age'])->setBankRecipient($data['bank_recipient'])->setIban($data['iban'])->setBic($data['bic'])->setPassword($data['password'])->setSignupDate($now)->setBonusIds('{}')->setPaidDate(null)->setIsExtended(1);
         $member->setHash(\Member::calcHash($member));
         $wasFreeInvitation = false;
         if ($invitation) {
             $invitationType = $invitation->getType();
             $member->setType($invitationType);
             // Special case if e.g. director invites another director.
             // The referrer of the referrer will be the referrer.
             // This is necessary because the same type can not be on same line vertical
             // but horizontal. E.g. Director can have more marketing leader under him
             // but only Directors next to him (NOT under him)
             if ($invitationType > \Member::TYPE_MEMBER && $referrerMember->getType() == $invitationType) {
                 $referrerMember = $referrerMember->getReferrerMember();
             }
             $invitation->setAcceptedDate($now);
             if ($invitation->getFreeSignup()) {
                 $member->setFreeInvitation(1);
                 $wasFreeInvitation = true;
             }
             // Deprecated code
             // if ( $invitation->getType() === \Member::TYPE_SUB_PROMOTER ) {
             //   $member->setSubPromoterReferral($invitation->getMeta()['promoter_id']);
             // }
         }
         $member->setReferrerMember($referrerMember, $con);
         $member->save($con);
         $member->setNum($member->getId() + 1000000);
         if ($invitation) {
             $invitation->setAcceptedMemberId($member->getId());
             $invitation->save($con);
             if ($wasFreeInvitation) {
                 $member->onReceivedMemberFee(\Transaction::$BASE_CURRENCY, $now, true, $con);
             }
         }
         if ($wasFreeInvitation) {
             \Tbmt\MailHelper::sendFreeSignupConfirm($member);
             \Tbmt\MailHelper::sendNewFreeRecruitmentCongrats($referrerMember, $member);
         } else {
             \Tbmt\MailHelper::sendSignupConfirm($member);
             \Tbmt\MailHelper::sendNewRecruitmentCongrats($referrerMember, $member);
         }
         $member->save($con);
         if (!$con->commit()) {
             throw new \Exception('Could not commit transaction');
         }
     } catch (\Exception $e) {
         $con->rollBack();
         throw $e;
     }
     return $member;
 }