Completed
Push — master ( 367b93...f210fc )
by Hector
01:52
created

analytics.php ➔ dateRanges()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 16
nc 6
nop 2
dl 0
loc 23
rs 8.7972
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 103 and the first side effect is on line 11.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
use Hborras\TwitterAdsSDK\TwitterAds;
4
use Hborras\TwitterAdsSDK\TwitterAds\Account;
5
use Hborras\TwitterAdsSDK\TwitterAds\Analytics;
6
use Hborras\TwitterAdsSDK\TwitterAds\Campaign\Campaign;
7
use Hborras\TwitterAdsSDK\TwitterAds\Campaign\LineItem;
8
use Hborras\TwitterAdsSDK\TwitterAds\Enumerations;
9
use Hborras\TwitterAdsSDK\TwitterAds\Fields\AnalyticsFields;
10
11
require '../autoload.php';
12
13
const CONSUMER_KEY = 'your consumer key';
14
const CONSUMER_SECRET = 'your consumer secret';
15
const ACCESS_TOKEN = 'your access token';
16
const ACCESS_TOKEN_SECRET = 'your access token secret';
17
const ACCOUNT_ID = 'account id';
18
19
// Create Twitter Ads Api Instance
20
$api = TwitterAds::init(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
21
22
$accounts = $api->getAccounts();
23
// load up the account instance, campaign and line item
24
$account = new Account(ACCOUNT_ID);
25
$account->read();
26
$campaigns = $account->getCampaigns('', [TwitterAds\Fields\CampaignFields::COUNT => 1]);
27
$campaigns->setUseImplicitFetch(false);
0 ignored issues
show
Bug introduced by
The method setUseImplicitFetch does only exist in Hborras\TwitterAdsSDK\TwitterAds\Cursor, but not in Hborras\TwitterAdsSDK\TwitterAds\Campaign\Campaign.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
28
$campaignsData = [];
29
30
31
/** @var Campaign $campaign */
32
foreach ($campaigns as $campaign) {
0 ignored issues
show
Bug introduced by
The expression $campaigns of type object<Hborras\TwitterAd...sSDK\TwitterAds\Cursor> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
33
    $campaignsData[] = $campaign;
34
}
35
36
$i = 1;
37
$j = 1;
38
$l = 1;
39
foreach ($campaignsData as $campaign) {
40
    echo $i . ": " . $campaign->getId() . " " . $campaign->getName() . " " . $campaign->getStartTime()->format('Y-m-d') . " - " . $campaign->getEntityStatus() . PHP_EOL;
41
    $lineItems = $campaign->getLineItems();
42
    /** @var LineItem $lineItem */
43
    foreach ($lineItems as $lineItem) {
44
        echo "\t" . $j . ": " . $lineItem->getId() . " " . $lineItem->getName() . " " . PHP_EOL;
45
        echo "\t\tBid: " . ($lineItem->getBidAmountLocalMicro() / 1000000) . PHP_EOL;
46
        echo "\t\tObjective: " . $lineItem->getObjective() . PHP_EOL;
47
        echo "\t\tCharge By: " . $lineItem->getChargeBy() . PHP_EOL;
48
        echo "\t\tBid Unit: " . $lineItem->getBidUnit() . PHP_EOL;
49
        echo "\t\tOptimization: " . $lineItem->getOptimization() . PHP_EOL;
50
        echo "\t\tBid Type: " . $lineItem->getBidType() . PHP_EOL;
51
        $targetingCriterias = $lineItem->getTargetingCriteria();
52
        /** @var TwitterAds\Campaign\TargetingCriteria $targetingCriteria */
53
        foreach ($targetingCriterias as $targetingCriteria) {
54
            echo "\t\t" . $l . ": " . $targetingCriteria->getId() . " " . $targetingCriteria->getName() . " " .
55
56
                $targetingCriteria->getTargetingType() . " " . $targetingCriteria->getTargetingValue() . PHP_EOL;
57
58
            $l++;
59
        }
60
        $l = 1;
61
        try {
62
            $startDate = new \DateTime($campaign->getStartTime()->format('Y-m-d 00:00:00'));
63
            $endDate = new \DateTime('now');
64
            $dates = dateRanges($startDate, $endDate);
65
            foreach ($dates as $date) {
66
                $stats = $lineItem->stats(
67
                    [
68
                        TwitterAds\Fields\AnalyticsFields::METRIC_GROUPS_BILLING,
69
                        TwitterAds\Fields\AnalyticsFields::METRIC_GROUPS_MOBILE_CONVERSION,
70
                        TwitterAds\Fields\AnalyticsFields::METRIC_GROUPS_ENGAGEMENT,
71
                    ],
72
                    [
73
                        TwitterAds\Fields\AnalyticsFields::START_TIME => $date[0],
74
                        AnalyticsFields::END_TIME => $date[1],
75
                        AnalyticsFields::GRANULARITY => Enumerations::GRANULARITY_TOTAL,
76
                        AnalyticsFields::PLACEMENT => Enumerations::PLACEMENT_ALL_ON_TWITTER
77
                    ], true
78
                );
79
                $stats = $stats[0]->id_data[0]->metrics;
80
                if (!is_null($stats->billed_charge_local_micro)) {
81
                    echo "\t\t\t Start: " . $date[0]->format('Y-m-d H:i:s') . PHP_EOL;
82
                    echo "\t\t\t End: " . $date[1]->format('Y-m-d H:i:s') . PHP_EOL;
83
                    echo "\t\t\t " . ($stats->billed_charge_local_micro[0] / 1000000) . "€" . PHP_EOL;
84
                    echo "\t\t\t\t App clicks: ";
85
                    getStats($stats->app_clicks);
86
                    echo "\t\t\t\t Installs:" . PHP_EOL;
87
                    getStats($stats->mobile_conversion_installs);
88
                    echo "\t\t\t\t Checkouts:" . PHP_EOL;
89
                    getStats($stats->mobile_conversion_checkouts_initiated);
90
                }
91
            }
92
93
        } catch (\Hborras\TwitterAdsSDK\TwitterAdsException $e) {
94
            print_r($e->getErrors());
95
        }
96
97
        $j++;
98
    }
99
    $j = 1;
100
    $i++;
101
}
102
103
function getStats($stat)
104
{
105
    if ($stat instanceof stdClass) {
106
        foreach (get_object_vars($stat) as $key => $val) {
107
            if (is_array($val)) {
108
                echo "\t\t\t\t\t " . $key . ": " . $val[0] . PHP_EOL;
109
            } else {
110
                echo "\t\t\t\t\t " . $key . " 0" . PHP_EOL;
111
            }
112
        }
113
    } else if (is_array($stat)) {
114
        foreach ($stat as $s) {
115
            echo $s . PHP_EOL;
116
        }
117
    }
118
119
}
120
121
/**
122
 * @param $startTime
123
 * @param $endTime
124
 * @return array
125
 */
126
function dateRanges($startTime, $endTime)
127
{
128
    $interval = new \DateInterval('P7D');
129
    $dateRange = new \DatePeriod($startTime, $interval, $endTime);
130
131
    $previous = null;
132
    $dates = array();
133
    foreach ($dateRange as $dt) {
134
        $current = $dt;
135
        if (!empty($previous)) {
136
            $show = $current;
137
            $dates[] = array($previous, $show);
138
        }
139
        $previous = $current;
140
    }
141
    if (isset($dates[count($dates) - 1])) {
142
        $dates[] = array($dates[count($dates) - 1][1], $endTime);
143
    } else {
144
        $dates[] = array($startTime, $endTime);
145
    }
146
147
    return $dates;
148
}