YetiForceCompany/YetiForceCRM

View on GitHub
modules/ServiceContracts/handlers/ServiceContractsHandler.php

Summary

Maintainability
C
7 hrs
Test Coverage
F
31%

Function entityAfterSave has a Cognitive Complexity of 26 (exceeds 5 allowed). Consider refactoring.
Open

    public function entityAfterSave(App\EventHandler $eventHandler)
    {
        $moduleName = $eventHandler->getModuleName();
        // Update Used Units for the Service Contract, everytime the status of a ticket related to the Service Contract changes
        if ('HelpDesk' === $moduleName && 'ServiceContracts' !== \App\Request::_get('return_module')) {
Severity: Minor
Found in modules/ServiceContracts/handlers/ServiceContractsHandler.php - About 3 hrs to fix

Cognitive Complexity

Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

A method's cognitive complexity is based on a few simple rules:

  • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
  • Code is considered more complex for each "break in the linear flow of the code"
  • Code is considered more complex when "flow breaking structures are nested"

Further reading

Method entityAfterSave has 55 lines of code (exceeds 25 allowed). Consider refactoring.
Open

    public function entityAfterSave(App\EventHandler $eventHandler)
    {
        $moduleName = $eventHandler->getModuleName();
        // Update Used Units for the Service Contract, everytime the status of a ticket related to the Service Contract changes
        if ('HelpDesk' === $moduleName && 'ServiceContracts' !== \App\Request::_get('return_module')) {
Severity: Major
Found in modules/ServiceContracts/handlers/ServiceContractsHandler.php - About 2 hrs to fix

    The method entityAfterSave() has a Cyclomatic Complexity of 12. The configured cyclomatic complexity threshold is 10.
    Open

        public function entityAfterSave(App\EventHandler $eventHandler)
        {
            $moduleName = $eventHandler->getModuleName();
            // Update Used Units for the Service Contract, everytime the status of a ticket related to the Service Contract changes
            if ('HelpDesk' === $moduleName && 'ServiceContracts' !== \App\Request::_get('return_module')) {

    CyclomaticComplexity

    Since: 0.1

    Complexity is determined by the number of decision points in a method plus one for the method entry. The decision points are 'if', 'while', 'for', and 'case labels'. Generally, 1-4 is low complexity, 5-7 indicates moderate complexity, 8-10 is high complexity, and 11+ is very high complexity.

    Example

    // Cyclomatic Complexity = 11
    class Foo {
    1   public function example() {
    2       if ($a == $b) {
    3           if ($a1 == $b1) {
                    fiddle();
    4           } elseif ($a2 == $b2) {
                    fiddle();
                } else {
                    fiddle();
                }
    5       } elseif ($c == $d) {
    6           while ($c == $d) {
                    fiddle();
                }
    7        } elseif ($e == $f) {
    8           for ($n = 0; $n < $h; $n++) {
                    fiddle();
                }
            } else {
                switch ($z) {
    9               case 1:
                        fiddle();
                        break;
    10              case 2:
                        fiddle();
                        break;
    11              case 3:
                        fiddle();
                        break;
                    default:
                        fiddle();
                        break;
                }
            }
        }
    }

    Source https://phpmd.org/rules/codesize.html#cyclomaticcomplexity

    Refactor this function to reduce its Cognitive Complexity from 26 to the 15 allowed.
    Open

        public function entityAfterSave(App\EventHandler $eventHandler)

    Cognitive Complexity is a measure of how hard the control flow of a function is to understand. Functions with high Cognitive Complexity will be difficult to maintain.

    See

    Missing class import via use statement (line '30', column '24').
    Open

                    $dataReader = (new App\Db\Query())

    MissingImport

    Since: 2.7.0

    Importing all external classes in a file through use statements makes them clearly visible.

    Example

    function make() {
        return new \stdClass();
    }

    Source http://phpmd.org/rules/cleancode.html#MissingImport

    Missing class import via use statement (line '35', column '12').
    Open

                            (new App\Db\Query())

    MissingImport

    Since: 2.7.0

    Importing all external classes in a file through use statements makes them clearly visible.

    Example

    function make() {
        return new \stdClass();
    }

    Source http://phpmd.org/rules/cleancode.html#MissingImport

    Avoid using static access to class 'CRMEntity' in method 'entityAfterSave'.
    Open

                        $scFocus = CRMEntity::getInstance('ServiceContracts');

    StaticAccess

    Since: 1.4.0

    Static access causes unexchangeable dependencies to other classes and leads to hard to test code. Avoid using static access at all costs and instead inject dependencies through the constructor. The only case when static access is acceptable is when used for factory methods.

    Example

    class Foo
    {
        public function bar()
        {
            Bar::baz();
        }
    }

    Source https://phpmd.org/rules/cleancode.html#staticaccess

    The method entityAfterSave uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them.
    Open

                    } else {
                        $op = '+';
                    }

    ElseExpression

    Since: 1.4.0

    An if expression with an else branch is basically not necessary. You can rewrite the conditions in a way that the else clause is not necessary and the code becomes simpler to read. To achieve this, use early return statements, though you may need to split the code it several smaller methods. For very simple assignments you could also use the ternary operations.

    Example

    class Foo
    {
        public function bar($flag)
        {
            if ($flag) {
                // one branch
            } else {
                // another branch
            }
        }
    }

    Source https://phpmd.org/rules/cleancode.html#elseexpression

    Avoid using static access to class 'CRMEntity' in method 'entityAfterSave'.
    Open

                $scFocus = CRMEntity::getInstance('ServiceContracts');

    StaticAccess

    Since: 1.4.0

    Static access causes unexchangeable dependencies to other classes and leads to hard to test code. Avoid using static access at all costs and instead inject dependencies through the constructor. The only case when static access is acceptable is when used for factory methods.

    Example

    class Foo
    {
        public function bar()
        {
            Bar::baz();
        }
    }

    Source https://phpmd.org/rules/cleancode.html#staticaccess

    Avoid using static access to class '\App\Request' in method 'entityAfterSave'.
    Open

            if ('HelpDesk' === $moduleName && 'ServiceContracts' !== \App\Request::_get('return_module')) {

    StaticAccess

    Since: 1.4.0

    Static access causes unexchangeable dependencies to other classes and leads to hard to test code. Avoid using static access at all costs and instead inject dependencies through the constructor. The only case when static access is acceptable is when used for factory methods.

    Example

    class Foo
    {
        public function bar()
        {
            Bar::baz();
        }
    }

    Source https://phpmd.org/rules/cleancode.html#staticaccess

    The method entityAfterSave uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them.
    Open

                        } else {
                            $totalUnits = $prevUsedUnits + $usedUnits;
                        }

    ElseExpression

    Since: 1.4.0

    An if expression with an else branch is basically not necessary. You can rewrite the conditions in a way that the else clause is not necessary and the code becomes simpler to read. To achieve this, use early return statements, though you may need to split the code it several smaller methods. For very simple assignments you could also use the ternary operations.

    Example

    class Foo
    {
        public function bar($flag)
        {
            if ($flag) {
                // one branch
            } else {
                // another branch
            }
        }
    }

    Source https://phpmd.org/rules/cleancode.html#elseexpression

    The method entityAfterSave uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them.
    Open

                } else {
                    $scFocus->id = $contractId;
                    $scFocus->retrieveEntityInfo($contractId, 'ServiceContracts');
                    $scFocus->calculateProgress();
                }

    ElseExpression

    Since: 1.4.0

    An if expression with an else branch is basically not necessary. You can rewrite the conditions in a way that the else clause is not necessary and the code becomes simpler to read. To achieve this, use early return statements, though you may need to split the code it several smaller methods. For very simple assignments you could also use the ternary operations.

    Example

    class Foo
    {
        public function bar($flag)
        {
            if ($flag) {
                // one branch
            } else {
                // another branch
            }
        }
    }

    Source https://phpmd.org/rules/cleancode.html#elseexpression

    Define a constant instead of duplicating this literal "Closed" 3 times.
    Open

                if ($status != $oldStatus && ('Closed' === $status || 'Closed' === $oldStatus)) {

    Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.

    On the other hand, constants can be referenced from many places, but only need to be updated in a single place.

    Noncompliant Code Example

    With the default threshold of 3:

    function run() {
      prepare('action1');                              // Non-Compliant - 'action1' is duplicated 3 times
      execute('action1');
      release('action1');
    }
    

    Compliant Solution

    ACTION_1 = 'action1';
    
    function run() {
      prepare(ACTION_1);
      execute(ACTION_1);
      release(ACTION_1);
    }
    

    Exceptions

    To prevent generating some false-positives, literals having less than 5 characters are excluded.

    Define a constant instead of duplicating this literal "ServiceContracts" 8 times.
    Open

            if ('HelpDesk' === $moduleName && 'ServiceContracts' !== \App\Request::_get('return_module')) {

    Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.

    On the other hand, constants can be referenced from many places, but only need to be updated in a single place.

    Noncompliant Code Example

    With the default threshold of 3:

    function run() {
      prepare('action1');                              // Non-Compliant - 'action1' is duplicated 3 times
      execute('action1');
      release('action1');
    }
    

    Compliant Solution

    ACTION_1 = 'action1';
    
    function run() {
      prepare(ACTION_1);
      execute(ACTION_1);
      release(ACTION_1);
    }
    

    Exceptions

    To prevent generating some false-positives, literals having less than 5 characters are excluded.

    Define a constant instead of duplicating this literal "HelpDesk" 3 times.
    Open

            if ('HelpDesk' === $moduleName && 'ServiceContracts' !== \App\Request::_get('return_module')) {

    Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.

    On the other hand, constants can be referenced from many places, but only need to be updated in a single place.

    Noncompliant Code Example

    With the default threshold of 3:

    function run() {
      prepare('action1');                              // Non-Compliant - 'action1' is duplicated 3 times
      execute('action1');
      release('action1');
    }
    

    Compliant Solution

    ACTION_1 = 'action1';
    
    function run() {
      prepare(ACTION_1);
      execute(ACTION_1);
      release(ACTION_1);
    }
    

    Exceptions

    To prevent generating some false-positives, literals having less than 5 characters are excluded.

    Call to undeclared method \CRMEntity::updateServiceContractState
    Open

                    $scFocus->updateServiceContractState($contractId);

    Reference to undeclared property \CRMEntity->column_fields
    Open

                        $prevUsedUnits = $scFocus->column_fields['used_units'];

    Reference to undeclared property \CRMEntity->id
    Open

                        $scFocus->id = $contractId;

    Call to undeclared method \CRMEntity::calculateProgress
    Open

                    $scFocus->calculateProgress();

    Call to undeclared method \App\Db\Query::select
    Open

                    $dataReader = (new App\Db\Query())

    Call to undeclared method \CRMEntity::computeUsedUnits
    Open

                        $usedUnits = $scFocus->computeUsedUnits($recordModel->getData());

    Reference to undeclared property \CRMEntity->id
    Open

                    $scFocus->id = $contractId;

    Call to undeclared method \App\Db\Query::select
    Open

                            (new App\Db\Query())

    Call to undeclared method \CRMEntity::updateUsedUnits
    Open

                        $scFocus->updateUsedUnits($totalUnits);

    Call to undeclared method \CRMEntity::calculateProgress
    Open

                        $scFocus->calculateProgress();

    Similar blocks of code found in 2 locations. Consider refactoring.
    Open

                    $dataReader = (new App\Db\Query())
                        ->select(['crmid'])
                        ->from('vtiger_crmentityrel')
                        ->where(['module' => 'ServiceContracts', 'relmodule' => 'HelpDesk', 'relcrmid' => $ticketId])
                        ->union(
    modules/ServiceContracts/ServiceContracts.php on lines 144..150

    Duplicated Code

    Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:

    Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

    When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).

    Tuning

    This issue has a mass of 103.

    We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.

    The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.

    If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.

    See codeclimate-duplication's documentation for more information about tuning the mass threshold in your .codeclimate.yml.

    Refactorings

    Further Reading

    Avoid excessively long class names like ServiceContracts_ServiceContractsHandler_Handler. Keep class name length under 40.
    Open

    class ServiceContracts_ServiceContractsHandler_Handler
    {
        /**
         * EntityAfterSave handler function.
         *

    LongClassName

    Since: 2.9

    Detects when classes or interfaces are declared with excessively long names.

    Example

    class ATooLongClassNameThatHintsAtADesignProblem {
    
    }
    
    interface ATooLongInterfaceNameThatHintsAtADesignProblem {
    
    }

    Source https://phpmd.org/rules/naming.html#longclassname

    Each class must be in a namespace of at least one level (a top-level vendor name)
    Open

    class ServiceContracts_ServiceContractsHandler_Handler

    Avoid variables with short names like $op. Configured minimum length is 3.
    Open

                        $op = '-';

    ShortVariable

    Since: 0.2

    Detects when a field, local, or parameter has a very short name.

    Example

    class Something {
        private $q = 15; // VIOLATION - Field
        public static function main( array $as ) { // VIOLATION - Formal
            $r = 20 + $this->q; // VIOLATION - Local
            for (int $i = 0; $i < 10; $i++) { // Not a Violation (inside FOR)
                $r += $this->q;
            }
        }
    }

    Source https://phpmd.org/rules/naming.html#shortvariable

    The class ServiceContracts_ServiceContractsHandler_Handler is not named in CamelCase.
    Open

    class ServiceContracts_ServiceContractsHandler_Handler
    {
        /**
         * EntityAfterSave handler function.
         *

    CamelCaseClassName

    Since: 0.2

    It is considered best practice to use the CamelCase notation to name classes.

    Example

    class class_name {
    }

    Source

    Line exceeds 120 characters; contains 127 characters
    Open

            // Update Used Units for the Service Contract, everytime the status of a ticket related to the Service Contract changes

    Spaces must be used to indent lines; tabs are not allowed
    Open

                        $scFocus = CRMEntity::getInstance('ServiceContracts');

    Spaces must be used to indent lines; tabs are not allowed
    Open

                    }

    Spaces must be used to indent lines; tabs are not allowed
    Open

                $contractId = $recordModel->getId();

    Spaces must be used to indent lines; tabs are not allowed
    Open

                if ($recordModel->get('tracking_unit') !== $recordModel->getPreviousValue('tracking_unit')) { // Need to recompute used_units based when tracking_unit changes.

    Line exceeds 120 characters; contains 171 characters
    Open

                if ($recordModel->get('tracking_unit') !== $recordModel->getPreviousValue('tracking_unit')) { // Need to recompute used_units based when tracking_unit changes.

    Spaces must be used to indent lines; tabs are not allowed
    Open

                    $scFocus->retrieveEntityInfo($contractId, 'ServiceContracts');

    Spaces must be used to indent lines; tabs are not allowed
    Open

                $ticketId = $recordModel->getId();

    Spaces must be used to indent lines; tabs are not allowed
    Open

                    while ($contractId = $dataReader->readColumn(0)) {

    Spaces must be used to indent lines; tabs are not allowed
    Open

                        } else {

    Spaces must be used to indent lines; tabs are not allowed
    Open

                    }

    Spaces must be used to indent lines; tabs are not allowed
    Open

                                ->from('vtiger_crmentityrel')

    Spaces must be used to indent lines; tabs are not allowed
    Open

                        $scFocus->id = $contractId;

    Spaces must be used to indent lines; tabs are not allowed
    Open

        public function entityAfterSave(App\EventHandler $eventHandler)

    Spaces must be used to indent lines; tabs are not allowed
    Open

                $scFocus = CRMEntity::getInstance('ServiceContracts');

    Spaces must be used to indent lines; tabs are not allowed
    Open

        /**

    Spaces must be used to indent lines; tabs are not allowed
    Open

         */

    Spaces must be used to indent lines; tabs are not allowed
    Open

            // Update Used Units for the Service Contract, everytime the status of a ticket related to the Service Contract changes

    Spaces must be used to indent lines; tabs are not allowed
    Open

                    if ('Closed' === $oldStatus) {

    Spaces must be used to indent lines; tabs are not allowed
    Open

                            $totalUnits = $prevUsedUnits - $usedUnits;

    Spaces must be used to indent lines; tabs are not allowed
    Open

                    $scFocus->id = $contractId;

    Spaces must be used to indent lines; tabs are not allowed
    Open

         *

    Spaces must be used to indent lines; tabs are not allowed
    Open

                $oldStatus = $recordModel->getPreviousValue('ticketstatus');

    Spaces must be used to indent lines; tabs are not allowed
    Open

                        ->union(

    Spaces must be used to indent lines; tabs are not allowed
    Open

                                ->select(['relcrmid'])

    Spaces must be used to indent lines; tabs are not allowed
    Open

                        ->createCommand()->query();

    Spaces must be used to indent lines; tabs are not allowed
    Open

                        $prevUsedUnits = $scFocus->column_fields['used_units'];

    Spaces must be used to indent lines; tabs are not allowed
    Open

            $moduleName = $eventHandler->getModuleName();

    Spaces must be used to indent lines; tabs are not allowed
    Open

            if ('HelpDesk' === $moduleName && 'ServiceContracts' !== \App\Request::_get('return_module')) {

    Spaces must be used to indent lines; tabs are not allowed
    Open

                $recordModel = $eventHandler->getRecordModel();

    Spaces must be used to indent lines; tabs are not allowed
    Open

                if ($status != $oldStatus && ('Closed' === $status || 'Closed' === $oldStatus)) {

    Spaces must be used to indent lines; tabs are not allowed
    Open

                        ->from('vtiger_crmentityrel')

    Spaces must be used to indent lines; tabs are not allowed
    Open

                    $dataReader->close();

    Spaces must be used to indent lines; tabs are not allowed
    Open

                $recordModel = $eventHandler->getRecordModel();

    Spaces must be used to indent lines; tabs are not allowed
    Open

                    $scFocus->calculateProgress();

    Spaces must be used to indent lines; tabs are not allowed
    Open

                }

    Spaces must be used to indent lines; tabs are not allowed
    Open

        }

    Spaces must be used to indent lines; tabs are not allowed
    Open

        {

    Spaces must be used to indent lines; tabs are not allowed
    Open

                $status = $recordModel->get('ticketstatus');

    Spaces must be used to indent lines; tabs are not allowed
    Open

                        $op = '+';

    Spaces must be used to indent lines; tabs are not allowed
    Open

                        $usedUnits = $scFocus->computeUsedUnits($recordModel->getData());

    Spaces must be used to indent lines; tabs are not allowed
    Open

                        if ('-' === $op) {

    Spaces must be used to indent lines; tabs are not allowed
    Open

                            $totalUnits = $prevUsedUnits + $usedUnits;

    Spaces must be used to indent lines; tabs are not allowed
    Open

                        ->select(['crmid'])

    Spaces must be used to indent lines; tabs are not allowed
    Open

                        ->where(['module' => 'ServiceContracts', 'relmodule' => 'HelpDesk', 'relcrmid' => $ticketId])

    Spaces must be used to indent lines; tabs are not allowed
    Open

                                ->where(['relmodule' => 'ServiceContracts', 'module' => 'HelpDesk', 'crmid' => $ticketId])

    Spaces must be used to indent lines; tabs are not allowed
    Open

                        $scFocus->retrieveEntityInfo($contractId, 'ServiceContracts');

    Spaces must be used to indent lines; tabs are not allowed
    Open

                        $scFocus->updateUsedUnits($totalUnits);

    Spaces must be used to indent lines; tabs are not allowed
    Open

                        $op = '-';

    Spaces must be used to indent lines; tabs are not allowed
    Open

                        )

    Spaces must be used to indent lines; tabs are not allowed
    Open

                        if (empty($prevUsedUnits)) {

    Spaces must be used to indent lines; tabs are not allowed
    Open

                        }

    Spaces must be used to indent lines; tabs are not allowed
    Open

         * @param App\EventHandler $eventHandler

    Spaces must be used to indent lines; tabs are not allowed
    Open

                    $dataReader = (new App\Db\Query())

    Spaces must be used to indent lines; tabs are not allowed
    Open

            }

    Spaces must be used to indent lines; tabs are not allowed
    Open

            // Update the Planned Duration, Actual Duration, End Date and Progress based on other field values.

    Spaces must be used to indent lines; tabs are not allowed
    Open

                    $scFocus->updateServiceContractState($contractId);

    Spaces must be used to indent lines; tabs are not allowed
    Open

                } else {

    Spaces must be used to indent lines; tabs are not allowed
    Open

                            (new App\Db\Query())

    Spaces must be used to indent lines; tabs are not allowed
    Open

                        }

    Spaces must be used to indent lines; tabs are not allowed
    Open

            if ('ServiceContracts' === $moduleName) {

    Spaces must be used to indent lines; tabs are not allowed
    Open

                        $scFocus->calculateProgress();

    Spaces must be used to indent lines; tabs are not allowed
    Open

            }

    Spaces must be used to indent lines; tabs are not allowed
    Open

         * EntityAfterSave handler function.

    Spaces must be used to indent lines; tabs are not allowed
    Open

                    } else {

    Spaces must be used to indent lines; tabs are not allowed
    Open

                            $prevUsedUnits = 0;

    Spaces must be used to indent lines; tabs are not allowed
    Open

                }

    Class name "ServiceContracts_ServiceContractsHandler_Handler" is not in camel caps format
    Open

    class ServiceContracts_ServiceContractsHandler_Handler

    There are no issues that match your filters.

    Category
    Status